我在使用scikit-learn计算分类记录,当我尝试打印它时,会出现一个警告:
print classification_report(original,predicted)
警告:
Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples.
所以我想通过微平均来报告精确度和召回率。我该如何使用分类报告,使其结果不出现未定义的精确度和召回率?提前感谢。
回答:
这并不是分类报告本身的问题;仔细阅读,警告实际上告诉你,一些类别在你的预测中不存在(即你的分类器没有预测任何样本属于某些类别)。
通过调整文档中的示例可以帮助演示这一点:
from sklearn.metrics import classification_reporty_true = [0, 1, 2, 2, 0]y_pred = [0, 0, 2, 2, 0] # no 1's predictedtarget_names = ['class 0', 'class 1', 'class 2']print classification_report(y_true, y_pred, target_names=target_names)
这是结果:
precision recall f1-score support class 0 0.67 1.00 0.80 2 class 1 0.00 0.00 0.00 1 class 2 1.00 1.00 1.00 2avg / total 0.67 0.80 0.72 5/home/ctsats/.local/lib/python2.7/site-packages/sklearn/metrics/classification.py:1135: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples.
所以,问题出在你的分类器和/或训练数据上…
更新(评论后):根据定义,只有宏平均会为每个类(标签)提供一个F1分数;从文档中可以看到:
‘micro’:
通过计算总的真阳性、假阴性和假阳性来全局计算指标。
‘macro’:
为每个标签计算指标,并找到它们的非加权平均值。这不考虑标签的不平衡性。
这就是为什么在classification_report
中报告的F1分数是通过宏平均计算的。确实,使用微平均不会得到警告(因为它计算了总的真阳性,因此它不关心某些类别是否在预测中未被表示),但你不会得到每个类的F1分数 – 你只会得到一个整体数字:
f1_score(y_true, y_pred, average='micro')# 0.8000000000000002
这不能在classification_report
中使用,因为所有报告的指标都是按类别的。