【问题标题】:Plot precision and recall with sklearn使用 sklearn 绘制精度和召回率
【发布时间】:2021-05-05 02:28:42
【问题描述】:

我使用自定义 ML 框架创建了一个分类模型。

我有 3 个班级:1、2、3

输入样本:

# y_true, y_pred, and y_scores are lists

print(y_true[0], y_pred[0], y_scores[0])
print(y_true[1], y_pred[1], y_scores[1])
print(y_true[2], y_pred[2], y_scores[2])

1 1 0.6903580037019461
3 3 0.8805178752523366
1 2 0.32107199420078963

使用 sklearn 我可以使用:metrics.classification_report:

metrics.classification_report(y_true, y_pred)

                         precision    recall  f1-score   support

                      1      0.521     0.950     0.673        400
                      2      0.000     0.000     0.000        290
                      3      0.885     0.742     0.807        310

               accuracy                          0.610       1000
              macro avg      0.468     0.564     0.493       1000
           weighted avg      0.482     0.610     0.519       1000

我想生成精确率与召回率的可视化。

但我收到此错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-108-2ebb913a4e4b> in <module>()
----> 1 precision, recall, thresholds = metrics.precision_recall_curve(y_true, y_scores)

1 frames
/usr/local/lib/python3.6/dist-packages/sklearn/metrics/_ranking.py in _binary_clf_curve(y_true, y_score, pos_label, sample_weight)
    534     if not (y_type == "binary" or
    535             (y_type == "multiclass" and pos_label is not None)):
--> 536         raise ValueError("{0} format is not supported".format(y_type))
    537 
    538     check_consistent_length(y_true, y_score, sample_weight)

ValueError: multiclass format is not supported 

我找到了一些例子:

但是如果我已经有了结果,还不太清楚如何对我的数组进行二值化,寻找指针如何简单地绘制它。

【问题讨论】:

  • 嗨!试试这样的link。我认为它对您非常有用,您的问题应该得到解决。
  • 谢谢,但正如我在原帖中提到的,在这两种情况下都使用二值化选项,这里不是这种情况。
  • 不清楚您所说的“二值化”是什么意思,也不清楚为什么,而对于 CM,您使用 y_pred,而对于您切换到 y_score 的情节。顺便说一句,问题与matplotlibseaborn 无关(已删除标签)。
  • 这是一个多类问题。大多数示例用于二进制分类。并推荐使用来自 sklearn.preprocessing import label_binarize 的示例

标签: python scikit-learn


【解决方案1】:

precision_recall_curve 有一个参数pos_label,用于 TP/TN/FP/FN 的“正”类的标签。因此,您可以提取相关概率,然后生成精度/召回点为:

y_pred = model.predict_proba(X)

index = 2  # or 0 or 1; maybe you want to loop?
label = model.classes_[index]  # see below
p, r, t = precision_recall_curve(y_true, y_pred[:, index], pos_label=label)

这里主要令人讨厌的是您需要按索引提取y_pred 的列,但pos_label 需要实际的类标签。您可以使用model.classes_ 连接这些人。

可能还值得注意的是,新的绘图便利函数plot_precision_recall_curve 不适用于此:它将模型作为参数,如果不是二元分类则中断。

【讨论】:

    猜你喜欢
    • 2018-07-04
    • 2017-05-28
    • 2015-07-22
    • 2023-04-07
    • 2018-01-20
    • 2018-11-03
    • 2018-09-14
    • 2019-11-20
    • 2012-11-26
    相关资源
    最近更新 更多