roc_curve 在 sklearn 中:为什么它不能正常工作?

roc_curve in sklearn: why doesn't it work correctly?

我正在解决一个多class class化的任务,想在 sklearn 中使用 roc 曲线估计结果。据我所知,如果我设置正标签,它允许在这种情况下绘制曲线。 我尝试使用正标签绘制 roc 曲线并得到奇怪的结果:class 的 "positive label" 越大,roc 曲线变得越靠近左上角。 然后我用数组的先前二进制标记绘制了一条 roc 曲线。这两个地块是不同的!我认为第二个构建正确,但在二进制 classes 的情况下,情节只有 3 个点,这没有提供信息。

我想了解,为什么二进制 classes 的 roc 曲线和带有 "positive label" 的 roc 曲线看起来不同,以及如何正确绘制带有正标签的 roc 曲线。

代码如下:

from sklearn.metrics import roc_curve, auc
y_pred = [1,2,2,2,3,3,1,1,1,1,1,2,1,2,3,2,2,1,1]
y_test = [1,3,2,2,1,3,2,1,2,2,1,2,2,2,1,1,1,1,1]
fp, tp, _ = roc_curve(y_test, y_pred, pos_label = 2)
from sklearn.preprocessing import label_binarize
y_pred = label_binarize(y_pred, classes=[1, 2, 3])
y_test = label_binarize(y_test, classes=[1, 2, 3])
fpb, tpb, _b = roc_curve(y_test[:,1], y_pred[:,1])
plt.plot(fp, tp, 'ro-', fpb, tpb, 'bo-', alpha = 0.5)
plt.show()
print('AUC with pos_label', auc(fp,tp))
print('AUC binary variant', auc(fpb,tpb))

这是example of the plot

红色曲线表示roc_curve和pos_label,蓝色曲线表示roc_curve和"binary case"

如评论中所述,ROC 曲线 适合评估阈值 预测(即硬 classes) , 作为你的 y_pred;此外,在使用 AUC 时,记住一些对许多从业者来说并不明显的限制是很有用的 - 有关更多详细信息,请参阅 中自己答案的最后部分。

Could you give me please some advise, which metrics I can use to evaluate the quality of such a multi-class classification with "hard" classes?

最直接的方法是混淆矩阵和 scikit-learn 提供的 class化验报告:

from sklearn.metrics import confusion_matrix, classification_report

y_pred = [1,2,2,2,3,3,1,1,1,1,1,2,1,2,3,2,2,1,1]
y_test = [1,3,2,2,1,3,2,1,2,2,1,2,2,2,1,1,1,1,1]

print(classification_report(y_test, y_pred)) # caution - order of arguments matters!
# result:
             precision    recall  f1-score   support

          1       0.56      0.56      0.56         9
          2       0.57      0.50      0.53         8
          3       0.33      0.50      0.40         2

avg / total       0.54      0.53      0.53        19

cm = confusion_matrix(y_test, y_pred) # again, order of arguments matters
cm
# result:
array([[5, 2, 2],
       [4, 4, 0],
       [0, 1, 1]], dtype=int64)

从混淆矩阵中,您可以提取其他感兴趣的数量,例如每个 class 等的正确率和错误率 - 有关详细信息,请参阅

中的自己的答案