如果您的 label_true 仅包含 true 值,则您只能找到真阳性 (TP) 和假阴性 (FN),因为没有可以找到的假值(真阴性 TN)或遗漏(假阳性) FP)
TP,TN,FP,FN 适用于二分类问题。要么分析整个混淆矩阵,要么进行分箱以获得二元问题
这是一个分箱解决方案:
from collections import Counter
truth = [1, 2, 1, 2, 1, 1, 1, 2, 1, 3, 4, 1]
prediction = [1, 1, 2, 1, 1, 2, 1, 2, 1, 4, 4, 3]
confusion_matrix = Counter()
#say class 1, 3 are true; all other classes are false
positives = [1, 3]
binary_truth = [x in positives for x in truth]
binary_prediction = [x in positives for x in prediction]
print binary_truth
print binary_prediction
for t, p in zip(binary_truth, binary_prediction):
confusion_matrix[t,p] += 1
print "TP: {} TN: {} FP: {} FN: {}".format(confusion_matrix[True,True], confusion_matrix[False,False], confusion_matrix[False,True], confusion_matrix[True,False])
编辑:这是一个完整的混淆矩阵
from collections import Counter
truth = [1, 2, 1, 2, 1, 1, 1, 2, 1, 3, 4, 1]
prediction = [1, 1, 2, 1, 1, 2, 1, 2, 1, 4, 4, 3]
# make confusion matrix
confusion_matrix = Counter()
for t, p in zip(truth, prediction):
confusion_matrix[t,p] += 1
# print confusion matrix
labels = set(truth + prediction)
print "t/p",
for p in sorted(labels):
print p,
print
for t in sorted(labels):
print t,
for p in sorted(labels):
print confusion_matrix[t,p],
print