备注
Go to the end 下载完整的示例代码。或者通过浏览器中的MysterLite或Binder运行此示例
具有交叉验证的接收器工作特性(ROC)#
此示例展示了如何使用交叉验证来估计和可视化接收者操作特征(ROC)指标的方差。
ROC曲线通常以Y轴上的真阳性率(TPR)和X轴上的假阳性率(FPR)为特征。这意味着该图的左上角是“理想”点-FPR为零,TPA为1。这并不太现实,但这确实意味着更大的曲线下面积(UC)通常会更好。ROC曲线的“陡度”也很重要,因为最大限度地降低FPR是理想的选择。
此示例显示了从K折叠交叉验证创建的不同数据集的ROC响应。采用所有这些曲线,可以计算平均AUR,并查看将训练集拆分为不同子集时曲线的方差。这大致显示了分类器输出如何受到训练数据变化的影响,以及K折叠交叉验证生成的分裂之间有多大差异。
备注
看到 sphx_glr_auto_examples_model_selection_plot_roc.py 作为本示例的补充,解释平均策略以概括多类分类器的指标。
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
加载和准备数据#
我们进口 虹膜植物数据集 它包含3个类别,每个类别对应于一种鸢尾植物。一个类与另两个类线性可分;后者是 not 彼此线性分离。
在下文中,我们通过删除“virginica”类来对数据集进行二进制化 (class_id=2
).这意味着“变色”类 (class_id=1
)被视为积极类,“setosa”被视为消极类 (class_id=0
).
import numpy as np
from sklearn.datasets import load_iris
iris = load_iris()
target_names = iris.target_names
X, y = iris.data, iris.target
X, y = X[y != 2], y[y != 2]
n_samples, n_features = X.shape
我们还添加了噪音功能,以使问题变得更加困难。
random_state = np.random.RandomState(0)
X = np.concatenate([X, random_state.randn(n_samples, 200 * n_features)], axis=1)
分类和ROC分析#
我们在这里跑步 cross_validate
上 SVC
分类器,然后使用计算出的交叉验证结果以折叠方式绘制ROC曲线。请注意,定义机会水平的基线(虚线ROC曲线)是一个始终预测最频繁类别的分类器。
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.metrics import RocCurveDisplay, auc
from sklearn.model_selection import StratifiedKFold, cross_validate
n_splits = 6
cv = StratifiedKFold(n_splits=n_splits)
classifier = svm.SVC(kernel="linear", probability=True, random_state=random_state)
cv_results = cross_validate(
classifier, X, y, cv=cv, return_estimator=True, return_indices=True
)
prop_cycle = plt.rcParams["axes.prop_cycle"]
colors = prop_cycle.by_key()["color"]
curve_kwargs_list = [
dict(alpha=0.3, lw=1, color=colors[fold % len(colors)]) for fold in range(n_splits)
]
names = [f"ROC fold {idx}" for idx in range(n_splits)]
mean_fpr = np.linspace(0, 1, 100)
interp_tprs = []
_, ax = plt.subplots(figsize=(6, 6))
viz = RocCurveDisplay.from_cv_results(
cv_results,
X,
y,
ax=ax,
name=names,
curve_kwargs=curve_kwargs_list,
plot_chance_level=True,
)
for idx in range(n_splits):
interp_tpr = np.interp(mean_fpr, viz.fpr[idx], viz.tpr[idx])
interp_tpr[0] = 0.0
interp_tprs.append(interp_tpr)
mean_tpr = np.mean(interp_tprs, axis=0)
mean_tpr[-1] = 1.0
mean_auc = auc(mean_fpr, mean_tpr)
std_auc = np.std(viz.roc_auc)
ax.plot(
mean_fpr,
mean_tpr,
color="b",
label=r"Mean ROC (AUC = %0.2f $\pm$ %0.2f)" % (mean_auc, std_auc),
lw=2,
alpha=0.8,
)
std_tpr = np.std(interp_tprs, axis=0)
tprs_upper = np.minimum(mean_tpr + std_tpr, 1)
tprs_lower = np.maximum(mean_tpr - std_tpr, 0)
ax.fill_between(
mean_fpr,
tprs_lower,
tprs_upper,
color="grey",
alpha=0.2,
label=r"$\pm$ 1 std. dev.",
)
ax.set(
xlabel="False Positive Rate",
ylabel="True Positive Rate",
title=f"Mean ROC curve with variability\n(Positive label '{target_names[1]}')",
)
ax.legend(loc="lower right")
plt.show()
Traceback (most recent call last):
File "/pb1/repo/scikit-learn/examples/model_selection/plot_roc_crossval.py", line 95, in <module>
viz = RocCurveDisplay.from_cv_results(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: type object 'RocCurveDisplay' has no attribute 'from_cv_results'
Total running time of the script: (0 minutes 0.101 seconds)
相关实例
Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>
_