10

您能否举一个在 matlab 中使用支持向量机 (SVM) 对 4 个类进行分类的示例,例如:

atribute_1  atribute_2 atribute_3 atribute_4 class
1           2          3           4             0
1           2          3           5             0
0           2          6           4             1
0           3          3           8             1
7           2          6           4             2
9           1          7           10            3
4

2 回答 2

25

SVM 最初是为二进制分类而设计的。然后它们被扩展为处理多类问题。这个想法是将问题分解为许多二元类问题,然后将它们组合起来以获得预测。

一种称为one-against-all 的方法,构建与类一样多的二元分类器,每个分类器都经过训练以将一个类与其他类分开。为了预测一个新实例,我们选择具有最大决策函数值的分类器。

另一种称为一对一的方法(我相信它在 LibSVM 中使用),构建k(k-1)/2二进制分类器,经过训练以将每对类彼此分开,并使用多数投票方案(最大获胜策略)来确定输出预测.

还有其他方法,例如使用纠错输出码 (ECOC)来构建许多有些冗余的二进制分类器,并使用这种冗余来获得更稳健的分类(使用与汉明码相同的想法)。

示例(一对一):

%# load dataset
load fisheriris
[g gn] = grp2idx(species);                      %# nominal class to numeric

%# split training/testing sets
[trainIdx testIdx] = crossvalind('HoldOut', species, 1/3);

pairwise = nchoosek(1:length(gn),2);            %# 1-vs-1 pairwise models
svmModel = cell(size(pairwise,1),1);            %# store binary-classifers
predTest = zeros(sum(testIdx),numel(svmModel)); %# store binary predictions

%# classify using one-against-one approach, SVM with 3rd degree poly kernel
for k=1:numel(svmModel)
    %# get only training instances belonging to this pair
    idx = trainIdx & any( bsxfun(@eq, g, pairwise(k,:)) , 2 );

    %# train
    svmModel{k} = svmtrain(meas(idx,:), g(idx), ...
        'BoxConstraint',2e-1, 'Kernel_Function','polynomial', 'Polyorder',3);

    %# test
    predTest(:,k) = svmclassify(svmModel{k}, meas(testIdx,:));
end
pred = mode(predTest,2);   %# voting: clasify as the class receiving most votes

%# performance
cmat = confusionmat(g(testIdx),pred);
acc = 100*sum(diag(cmat))./sum(cmat(:));
fprintf('SVM (1-against-1):\naccuracy = %.2f%%\n', acc);
fprintf('Confusion Matrix:\n'), disp(cmat)

这是一个示例输出:

SVM (1-against-1):
accuracy = 93.75%
Confusion Matrix:
    16     0     0
     0    14     2
     0     1    15
于 2011-02-12T19:17:07.380 回答
14

MATLAB 目前不支持多类 SVM。您可以使用svmtrain(2-classes) 来实现这一点,但使用标准 SVM 包会容易得多。

我使用过LIBSVM并且可以确认它非常易于使用。


%%# Your data
D = [
1           2          3           4             0
1           2          3           5             0
0           2          6           4             1
0           3          3           8             1
7           2          6           4             2
9           1          7           10            3];
%%# For clarity
Attributes = D(:,1:4);
Classes = D(:,5);
train = [1 3 5 6];
test = [2 4];

%%# Train
model = svmtrain(Classes(train),Attributes(train,:),'-s 0 -t 2');

%%# Test
[predict_label, accuracy, prob_estimates] = svmpredict(Classes(test), Attributes(test,:), model);
于 2011-02-12T05:45:15.730 回答