如何修改标准代码以绘制 ROC 曲线以将几个模型的 ROC 绘制到 Python 中的一个图中?

How to modify standard code to plot ROC curve to plot ROC of a few models to one plot in Python?

我使用以下代码创建 ROC 曲线:

probs = model.predict_proba(X)[::,1]
auc = metrics.roc_auc_score(y, probs)
fper, tper, thresholds = roc_curve(y, probs)
plt.plot(fper, tper, label= model_name + " (auc = %0.3f)" % auc, color=color)
plt.plot([0, 1], [0, 1], color='black', linestyle='--')
plt.xlabel('False Positive Rate', fontsize=15)
plt.ylabel('True Positive Rate', fontsize=15)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.show()

然而,通过这种方式,我只能为 1 个模型创建 ROC,但是我如何修改这段代码,以呈现涉及几个模型的 ROC 曲线,而不仅仅是像上面的 1 个模型?

不清楚您想要哪种类型的绘图,您是要求 ROC 曲线位于多个单独的绘图中还是相互重叠?

如果你想要多个图,看看这个函数:https://matplotlib.org/devdocs/gallery/subplots_axes_and_figures/subplots_demo.html

这是他们给出的如何使用 plt.subplots 在单个图形上放置 4 个绘图的示例:

fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(x, y)
axs[0, 0].set_title('Axis [0, 0]')
axs[0, 1].plot(x, y, 'tab:orange')
axs[0, 1].set_title('Axis [0, 1]')
axs[1, 0].plot(x, -y, 'tab:green')
axs[1, 0].set_title('Axis [1, 0]')
axs[1, 1].plot(x, -y, 'tab:red')
axs[1, 1].set_title('Axis [1, 1]')

for ax in axs.flat:
    ax.set(xlabel='x-label', ylabel='y-label')

# Hide x labels and tick labels for top plots and y ticks for right plots.
for ax in axs.flat:
    ax.label_outer()

所以对你来说,你需要创建子图,而不是用 plt.plot(fper, tper, label= model_name + " (auc = %0.3f)" % auc, color=color) 绘图,而是 axs[i, j].plot(fper, tper, label= model_name + " (auc = %0.3f)" % auc, color=color)

如果你想让ROC曲线叠加在同一个图上,matplotlib默认会这样做。只需按照此处所述绘制所有数据:How to get different colored lines for different plots in a single figure?.