scikit-learn 分类指标中的 classification_report 与 f1_score

Posted

技术标签:

【中文标题】scikit-learn 分类指标中的 classification_report 与 f1_score【英文标题】:classification_report vs f1_score in scikit-learn's classification metrics 【发布时间】:2016-01-19 18:32:41 【问题描述】:

使用 scikit-learn 的评估指标评估二元分类器的正确方法是什么?

假设 y_test 和 y_pred 作为黄金和预测标签,classification_report 输出中的 F1 分数不应该与 f1_score 产生的相同吗?

这是我的做法:

print(classification_reprot(y_test, y_pred)

给出下表:

         precision    recall  f1-score   support

      0       0.49      0.18      0.26       204
      1       0.83      0.96      0.89       877

avg / total       0.77      0.81      0.77      1081

然而,

print(f1_score(y_test, y_pred) 

给出 F1 分数 = 0.89

现在,给定以上输出,这个模型的 F1 分数是 0.89 还是 0.77?

【问题讨论】:

【参考方案1】:

简而言之,对于您的情况,f1-score 为 0.89,加权平均 f1-score 为 0.77。

看一下sklearn.metrics.f1_score的docstring:

The F1 score can be interpreted as a weighted average of the precision and
recall, where an F1 score reaches its best value at 1 and worst score at 0.
The relative contribution of precision and recall to the F1 score are
equal. The formula for the F1 score is::

    F1 = 2 * (precision * recall) / (precision + recall)

In the multi-class and multi-label case, this is the weighted average of
the F1 score of each class.

关键是这里的最后一句话。如果您正在寻找每个类的加权平均 f1 分数,那么您不应该为函数提供 0/1 二元分类。因此,例如,您可以这样做

f1_score(y_test + 1, y_pred + 1)
# 0.77

如果类标签不是 0/1,则将其视为多类指标(您关心所有精度/召回分数)而不是二元指标(您只关心正样本的精度/召回率) .我同意这可能有点令人惊讶,但通常 0/1 类被视为二元分类的标记。


编辑:这里列出的一些行为自 Scikit-learn 0.16 以来已被弃用——尤其是关于二进制与非二进制分类的令人困惑的隐含假设。详情请见this github thread。

【讨论】:

以上是关于scikit-learn 分类指标中的 classification_report 与 f1_score的主要内容,如果未能解决你的问题,请参考以下文章