
一、显示 API 简介使用 utils.discovery.all_displays 查找可用的 API。Sklearn 的utils.discovery.all_displays可以让你看到哪些类可以使用。from sklearn.utils.discovery import all_displays displays all_displays() displaysScikit-learn (sklearn) 总是会在新版本中添加 Display API因此这里可以了解你的版本中有哪些可用的 API 。例如在我的 Scikit-learn 1.4.0 中就有这些类[(CalibrationDisplay, sklearn.calibration.CalibrationDisplay), (ConfusionMatrixDisplay, sklearn.metrics._plot.confusion_matrix.ConfusionMatrixDisplay), (DecisionBoundaryDisplay, sklearn.inspection._plot.decision_boundary.DecisionBoundaryDisplay), (DetCurveDisplay, sklearn.metrics._plot.det_curve.DetCurveDisplay), (LearningCurveDisplay, sklearn.model_selection._plot.LearningCurveDisplay), (PartialDependenceDisplay, sklearn.inspection._plot.partial_dependence.PartialDependenceDisplay), (PrecisionRecallDisplay, sklearn.metrics._plot.precision_recall_curve.PrecisionRecallDisplay), (PredictionErrorDisplay, sklearn.metrics._plot.regression.PredictionErrorDisplay), (RocCurveDisplay, sklearn.metrics._plot.roc_curve.RocCurveDisplay), (ValidationCurveDisplay, sklearn.model_selection._plot.ValidationCurveDisplay)]二、显示决策边界使用 inspection.DecisionBoundaryDisplay 显示决策边界如果使用 Matplotlib 来绘制会很麻烦使用np.linspace设置坐标范围使用plt.meshgrid计算网格使用plt.contourf绘制决策边界填充然后使用plt.scatter绘制数据点。现在使用inspection.DecisionBoundaryDisplay可以简化这一过程from sklearn.inspection import DecisionBoundaryDisplay from sklearn.datasets import load_iris from sklearn.svm import SVC from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt iris load_iris(as_frameTrue) X iris.data[[petal length (cm), petal width (cm)]] y iris.target svc_clf make_pipeline(StandardScaler(), SVC(kernellinear, C1)) svc_clf.fit(X, y) display DecisionBoundaryDisplay.from_estimator(svc_clf, X, grid_resolution1000, xlabelPetal length (cm), ylabelPetal width (cm)) plt.scatter(X.iloc[:, 0], X.iloc[:, 1], cy, edgecolorsw) plt.title(Decision Boundary) plt.show()使用 DecisionBoundaryDisplay 绘制三重分类模型。请记住Display只能绘制二维数据因此请确保数据只有两个特征或更小的维度。三、概率校准要比较分类模型使用 calibration.CalibrationDisplay 进行概率校准概率校准曲线可以显示模型预测的可信度。CalibrationDisplay使用的是模型的predict_proba。如果使用支持向量机需要将probability设为 Truefrom sklearn.calibration import CalibrationDisplay from sklearn.model_selection import train_test_split from sklearn.datasets import make_classification from sklearn.ensemble import HistGradientBoostingClassifier X, y make_classification(n_samples1000, n_classes2, n_features5, random_state42) X_train, X_test, y_train, y_test train_test_split(X, y, test_size0.3, random_state42) proba_clf make_pipeline(StandardScaler(), SVC(kernelrbf, gammaauto, C10, probabilityTrue)) proba_clf.fit(X_train, y_train) CalibrationDisplay.from_estimator(proba_clf, X_test, y_test) hist_clf HistGradientBoostingClassifier() hist_clf.fit(X_train, y_train) ax plt.gca() CalibrationDisplay.from_estimator(hist_clf, X_test, y_test, axax) plt.show()CalibrationDisplay.四、显示混淆矩阵在评估分类模型和处理不平衡数据时需要查看精确度和召回率。使用metrics.ConfusionMatrixDisplay绘制混淆矩阵TP、FP、TN 和 FN。from sklearn.datasets import fetch_openml from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import ConfusionMatrixDisplay digits fetch_openml(mnist_784, version1) X, y digits.data, digits.target rf_clf RandomForestClassifier(max_depth5, random_state42) rf_clf.fit(X, y) ConfusionMatrixDisplay.from_estimator(rf_clf, X, y) plt.show()五、Roc 和 Det 曲线因为经常并列评估Roc 和 Det 曲线因此把metrics.RocCurveDisplay和metrics.DetCurveDisplay两个图表放在一起。RocCurveDisplay比较模型的 TPR 和 FPR。对于二分类希望 FPR 低而 TPR 高因此左上角是最佳位置。Roc 曲线向这个角弯曲。由于 Roc 曲线停留在左上角附近右下角是空的因此很难看到模型差异。使用DetCurveDisplay绘制一条带有 FNR 和 FPR 的 Det 曲线。它使用了更多空间比 Roc 曲线更清晰。Det 曲线的最佳点是左下角。from sklearn.metrics import RocCurveDisplay from sklearn.metrics import DetCurveDisplay X, y make_classification(n_samples10_000, n_features5, n_classes2, n_informative2) X_train, X_test, y_train, y_test train_test_split(X, y, test_size0.3, random_state42, stratifyy) classifiers { SVC: make_pipeline(StandardScaler(), SVC(kernellinear, C0.1, random_state42)), Random Forest: RandomForestClassifier(max_depth5, random_state42) } fig, [ax_roc, ax_det] plt.subplots(1, 2, figsize(10, 4)) for name, clf in classifiers.items(): clf.fit(X_train, y_train) RocCurveDisplay.from_estimator(clf, X_test, y_test, axax_roc, namename) DetCurveDisplay.from_estimator(clf, X_test, y_test, axax_det, namename)六、调整阈值在数据不平衡的情况下希望调整召回率和精确度。可以使用使用 metrics.PrecisionRecallDisplay 调整阈值对于电子邮件欺诈需要高精确度。而对于疾病筛查则需要高召回率来捕获更多病例。那么可以调整阈值但调整多少才合适呢因此可以使用metrics.PrecisionRecallDisplay来绘制相关图表。from xgboost import XGBClassifier from sklearn.datasets import load_wine from sklearn.metrics import PrecisionRecallDisplay wine load_wine() X, y wine.data[wine.target1], wine.target[wine.target1] X_train, X_test, y_train, y_test train_test_split(X, y, test_size0.3, stratifyy, random_state42) xgb_clf XGBClassifier() xgb_clf.fit(X_train, y_train) PrecisionRecallDisplay.from_estimator(xgb_clf, X_test, y_test) plt.show()这表明可以按照 Scikit-learn 的设计绘制模型就像这里的xgboost。七、回归模型评估Scikit-learn 的metrics.PredictionErrorDisplay绘制残差图可以帮助评估回归模型。from sklearn.svm import SVR from sklearn.metrics import PredictionErrorDisplay rng np.random.default_rng(42) X rng.random(size(200, 2)) * 10 y X[:, 0]**2 5 * X[:, 1] 10 rng.normal(loc0.0, scale0.1, size(200,)) reg make_pipeline(StandardScaler(), SVR(kernellinear, C10)) reg.fit(X, y) fig, axes plt.subplots(1, 2, figsize(8, 4)) PredictionErrorDisplay.from_estimator(reg, X, y, axaxes[0], kindactual_vs_predicted) PredictionErrorDisplay.from_estimator(reg, X, y, axaxes[1], kindresidual_vs_predicted) plt.show()图表展示预测值与实际值的比较左图适合线性回归。然而并非所有数据都是完全线性的因此请参考右图。右图展示了实际值与预测值的差异即残差图。残差图的香蕉形状暗示我们的数据可能不适合线性回归。考虑将核函数从线性 转换为 rbf 残差图会更好。reg make_pipeline(StandardScaler(), SVR(kernelrbf, C10))八、绘制学习曲线学习曲线主要研究模型的泛化效果和训练测试数据之间的差异或偏差。接下来使用model_selection.LearningCurveDisplay绘制学习曲线并比较了决策树分类器和梯度提升分类器在不同训练数据下的表现。from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import GradientBoostingClassifier from sklearn.model_selection import LearningCurveDisplay X, y make_classification(n_samples1000, n_classes2, n_features10, n_informative2, n_redundant0, n_repeated0) tree_clf DecisionTreeClassifier(max_depth3, random_state42) gb_clf GradientBoostingClassifier(n_estimators50, max_depth3, tol1e-3) train_sizes np.linspace(0.4, 1.0, 10) fig, axes plt.subplots(1, 2, figsize(10, 4)) LearningCurveDisplay.from_estimator(tree_clf, X, y, train_sizestrain_sizes, axaxes[0], scoringaccuracy) axes[0].set_title(DecisionTreeClassifier) LearningCurveDisplay.from_estimator(gb_clf, X, y, train_sizestrain_sizes, axaxes[1], scoringaccuracy) axes[1].set_title(GradientBoostingClassifier) plt.show()从图中可以看出虽然基于树的GradientBoostingClassifier在训练数据上保持了良好的准确性但其在测试数据上的泛化能力与DecisionTreeClassifier相比并无明显优势。九、可视化参数调整为了改善泛化效果差的模型可以尝试通过调整正则化参数来提高性能。传统的方法是使用 GridSearchCV 或 Optuna 等工具来实现模型调整然而这些方法只能找出整体表现最佳的模型且调整过程并不直观。如果需要调整特定参数以测试其对模型的影响建议使用model_selection.ValidationCurveDisplay来直观地观察模型在参数变化时的表现。from sklearn.model_selection import ValidationCurveDisplay from sklearn.linear_model import LogisticRegression param_name, param_range C, np.logspace(-8, 3, 10) lr_clf LogisticRegression() ValidationCurveDisplay.from_estimator(lr_clf, X, y, param_nameparam_name, param_rangeparam_range, scoringf1_weighted, cv5, n_jobs-1) plt.show()十、讨论尝试过所有这些显示后我必须承认一些遗憾最大的遗憾是这些 API 大多数缺乏详细的教程这可能也是与 Scikit-learn 的详尽文档相比不为人知的原因。这些应用程序接口散布在不同的软件包中因此很难从一个地方引用它们。代码仍然非常基础。通常需要将其与 Matplotlib 的 API 搭配使用才能完成工作。一个典型的例子是 DecisionBoundaryDisplay在绘制决策边界后还需要使用 Matplotlib 来绘制数据分布。它们很难扩展。除了一些验证参数的方法外很难用工具或方法来简化模型的可视化过程最终需要重写了很多东西。这些 API 希望得到更多关注并且随着版本升级可视化 API 也能更易用。在机器学习中用可视化方式解释模型与训练模型同样重要。本文介绍了当前版本 scikit-learn 中的各种绘图 API利用这些 API可以简化一些 Matplotlib 代码缓解学习曲线并简化模型评估过程。由于篇幅有限未对每个 API 进行详细介绍。如果有兴趣可以查看 [官方文档:https://scikit-learn.org/stable/visualizations.html?refdataleadsfuture.com] 了解更多详情。