使用wandb可视化Scikit-Learn模型

本文探讨了如何使用wandb仅用几行代码就可视化您的scikit-learn模型的性能。

在本文中,我将向您展示如何仅用几行代码就可视化您的scikit-learn模型的性能。我们还将探讨这些图如何帮助我们更好地理解我们的模型。

  • 步骤1:导入Weights & bias并初始化一个新运行。
import wandb
wandb.init(project="visualize-sklearn")

  • 步骤2:可视化单个的plot。
# Visualize single plot
wandb.sklearn.plot_confusion_matrix(y_true, y_probas, labels)

或者同时想象所有的plot

# Visualize all the plots in the Classification section below with one line of code
wandb.sklearn.plot_classifier(clf, X_train, X_test, y_train, y_test, y_pred, y_probas, labels,
                                                         model_name='SVC', feature_names=None)

# Visualize all the plots in the Regression section below with one line of code
wandb.sklearn.plot_regressor(reg, X_train, X_test, y_train, y_test,  model_name='Ridge')

# Visualize all the plots in the Clustering section below with one line of code
wandb.sklearn.plot_clusterer(kmeans, X_train, cluster_labels, labels=None, model_name='KMeans')

如果你有任何问题,我们很乐意在我们松散的社区中解答

Classification

数据集

在这份报告中,我在泰坦尼克号数据集上训练了几个模型,这些数据集描述了泰坦尼克号上的乘客。我们的目标是预测乘客是否幸存。

学习曲线

在不同长度的数据集上训练模型,并为训练集和测试集生成交叉验证分数与数据集大小的关系图。

在这里我们可以观察到我们的模型是过拟合的。虽然它在训练集上表现得很好,但测试准确度逐渐提高,但从未完全达到与训练准确度相当的水平。

Example
wandb.sklearn.plot_learning_curve(model, X, y)

  • model (clf or reg): 接受一个拟合的回归器或分类器。
  • X (arr): Dataset features.
  • y (arr): Dataset labels.

ROC Curve

ROC曲线绘制真阳性率(y轴)vs假阳性率(x轴)。理想的分数是TPR = 1, FPR = 0,即左上角的点。通常我们计算ROC曲线下的面积(AUC-ROC), AUC-ROC越大越好。
Example
wandb.sklearn.plot_roc(y_true, y_probas, labels)

  • y_true (arr): 测试集的标签。
  • y_probas (arr): 测试集预测概率。
  • labels (list): 目标y的命名标签

精密召回曲线

计算不同阈值下的精度和召回率之间的权衡。曲线下的高面积同时代表高召回率和高精度,其中高召回率对应低假阳性率,高召回率对应低假阴性率。

两者的得分都很高,说明分类器返回了准确的结果(精度高),也返回了大部分积极的结果(高召回率)。PR曲线在班级非常不平衡的情况下是有用的。

Example
wandb.sklearn.plot_precision_recall(y_true, y_probas, labels)

  • y_true (arr): Test set labels.
  • y_probas (arr): Test set predicted probabilities.
  • labels (list): Named labels for target varible (y).

功能的重要性

评估并绘制分类任务中每个特征的重要性。只适用于具有“特征重要性”属性的分类器,如树。

在这里,我们可以看到“头衔”(小姐,夫人,先生,主人)非常能说明谁活了下来。这是有道理的,因为“头衔”同时抓住了乘客的性别、年龄和社会地位。奇怪的是,max_length是第二大最具预测性的特征,深入研究为什么会是这样可能会很有趣。

