Search code examples
matlabknnconfusion-matrixprecision-recall

Is there any function to calculate Precision and Recall using Matlab?


I have problem about calculating the precision and recall for classifier in matlab. I use fisherIris data (that consists of 150 datapoints, 50-setosa, 50-versicolor, 50-virginica). I have classified using kNN algorithm. Here is my confusion matrix:

50     0     0
 0    48     2
 0     4    46

correct classification rate is 96% (144/150), but how to calculate precision and recall using matlab, is there any function? I know the formulas for that precision=tp/(tp+fp),and recall=tp/(tp+fn), but I am lost in identifying components. For instance, can I say that true positive is 144 from the matrix? what about false positive and false negative? Please help!!! I would really appreciate! Thank you!


Solution

  • To add to pederpansen's answer, here are some anonymous Matlab functions for calculating precision, recall and F1-score for each class, and the mean F1 score over all classes:

    precision = @(confusionMat) diag(confusionMat)./sum(confusionMat,2);
    
    recall = @(confusionMat) diag(confusionMat)./sum(confusionMat,1)';
    
    f1Scores = @(confusionMat) 2*(precision(confusionMat).*recall(confusionMat))./(precision(confusionMat)+recall(confusionMat))
    
    meanF1 = @(confusionMat) mean(f1Scores(confusionMat))