在matlab中使用fitcsvm进行分类会产生错误

时间:2017-06-04 17:19:25

标签: matlab classification svm

我曾尝试过以下代码

clear all;close all;
data =  [27 9   2
11.6723281  28.93422177 2
25  9   2
23  8   2
5.896096039 23.97745722 1
21  6   2
21.16823369 5.292058423 2
4.242640687 13.43502884 1
22  6   2];
Attributes = data(:,1:2);
Classes = data(:,3);
train = [1 3 4 5 6 7];
testInds = [2 8 9];
test1 = data(testInds,1:2);
YTest =data(testInds,3);
%%# Train
svmStruct = svmtrain(Attributes(train,:),Classes(train),'ShowPlot',true);

 SVMModel = fitcsvm(Attributes(train,:),Classes(train))
 classOrder = SVMModel.ClassNames
sv = SVMModel.SupportVectors;
figure
gscatter(data(:,1),data(:,2),Classes)
hold on
plot(sv(:,1), sv(:,2),'ko','MarkerSize',10)
legend('good','bad','Support Vector')
hold off
[label,score] = predict(SVMModel,test1);
% [predict_label, accuracy, prob_estimates] = predict(SVMModel,test1)
table(YTest(1:2),label(1:2),score(1:10,2),'VariableNames',...
    {'TrueLabel','PredictedLabel','Score'})

我尝试了上面的代码。前两列是我的数据,最后一列是组ID。 SVMModel是分类。我收到错误

指数超出矩阵维度。

无标题错误(第34行) 表(YTest(1:2),标记(1:2),分(1:10,2),' VariableNames',... 我试着测试一个实例。但是这两个语句都会产生错误

[label,score] = predict(SVMModel,test);
 label           = svmclassify(SVMModel, test);

1 个答案:

答案 0 :(得分:1)

您只需翻转预测变量和标签 - 它是fitcsvm(predictors,labels),或者在您的情况下fitcsvm(Attributes(train,:),Classes(train))

编辑:

plot(sv(:,1), sv(:,2),'ko','MarkerSize',10) % you obviously do not want to plot the same data twice in the same plot...

对于预测:[predict_label, accuracy, prob_estimates] = svmpredict(Classes(test), Attributes(test,:), SVMModel);看起来很好。