数据可视化API的核心特性是它允许用户进行快速绘图和视觉调整,而无需重新计算。提供了一系列的展示类(Display classes),这些类通过两种方法来创建图表:from_estimator和from_predictions。from_estimator方法接受一个拟合过的估计器(estimator)和一些数据(X和y),然后创建一个展示对象。有时候,可能希望只计算一次预测结果,这时就应该使用from_predictions方法。以下是一个使用支持向量机绘制ROC曲线的例子:
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import RocCurveDisplay
from sklearn.datasets import load_wine
X, y = load_wine(return_X_y=True)
y = y == 2 # 将标签转换为二分类
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 = RocCurveDisplay.from_estimator(svc, X_test, y_test)
返回的svc_disp对象允许在未来的图表中继续使用已经计算过的SVC的ROC曲线。在这种情况下,svc_disp是一个RocCurveDisplay对象,它将计算得到的值存储在名为roc_auc、fpr和tpr的属性中。需要注意的是,也可以从支持向量机获取预测结果,然后使用from_predictions代替from_estimator。接下来,训练一个随机森林分类器,并再次绘制之前计算过的ROC曲线,通过使用展示对象的plot方法。
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
rfc = RandomForestClassifier(n_estimators=10, random_state=42)
rfc.fit(X_train, y_train)
ax = plt.gca()
rfc_disp = RocCurveDisplay.from_estimator(rfc, X_test, y_test, ax=ax, alpha=0.8)
svc_disp.plot(ax=ax, alpha=0.8)
请注意,传递了alpha=0.8到plot函数中,以调整曲线的透明度。
以下是一些使用可视化API的例子,包括ROC曲线的可视化、高级绘图与部分依赖图、展示对象的可视化以及分类器校准的比较。
5.1 显示对象
以下是一些可用的显示对象,用于不同类型的数据可视化: