【发布时间】:2017-04-05 10:06:10
【问题描述】:
【问题讨论】:
标签: python-3.x machine-learning
【问题讨论】:
标签: python-3.x machine-learning
首先,您的矩阵是颠倒排列的。 您想要排列标签,以便在对角线 [(0,0),(1,1),(2,2)] 上设置真正的正数,这是您将使用生成的混淆矩阵找到的排列sklearn 和其他软件包。
一旦我们把事情按正确的方向排序,我们就可以从this answer 中获取一个页面并说:
\ 然后我们从 sklearn docs 中获取一些公式来进行精度和召回。 并将其全部放入代码中:
import numpy as np
cm = np.array([[2,1,0], [3,4,5], [6,7,8]])
true_pos = np.diag(cm)
false_pos = np.sum(cm, axis=0) - true_pos
false_neg = np.sum(cm, axis=1) - true_pos
precision = np.sum(true_pos / (true_pos + false_pos))
recall = np.sum(true_pos / (true_pos + false_neg))
由于我们删除了真正的阳性来定义 false_positives/negatives 只是为了将它们添加回来......我们可以通过跳过几个步骤来进一步简化:
true_pos = np.diag(cm)
precision = np.sum(true_pos / np.sum(cm, axis=0))
recall = np.sum(true_pos / np.sum(cm, axis=1))
【讨论】:
我认为您最终不需要求和。没有总结,你的方法是正确的;它为每个类别提供精度和召回率。
如果您打算计算平均精度和召回率,那么您有两种选择:微观和宏观平均。
在此处阅读更多信息http://scikit-learn.org/stable/auto_examples/model_selection/plot_precision_recall.html
【讨论】:
为了完整起见,以供将来参考,给出了grounth(gt)和预测(pd)的列表。以下代码 sn-p 计算混淆矩阵,然后计算精度和召回率。
from sklearn.metrics import confusion_matrix
gt = [1,1,2,2,1,0]
pd = [1,1,1,1,2,0]
cm = confusion_matrix(gt, pd)
#rows = gt, col = pred
#compute tp, tp_and_fn and tp_and_fp w.r.t all classes
tp_and_fn = cm.sum(1)
tp_and_fp = cm.sum(0)
tp = cm.diagonal()
precision = tp / tp_and_fp
recall = tp / tp_and_fn
【讨论】:
假设的混淆矩阵 (cm)
cm =
[[ 970 1 2 1 1 6 10 0 5 0]
[ 0 1105 7 3 1 6 0 3 16 0]
[ 9 14 924 19 18 3 13 12 24 4]
[ 3 10 35 875 2 34 2 14 19 19]
[ 0 3 6 0 903 0 9 5 4 32]
[ 9 6 4 28 10 751 17 5 24 9]
[ 7 2 6 0 9 13 944 1 7 0]
[ 3 11 17 3 16 3 0 975 2 34]
[ 5 38 10 16 7 28 5 4 830 20]
[ 5 3 5 13 39 10 2 34 5 853]]
精度和召回率每个类使用map()计算列表划分。
from operator import truediv
import numpy as np
tp = np.diag(cm)
prec = list(map(truediv, tp, np.sum(cm, axis=0)))
rec = list(map(truediv, tp, np.sum(cm, axis=1)))
print ('Precision: {}\nRecall: {}'.format(prec, rec))
Precision: [0.959, 0.926, 0.909, 0.913, 0.896, 0.880, 0.941, 0.925, 0.886, 0.877]
Recall: [0.972, 0.968, 0.888, 0.863, 0.937, 0.870, 0.954, 0.916, 0.861, 0.880]
请注意:10 个类别、10 个精度和 10 个召回。
【讨论】:
看看@Aaditya Ura 发布的答案:https://stackoverflow.com/a/63922083/11534375
您可以使用名为Disarray 的自定义库。它有助于从混淆矩阵中生成所有必需的指标。
【讨论】: