
如何在 scikit-learn 中校准分类器的概率
来源标题:How to Calibrate Your Classifier’s Probabilities in Scikit-learn
本教程演示如何用 Platt scaling 和 isotonic regression 修复分类器概率校准问题。在真实数据集上训练两个 scikit-learn 分类器,通过可靠性图和 Brier 分数暴露其校准偏差,再使用 CalibratedClassifierCV 进行校准修正。
以下正文由 AI 翻译自 KDnuggets(原文版权归原站所有),可能存在偏差,重要内容请以原文为准。
import numpy as np import matplotlib.pyplot as plt from sklearn.calibration import CalibratedClassifierCV, CalibrationDisplay from sklearn.datasets import fetch_covtype from sklearn.ensemble import RandomForestClassifier from sklearn.frozen import FrozenEstimator from sklearn.metrics import brier_score_loss, log_loss, roc_auc_score from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB RANDOM_STATE = 42
---- 第 1 步:数据 -------------------------------------------------------
X, y = fetch_covtype(return_X_y=True) y = (y == 1).astype(int) # 1 = Spruce/Fir,其余 = 0
取 100,000 行样本,让所有流程都能快速跑完
rng = np.random.default_rng(RANDOM_STATE) subset = rng.choice(len(X), size=100_000, replace=False) X, y = X[subset], y[subset] print("Rows:", X.shape[0], "| Share of positives:", round(y.mean(), 3))
划分:50% 训练、20% 校准、30% 测试
X_train, X_rest, y_train, y_rest = train_test_split( X, y, train_size=0.5, stratify=y, random_state=RANDOM_STATE ) X_cal, X_test, y_cal, y_test = train_test_split( X_rest, y_rest, train_size=0.4, stratify=y_rest, random_state=RANDOM_STATE ) print("Train / calibration / test:", len(X_train), len(X_cal), len(X_test))
fetch_covtype 第一次调用时会下载数据,并缓存到你主目录下的 scikit_learn_data 文件夹中。目标值包含 1 到 7,因此 y == 1 会把它变成 0/1 标签。抽取 100,000 行既能让随机森林跑得快,又不影响要讲的内容。
最关键的是这个三路划分。用户指南中解释说,校准器应当拟合在与训练分类器所用数据相互独立的数据上,因为模型在自己的训练数据上会更有把握。如果在校准数据上拟合校准器,学到的概率会过于接近 0 和 1。因此你需要一个训练集、一个校准集,以及一个直到最后检查才动用的测试集。stratify 会保证每个划分中的类别占比一致。
现在训练两个已知会朝相反方向出问题的模型。把下面这段加到同一个文件里:
---- 第 2 步:训练两个模型 -------------------------------------------
models = { "Naive Bayes": GaussianNB(), "Random forest": RandomForestClassifier( n_estimators=200, n_jobs=-1, random_state=RANDOM_STATE ), for model in models.values(): model.fit(X_train, y_train)
在未触碰的测试集上,预测正类的概率
raw = {name: m.predict_proba(X_test)[:, 1] for name, m in models.items()}
两个模型都只在训练集上拟合。predict_proba(X_test)[:, 1] 保留正类的概率,对于二分类问题,这就是你需要的全部。
接下来是三个小辅助函数,你会在每次比较中反复用到:
---- 辅助函数 ------------------------------------------------------------
def ninety_test(name, p, y_true, low=0.85, high=0.95): """在 [low, high) 区间被打分的样本,实际为正类的比例是多少?""" mask = (p >= low) & (p {y_true[mask].mean():.1%} are actually positive" ) def print_scores(y_true, probas): print(f"{'Model':8}{'Log loss':>10}{'ROC-AUC':>9}") for name, p in probas.items(): print( f"{name:8.4f}" f"{log_loss(y_true, p):>10.4f}{roc_auc_score(y_true, p):>9.4f}" ) def reliability_plot(y_true, probas, title): fig, (ax_curve, ax_hist) = plt.subplots( 2, 1, figsize=(7, 9), gridspec_kw={"height_ratios": [3, 1]}, sharex=True ) for i, (name, p) in enumerate(probas.items()): CalibrationDisplay.from_predictions( y_true, p, n_bins=10, name=name, ax=ax_curve, ref_line=(i == 0) ) ax_hist.hist(p, bins=10, range=(0, 1), histtype="step", label=name) ax_curve.set_title(title) ax_curve.set_xlabel("") ax_hist.set_xlabel("Mean predicted probability") ax_hist.set_ylabel("Count") ax_hist.legend(loc="upper center") plt.tight_layout() plt.show()
ninety_test 就是用普通代码做「0.9 是否意味着 90%?」这项检查。它取出所有打分在 0.85 到 0.95 之间的测试样本,并报告其中真正为正类的比例。
print_scores 报告三个数字。Brier 分数是概率与结果之间差值的平方均值,越低越好。Log loss 对高置信度的错误惩罚更重。ROC-AUC 衡量排序能力,可以帮助你说明校准没有破坏它。
reliability_plot 绘制校准曲线,也叫可靠性图。样本按预测概率分成 10 组。x 轴是每组中的平均预测值,y 轴是该组中真实正类的占比。完美的模型会落在对角线上。下面的直方图显示每个组里落了多少个预测,这样你就能知道哪些曲线点有充足的数据支撑、哪些只有很少的数据。ref_line=(i == 0) 只绘制一次对角线。
正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。