MATLAB:如何找到k-NN分类后的混淆矩阵?

MATLAB: How to find the confusion matrix after k-NN classification?

我正在 MATLAB 上进行模式识别项目。我正在研究 Fisher Iris 数据集。我已经编写了一些适用于 k-NN 分类的代码,完成分类后我想计算混淆矩阵。我所有的尝试都失败了。所以,我请求你帮助找到计算混淆矩阵 C 的方法。

相关部分代码如下:

fold_number = 5;
indices = crossvalind('Kfold',species, fold_number);

val = 1:2:5; % for these small k values there will not be an important difference
         % regarding the cp ErrorRates. The difference is going to be
         % observable for val = 1:2:100, for example!!! But the
         % exercise asks only for k = 1,3,5.

err_arr = [];

for k=val

    cp = classperf(species); % Reinitialize the cp-structure!

    for i = 1:fold_number
        test = (indices == i); 
        train = ~test;
        class = knnclassify(meas(test,:),meas(train,:),species(train), k);
        %class = knnclassify(meas(test,2),meas(train,2),species(train), k); % To experiment only with the 2nd feature

        classperf(cp,class,test);
    end
    err_arr = [err_arr; cp.ErrorRate];
    fprintf('The k-NN classification error rate for k = %d is: %f\n', k,cp.ErrorRate);
end  

fprintf('\n The error array is: \n');
disp(err_arr);

期待您的回答!

如果您有权访问统计和机器学习工具箱,则只需使用 confusionmat function。它 returns 混淆矩阵 C 如果您将已知分类 (knownGroups) 和您的 k-nn 输出(在您的示例中由 class 给出的预测分类)作为输入:

[C] = confusionmat(knownGroups,class)