Example
wandb.sklearn.plot_feature_importances(model, ['width', 'height, 'length'])

  • model (clf): 接受一个合适的分类器。
  • feature_names (list): 名称的特性。用相应的名称替换特征索引,使图更容易阅读。

Calibration Curve

绘制分类器的预测概率的校准情况,以及如何校准未校准的分类器。比较通过基线逻辑回归模型(作为参数传递的模型)及其等压校正和s型校正估计的预测概率。

校准曲线越接近对角线越好。转置的类s型曲线表示过拟合的分类器,而类s型曲线表示欠拟合的分类器。通过训练模型的等压和等压校正,并比较它们的曲线,我们可以确定模型是过拟合还是欠拟合,如果是这样的话,哪种校正(s型或等压校正)可能有助于解决这个问题。

欲了解更多细节,请查看sklearn的文档

在这种情况下,我们可以看到普通的AdaBoost存在过拟合问题(由转置的sigmoid曲线证明),这可能是因为冗余的特征(如“title”)违反了特征独立性的假设。使用sigmoid校准AdaBoost似乎是解决这种过拟合最有效的方法。

Example
wandb.sklearn.plot_calibration_curve(clf, X, y, 'RandomForestClassifier')

  • model (clf): Takes in a fitted classifier.
  • X (arr): Training set features.
  • y (arr): Training set labels.
  • model_name (str): Model name. Defaults to ‘Classifier’

Confusion Matrix

计算混淆矩阵来评估分类的准确性。它对于评估模型预测的质量和发现模型错误预测的模式是很有用的。对角线表示模型得到正确的预测,即实际标签等于预测标签。

Example
wandb.sklearn.plot_confusion_matrix(y_true, y_probas, labels)

  • y_true (arr): Test set labels.
  • y_probas (arr): Test set predicted probabilities.
  • labels (list): Named labels for target varible (y).

Summary Metrics

计算回归和分类算法的汇总指标(如分类的f1、准确性、精密度和召回率,回归的mse、mae、r2得分)。

Example
wandb.sklearn.plot_summary_metrics(model, X_train, X_test, y_train, y_test)

  • model (clf or reg): Takes in a fitted regressor or classifier.
  • X (arr): Training set features.
  • y (arr): Training set labels.
  • X_test (arr): Test set features.
  • y_test (arr): Test set labels.

Clustering

Elbow Plot

测量并绘制方差百分比,并将其解释为集群数量的函数,以及训练时间。在选择最佳簇数时很有用。

在这里我们可以看到,根据肘部图的最佳簇数是3,这反映了数据集(有3个类Iris Setosa, Iris Versicolour, Iris Virginica)。

Example
wandb.sklearn.plot_elbow_curve(model, X_train)

  • model (clusterer): Takes in a fitted clusterer.
  • X (arr): Training set features.

Silhouette Plot

度量并绘制一个集群中的每个点与相邻集群中的点的距离。簇的厚度与簇的大小相对应。垂直线表示所有点的平均轮廓分数。

剪影系数接近+1表示样本远离相邻的聚类。

值为0表示样本在两个相邻集群之间的决策边界上或非常接近决策边界,值为负值表示这些样本可能被分配到错误的集群。

一般来说,我们希望所有的剪影集群分数都高于平均水平(越过红线),并且尽可能接近1。我们还喜欢反映数据中的底层模式的簇大小。

Example
wandb.sklearn.plot_silhouette(model, X_train, ['spam', 'not spam'])

  • model (clusterer): Takes in a fitted clusterer.
  • X (arr): Training set features.
  • cluster_labels (list): 集群标签的名称。通过用相应的名称替换群集索引,使图更容易读取。

Regression

Outlier Candidates Plot

通过库克距离度量数据点对回归模型的影响。具有严重扭曲影响的实例可能是异常值。对异常值检测很有用。

Example
wandb.sklearn.plot_outlier_candidates(model, X, y)

  • model (regressor): Takes in a fitted classifier.
  • X (arr): Training set features.
  • y (arr): Training set labels.

Residuals Plot

测量和绘制预测目标值(y轴)与实际目标值和预测目标值之间的差值(x轴),以及剩余误差的分布。

一般来说,良好拟合模型的残差应该是随机分布的,因为好的模型将解释数据集中的大多数现象,除了随机误差。

在这里,我们可以看到我们的模型所产生的大部分误差都在+/-5之间,并且在训练和测试数据集中都是均匀分布的。

Example
wandb.sklearn.plot_residuals(model, X, y)

  • model (regressor): Takes in a fitted classifier.
  • X (arr): Training set features.
  • y (arr): Training set labels.

Try it for yourself

from sklearn.datasets import load_boston 
from sklearn.model_selection import train_test_split 
from sklearn.ensemble import RandomForestClassifier 
from sklearn.svm import SVC 
from sklearn.linear_model import LinearRegression 
from sklearn.linear_model import Ridge 
from sklearn.tree import DecisionTreeClassifier 
import matplotlib.pyplot as plt 
import pandas as pd 
import wandb 
wandb.init(project="sklearn") 


# Load data 
boston = load_boston() 
X = pd.DataFrame(boston.data, columns=boston.feature_names) 
y = boston.target


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)


# Train model, get predictions
reg = Ridge()
reg.fit(X, y)
y_pred = reg.predict(X_test)


# Visualize all regression plots
wandb.sklearn.plot_regressor(reg, X_train, X_test, y_train, y_test, 'Ridge')


# Make individual plots
wandb.sklearn.plot_outlier_candidates(reg, X, y)

参考

https://wandb.ai/lavanyashukla/visualize-sklearn/reports/Visualize-Scikit-Models–Vmlldzo0ODIzNg
https://open.gitcode.host/wandb-docs/chinese/examples.html