【问题标题】:ROC curve for binary classification in pythonpython中二进制分类的ROC曲线
【发布时间】:2017-08-19 23:24:50
【问题描述】:

我正在使用RandomForestClassifier 为二进制分类绘制 ROC 曲线

我有两个 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])

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

【问题讨论】:

    标签: numpy machine-learning scikit-learn ipython


    【解决方案1】:

    你需要概率来创建 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])
    

    来自 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()
    

    【讨论】:

    • 检查testpred的shape[0]的长度是否不等于0。如果是使用anyarray.reshape(-1)。您可以使用model.predict_proba(testdata)[:, 1] 获得概率
    • 我在plt.plot(fpr[2], tpr[2]) 遇到了一个密钥错误,我将其更改为1 ...其他一切正常!!!
    • fpr[2] 在示例中是因为有 3 个类。对于二元分类,只需计算fpr, tpr, _ = roc_curve(y_test, y_score) 并绘制x=fpr, y=tpr
    猜你喜欢
    • 2014-09-27
    • 2014-01-03
    • 2018-12-19
    • 2017-09-11
    • 1970-01-01
    • 2016-08-06
    • 2020-07-21
    • 2020-09-19
    • 2019-12-26
    相关资源
    最近更新 更多