sklearn画ROC曲线方法总结1(plot_roc_curve)

plot_roc_curve

在sklearn 0.22版本中,可以实现一行代码画出ROC-AUC图

 

sklearn.metrics.plot_roc_curve(estimator, X, y, sample_weight=None, drop_intermediate=True, response_method='auto', name=None, ax=None, **kwargs)

 

https://scikit-learn.org/stable/modules/generated/sklearn.metrics.plot_roc_curve.html?highlight=plot_roc_#sklearn.metrics.plot_roc_curve

例子:

import matplotlib.pyplot as plt
from sklearn import datasets, metrics, model_selection, svm

X, y = datasets.make_classification(random_state=0)
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, random_state=0)
clf = svm.SVC(random_state=0)
clf.fit(X_train, y_train)

display = metrics.plot_roc_curve(clf, X_test, y_test)
print('type(display):',type(display))
plt.show()

结果: 

type(display): <class 'sklearn.metrics._plot.roc_curve.RocCurveDisplay'>

打印display的类型,发现plot_roc_curve的返回值类型为RocCurveDisplay,此时可以通过RocCurveDisplay的figure_属性得到matplotlib.figure.Figure类型:

roc_fig = display.figure_
print('type(roc_fig):',type(roc_fig))

 结果:

type(roc_fig): <class 'matplotlib.figure.Figure'>

关于RocCurveDisplay详见

https://scikit-learn.org/stable/modules/generated/sklearn.metrics.RocCurveDisplay.html#sklearn.metrics.RocCurveDisplay

 

另外,如果想绘制多条roc曲线,可以采用如下方式:

from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn import datasets
from sklearn.metrics import plot_roc_curve
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier

X, y = datasets.make_classification(random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
svc = SVC(random_state=42)
svc.fit(X_train, y_train)

svc_disp = plot_roc_curve(svc, X_test, y_test)

# new curve
rfc = RandomForestClassifier(random_state=42)
rfc.fit(X_train, y_train)

# 将 svc 模型下的 ROC 图中的坐标系传到 rfc 模型下的 ROC 图中的 ax 参数中
# method1
ax = plt.gca()
rfc_disp = plot_roc_curve(rfc, X_test, y_test, ax=ax, alpha=0.8)

## method2
# rfc_disp = plot_roc_curve(rfc, X_test, y_test, ax=svc_disp.ax_, alpha=0.8)

plt.show()

结果:

详见

https://scikit-learn.org/stable/visualizations.html#visualizations

ref

盘一盘 Python 系列特别篇 - Sklearn (0.22)

 

来自 <https://blog.csdn.net/weixin_38753422/article/details/103545458?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task>

  • 7
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值