python中二进制分类的ROC曲线

Ani*_*Ani 4 numpy machine-learning ipython scikit-learn

我想绘制一个ROC曲线用于使用 RandomForestClassifier

我有两个numpy数组,一个包含预测值,一个包含真实值,如下所示:

In [84]: test
Out[84]: array([0, 1, 0, ..., 0, 1, 0])

In [85]: pred
Out[85]: array([0, 1, 0, ..., 1, 0, 0])
Run Code Online (Sandbox Code Playgroud)

如何在ipython中为此二进制分类结果移植ROC曲线并获得AUC(曲线下面积)?

Abh*_*kur 6

您需要创建ROC曲线的概率。

In [84]: test
Out[84]: array([0, 1, 0, ..., 0, 1, 0])

In [85]: pred
Out[85]: array([0.1, 1, 0.3, ..., 0.6, 0.85, 0.2])
Run Code Online (Sandbox Code Playgroud)

scikit-learn示例中的示例代码:

import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(2):
    fpr[i], tpr[i], _ = roc_curve(test, pred)
    roc_auc[i] = auc(fpr[i], tpr[i])

print roc_auc_score(test, pred)
plt.figure()
plt.plot(fpr[1], tpr[1])
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic')
plt.show()
Run Code Online (Sandbox Code Playgroud)

  • 检查 `test` 或 `pred` 的 shape[0] 的长度是否不等于 0。如果是使用 `anyarray.reshape(-1)`。您可以使用`model.predict_proba(testdata)[:, 1]` 获得概率 (2认同)