如何使用Matlab实现KNN并计算百分比准确度

时间:2016-05-22 05:09:29

标签: matlab matrix percentage knn

我是使用matlab的新手,我的目标是实现knn,我有两个不同的txt文件,一个包含测试数据(样本),另一个包含训练数据。

到目前为止,我认为我应该这样做,但我不知道该怎么做。

load fisheriris 
x = meas(:,3:4);
gscatter(x(:,1),x(:,2),species)
newpoint = [5 1.45];
[n,d] = knnsearch(x,newpoint,'k',10);
line(x(n,1),x(n,2),'color',[.5 .5 .5],'marker','o','linestyle','none','markersize',10)

或者这可能是一种更简单的方法,对我而言,非常清楚两组不同的数据,样本和训练,但这并没有显示预测类的准确性。

 A= [50, 60;
    7,2;
    13,12;
    100,200;];
B=[1,0;
    200,30;
    19,10];
G={'First Row';
    'Second Row';
    'Third Row'};
class = knnclassify(A,B,G);

disp('Result: ');
disp(class);

矩阵看起来像这样:

Training data:
148.0,50.0,0
187.0,34.0,0
204.0,89.0,0
430.0,161.0,1
427.0,22.0,1
-42.0,469.0,1
more,more,class....

Test data:
290.0,-57.0,0
194.0,-80.0,0
174.0,33.0,0
465.0,691.0,1
270.0,-194.0,1
-56.0,665.0,1
more,more,class....

如何使用knn对此数据进行分类并显示每行的预测,以便计算准确度百分比?

-------EDITED------

我忘了,如果我需要每节课的准确性,我该怎么办?

1 个答案:

答案 0 :(得分:1)

以下是使用knnclassify

的更新代码
trainData= [148.0,50.0,0; ...
            187.0,34.0,0; ...
            204.0,89.0,0; ...
            430.0,161.0,1; ...
            427.0,22.0,1; ...
            -42.0,469.0,1 ...
            ];

testData=   [290.0,-57.0,0; ...
            194.0,-80.0,0; ...
            174.0,33.0,0; ...
            465.0,691.0,1; ...
            270.0,-194.0,1; ...
            -56.0,665.0,1];

% Data
Sample=testData(:,1:2);
Training=trainData(:,1:2);
Group=trainData(:,3);

% Classify
k=1;  % number of nearest neighbors used in the classification
Class = knnclassify(Sample, Training, Group,k);

% Display Prediction
fprintf('%.1f %.1f - Real %d , Predicted %d\n',[testData.'; Class.']);

% Calculate percentage accuracy for each class
trueClass=testData(:,3);
classList=unique(trueClass);
for classIndex=1:length(classList)
    indexesOfEachClass=find(trueClass==classList(classIndex));
    percentageAccuracyEachClass(classIndex,1)=sum(Class(indexesOfEachClass)==trueClass(indexesOfEachClass))/length(indexesOfEachClass)*100;
end
fprintf('\nClass %d Accuracy : %f%%',[classList.'; percentageAccuracyEachClass.']);

% Calculate overall percentage accuracy 
dataClassifiedAccurately=Class==trueClass;
percentageAccuracy=sum(dataClassifiedAccurately)/length(dataClassifiedAccurately)*100;
fprintf('\n\nOverall Accuracy : %f%%\n',percentageAccuracy);