cMi*_*nor 10 matlab artificial-intelligence classification machine-learning svm
你能举一个在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
Run Code Online (Sandbox Code Playgroud)
Amr*_*mro 25
SVM最初设计用于二进制分类.然后他们被扩展到处理多类问题.我们的想法是将问题分解为许多二元类问题,然后将它们组合起来以获得预测.
一种叫做一对一的方法,就像有类一样构建尽可能多的二元分类器,每种方法都训练将一个类与其余类分开.为了预测新实例,我们选择具有最大决策函数值的分类器.
另一种称为一对一的方法(我相信在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)
Run Code Online (Sandbox Code Playgroud)
这是一个示例输出:
SVM (1-against-1):
accuracy = 93.75%
Confusion Matrix:
16 0 0
0 14 2
0 1 15
Run Code Online (Sandbox Code Playgroud)
Jac*_*cob 14
MATLAB目前不支持多类SVM.您可以使用svmtrain(2个类)来实现此目的,但使用标准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);
Run Code Online (Sandbox Code Playgroud)