matlab里有个confusionmat函数
接口是这样的
M = confusionmat(true_label,predict_label)
M计算出来是下面这样
比如第一个class airplane吧,923意思是true class是airplane, 而我们预测的label也是airplane的个数
而第一行第二列的4就表示true class是airplane, 而我们预测的label是automobile的个数是4
那么就相当于对角线上蓝色背景的都是预测对的
如果是2分类的情况,true class是0,1,假设1是positive
那么TP的个数就是M(2,2)
SE 即TPR= TP / (TP+FN) , 同时也是recall (TPR: true positive rate)
SP 即TNR= TN / (TN+FP) (TNR: true negative rate)
F1 score = 2 * (precision * recall) / (precision + recall)
precision = TP / (TP + FP), 即PPV(positive predictive value)
function [score, TPR, TNR] = f1_score(label, predict)
M = confusionmat(label, predict);
#以下两行为二分类时用
TPR = M(2,2) / (M(2,1) + M(2,2)); #SE: TP/(TP+FN)
TNR = M(1,1) / (M(1,1) + M(1,2)); #SP: TN/(TN+FP)
#转置,可以不转同时调换方向
M = M';
precision = diag(M)./(sum(M,2) + 0.0001); #按列求和: TP/(TP+FP)
recall = diag(M)./(sum(M,1)+0.0001)'; #按行求和: TP/(TP+FN)
precision = mean(precision);
recall = mean(recall);
score = 2*precision*recall/(precision + recall);
end