交叉验证模型比较
六个模型预测生产批次废料率的逐折 R²,附均值与校正后的 95% 区间。

“模型 B 得 0.47,模型 A 得 0.46”——在不知道得分随划分变动多少之前,这句话毫无意义。这里每个模型都在 相同 的 10 × 5 重复折上评估;每个点是一折,大标记为均值,横条为其 95% 区间。各折得分并不独立——训练集相互重叠——因此区间采用 Nadeau–Bengio 校正 方差,而不是过窄的朴素标准误。
本例以 Warin、d'Anglade 和 de Marcellis-Warin(2025,International Journal of Sustainable Engineering)的研究为背景,该研究结合 k-means 聚类与数据科学来减少制造业的废料。数据为说明用途而 模拟,并非 论文的数据或结果:n = 600 个生产批次,其废料率(报废材料的 %)以非线性方式取决于机器速度、温度和操作员经验,也取决于材料等级,以及湿度与距上次维护天数之间的交互作用;批次大小没有影响。后面五张图使用同一批模拟批次。分数来自配合 RepeatedKFold 的 cross_val_score;线性模型在 Pipeline 中做了标准化。由于效应是弯曲且相互作用的,树集成模型大幅领先于线性模型。
代码及图中文字均为英文。
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor
from sklearn.linear_model import LassoCV, LinearRegression, RidgeCV
from sklearn.model_selection import RepeatedKFold, cross_val_score
from sklearn.neighbors import KNeighborsRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
# Simulated data, set in the context of Warin, d'Anglade & de Marcellis-Warin (2025) [warin2025waste]
# Data: 600 production batches; outcome = waste rate (% of material scrapped)
rng = np.random.default_rng(2025)
n = 600
names = {"speed": "Machine speed (units/min)", "temperature": "Temperature (°C)",
"humidity": "Humidity (%)", "experience": "Operator experience (years)",
"maintenance": "Days since maintenance", "grade": "Material grade (1 = best)",
"batch_size": "Batch size (kg)"}
X = pd.DataFrame({"speed": rng.uniform(80, 160, n), "temperature": rng.uniform(195, 225, n),
"humidity": rng.uniform(30, 75, n), "experience": rng.gamma(2, 4, n),
"maintenance": rng.uniform(0, 120, n), "grade": rng.integers(1, 4, n),
"batch_size": rng.uniform(200, 1000, n)}) # batch size has no effect
y = (2 + 0.002 * np.clip(X.speed - 110, 0, None) ** 2 # waste climbs above 110 units/min
+ 0.025 * (X.temperature - 210) ** 2 # U-shape around the 210 °C set point
+ 3 * np.exp(-X.experience / 3) # novices waste more, gains fade
+ 4 * (X.humidity - 30) / 45 * X.maintenance / 120 # humidity hurts worn machines most
+ 0.6 * (X.grade - 1) + rng.normal(0, 0.7, n))
k, reps = 5, 10
cv = RepeatedKFold(n_splits=k, n_repeats=reps, random_state=0)
models = {
"Linear regression": make_pipeline(StandardScaler(), LinearRegression()),
"Ridge": make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-3, 3, 25))),
"Lasso": make_pipeline(StandardScaler(), LassoCV(random_state=0)),
"Random forest": RandomForestRegressor(n_estimators=200, min_samples_leaf=3, random_state=0),
"Gradient boosting": GradientBoostingRegressor(learning_rate=0.05, n_estimators=300, max_depth=2,
random_state=0),
"k-nearest neighbours": make_pipeline(StandardScaler(), KNeighborsRegressor(n_neighbors=15)),
}
scores = {name: cross_val_score(m, X, y, cv=cv, scoring="r2", n_jobs=-1) for name, m in models.items()}
# Nadeau–Bengio corrected 95% interval for a mean of k-fold scores
def corrected_ci(s):
J = len(s)
se = np.sqrt((1 / J + (1 / k) / (1 - 1 / k)) * s.var(ddof=1))
t = stats.t.ppf(0.975, J - 1)
return s.mean() - t * se, s.mean() + t * se
order = sorted(scores, key=lambda n: scores[n].mean())
best = order[-1]
fig, ax = plt.subplots(figsize=(8, 5.2))
jit = np.random.default_rng(3)
for i, name in enumerate(order):
s = scores[name]
c = "#007AFF" if name == best else "#8E8E93"
ax.scatter(s, i + jit.uniform(-0.18, 0.18, len(s)), s=12, color=c, alpha=0.35, lw=0)
lo, hi = corrected_ci(s)
ax.plot([lo, hi], [i, i], color=c, lw=3, solid_capstyle="round")
ax.scatter(s.mean(), i, s=80, color=c, edgecolor="white", lw=1.5, zorder=4)
ax.text(hi + 0.012, i, f"{s.mean():.3f}", va="center", fontsize=9.5, color=c, fontweight="semibold",
bbox=dict(fc="white", ec="none", pad=1), zorder=5)
ax.set_yticks(range(len(order)), order)
ax.set_xlabel("Out-of-sample R² (one dot per fold)")
ax.grid(axis="x"); ax.grid(axis="y", visible=False)
lin = scores["Linear regression"].mean()
ax.set_title(f"{best} explains {scores[best].mean():.0%} of waste variance; linear regression only {lin:.0%}",
pad=26)
ax.text(0, 1.02, f"Waste rate of production batches · n = {n} (simulated) · {k}-fold CV × {reps} repeats · "
"bars = Nadeau–Bengio corrected 95% CI", transform=ax.transAxes, fontsize=9.5, color="#6E6E73")
plt.show()
图表使用了可选的 PyStatlas 样式:添加 plt.style.use("pystatlas.mplstyle") 即可完全还原其外观。
数据来源
- Simulated data. Simulated data with a fixed random seed, created for this example.
No real respondents, documents or measurements: the numbers only illustrate how the chart and its statistics work. - Warin, d'Anglade & de Marcellis-Warin (2025), data science for waste reduction in manufacturing. Warin, T., d'Anglade, P. M., & de Marcellis-Warin, N. (2025). Optimising industrial efficiency: Integrating K-means clustering and data science for sustainable manufacturing and waste reduction. International Journal of Sustainable Engineering, 18(1), 2527300. https://doi.org/10.1080/19397038.2025.2527300
The example is set in the context of this paper; unless its description says otherwise, the numbers are simulated and are not the paper's data or results.
这些示例用于说明统计方法。除条目另有说明外,其数值均为模拟数据,图表标题描述的是该图在这些模拟数据中呈现的内容——既不是所引论文的结论,也不是作者对实质问题的立场。关于结果、背景和数据,请以此处引用的论文为准。
如何引用
PyStatlas 由 Thierry Warin 创建并维护。如果它对你的工作有所帮助,敬请引用。
Warin, T. (2026). Cross-validated model comparison. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/machine-learning/model-comparison/
@misc{warin2026statlas,
author = {Warin, Thierry},
title = {PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences},
year = {2026},
version = {1.1.0},
howpublished = {\url{https://warin.ca/pystatlas/}},
note = {Source code: https://github.com/warint/pystatlas}
}更多机器学习图表
带指标的混淆矩阵
分类器把推文归入环境、社会和治理主题的准确程度——样本外 3 × 3 混淆矩阵,并为各项指标给出自助法区间。
yardstick::conf_mat() + autoplot()精确率–召回率曲线
两个分类器预测哪些 Facebook 用户会分享 COVID-19 假新闻的样本外精确率–召回率曲线,附平均精确率与无技能基线。
yardstick::pr_curve() + autoplot()学习曲线
随着训练集增大,两个预测哪些 Facebook 用户会分享 COVID-19 假新闻的模型的训练准确率与交叉验证准确率。
caret::learning_curve_dat() + ggplot()