【问题标题】:How to plot multiple ROC curves in one plot with legend and AUC scores in python?python - 如何在一个带有图例和AUC分数的图中绘制多条ROC曲线?
【发布时间】:2017-08-11 05:10:50
【问题描述】:

我正在构建 2 个模型。

模型 1

modelgb = GradientBoostingClassifier()
modelgb.fit(x_train,y_train)
predsgb = modelgb.predict_proba(x_test)[:,1]
metrics.roc_auc_score(y_test,predsgb, average='macro', sample_weight=None)

模型 2

model = LogisticRegression()
model = model.fit(x_train,y_train)
predslog = model.predict_proba(x_test)[:,1]
metrics.roc_auc_score(y_test,predslog, average='macro', sample_weight=None)

如何在一个图中绘制两条 ROC 曲线,以及每个模型的 AUC 分数的图例和文本?

【问题讨论】:

  • 你使用的是哪个库?
  • 我有 matplotlib ,但是无论你建议什么 - 我都可以导入相关库
  • 我要的是模型...
  • 用于 GBM 的 sklearn.ensemble 和用于 Logistic 的 sklearn.linear_model

标签: python plot roc auc


【解决方案1】:

尝试根据您的数据进行调整:

from sklearn import metrics
import numpy as np
import matplotlib.pyplot as plt

plt.figure(0).clf()

pred = np.random.rand(1000)
label = np.random.randint(2, size=1000)
fpr, tpr, thresh = metrics.roc_curve(label, pred)
auc = metrics.roc_auc_score(label, pred)
plt.plot(fpr,tpr,label="data 1, auc="+str(auc))

pred = np.random.rand(1000)
label = np.random.randint(2, size=1000)
fpr, tpr, thresh = metrics.roc_curve(label, pred)
auc = metrics.roc_auc_score(label, pred)
plt.plot(fpr,tpr,label="data 2, auc="+str(auc))

plt.legend(loc=0)

【讨论】:

【解决方案2】:

只需将模型添加到列表中,即可在一个图中绘制多条 ROC 曲线。希望这对你有用!

from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import GradientBoostingClassifier
from sklearn import metrics
import matplotlib.pyplot as plt

plt.figure()

# Add the models to the list that you want to view on the ROC plot
models = [
{
    'label': 'Logistic Regression',
    'model': LogisticRegression(),
},
{
    'label': 'Gradient Boosting',
    'model': GradientBoostingClassifier(),
}
]

# Below for loop iterates through your models list
for m in models:
    model = m['model'] # select the model
    model.fit(x_train, y_train) # train the model
    y_pred=model.predict(x_test) # predict the test data
# Compute False postive rate, and True positive rate
    fpr, tpr, thresholds = metrics.roc_curve(y_test, model.predict_proba(x_test)[:,1])
# Calculate Area under the curve to display on the plot
    auc = metrics.roc_auc_score(y_test,model.predict(x_test))
# Now, plot the computed values
    plt.plot(fpr, tpr, label='%s ROC (area = %0.2f)' % (m['label'], auc))
# Custom settings for the plot 
plt.plot([0, 1], [0, 1],'r--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('1-Specificity(False Positive Rate)')
plt.ylabel('Sensitivity(True Positive Rate)')
plt.title('Receiver Operating Characteristic')
plt.legend(loc="lower right")
plt.show()   # Display

【讨论】:

  • 请解释为什么这回答了这个问题。这样会帮助更多的人。
【解决方案3】:

类似这样的...

#ROC Curve
from sklearn.metrics import roc_curve
y_pred_prob1 = classifier1.predict_proba(X_test)[:,1]
fpr1 , tpr1, thresholds1 = roc_curve(Y_test, y_pred_prob1)

y_pred_prob2 = classifier2.predict_proba(X_test)[:,1]
fpr2 , tpr2, thresholds2 = roc_curve(Y_test, y_pred_prob2)


y_pred_prob3 = classifier3.predict_proba(X_test)[:,1]
fpr3 , tpr3, thresholds3 = roc_curve(Y_test, y_pred_prob3)

y_pred_prob4 = classifier4.predict_proba(X_test)[:,1]
fpr4 , tpr4, thresholds4 = roc_curve(Y_test, y_pred_prob4)


plt.plot([0,1],[0,1], 'k--')
plt.plot(fpr1, tpr1, label= "Linear")
plt.plot(fpr2, tpr2, label= "Poly")
plt.plot(fpr3, tpr3, label= "RBF")
plt.plot(fpr4, tpr4, label= "Sigmoid")
plt.legend()
plt.xlabel("FPR")
plt.ylabel("TPR")
plt.title('Receiver Operating Characteristic')
plt.show()

【讨论】:

    【解决方案4】:
    from sklearn.metrics import plot_roc_curve
    
    
    fig = plot_roc_curve( clf, x_train_bow, y_train)
    fig = plot_roc_curve( clf, x_test_bow, y_test, ax = fig.ax_)
    fig.figure_.suptitle("ROC curve comparison")
    plt.show() 
    

    基本上plot_roc_curve 函数绘制分类器的 roc_curve。因此,如果我们使用plot_roc_curve 两次而不指定ax 参数,它将绘制两个图形。所以这里我们将第一个图形存储在图形变量中并访问它的轴并提供给下一个plot_roc_curve 函数,以便仅显示第一个图形的轴的图。

    【讨论】:

    • 请解释一下代码的作用和它是怎么做的。
    • 谢谢,它也解决了我的问题。你能帮我理解你为什么在 ax = fig.ax 中使用''(下划线)吗?
    【解决方案5】:
    from sklearn.metrics import plot_roc_curve
    
    classifiers = [log_reg, decision_tree, decision_forest]
    ax = plt.gca()
    for i in classifiers:
        plot_roc_curve(i, X_test, y_test, ax=ax)
    

    【讨论】:

    • 为什么(或何时)我想使用这种方法而不是接受的答案?这种变化有好处吗?如果是这样,您能否更新您的回复以包含详细信息?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 2012-12-14
    • 2016-09-11
    • 2019-02-27
    • 2014-09-20
    • 2017-09-04
    • 2020-06-07
    相关资源
    最近更新 更多