交差検証によるモデル比較
生産ロットの廃棄率を予測する 6 つのモデルの分割ごとの R²。平均と補正済み 95% 区間を添えます。

「モデル B は 0.47、モデル A は 0.46」と言っても、分割ごとにスコアがどれだけ変わるかが分からなければ意味がありません。ここでは各モデルを 同じ 10 × 5 の反復分割で評価します。各点がひとつの分割、大きなマーカーが平均、バーがその 95% 区間です。分割ごとのスコアは独立ではありません(訓練データが重なるため)。そこで区間には、狭すぎる素朴な標準誤差ではなく、Nadeau–Bengio の補正 分散を用いています。
例の舞台は、k-means クラスタリングとデータサイエンスを組み合わせて製造業の廃棄削減に取り組んだ Warin、d'Anglade、de Marcellis-Warin(2025 年、International Journal of Sustainable Engineering)の研究です。データは説明のために シミュレーション したもので、論文のデータや結果では ありません。n = 600 の生産ロットで、廃棄率(廃棄された材料の %)は機械速度、温度、作業者の経験に非線形に依存し、材料グレードにも依存し、さらに湿度と前回保守からの日数の交互作用にも依存します。ロットサイズには効果がありません。同じシミュレーションのロットを続く 5 つの図でも使います。スコアは 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()適合率–再現率曲線
COVID-19 のフェイクニュースを共有する Facebook ユーザーを予測する 2 つの分類器の、交差検証による適合率–再現率曲線。平均適合率と無技能の基準線を示します。
yardstick::pr_curve() + autoplot()学習曲線
学習データが増えるにつれての学習時正解率と交差検証正解率。COVID-19 のフェイクニュースを共有する Facebook ユーザーを予測する 2 つのモデルで比べます。
caret::learning_curve_dat() + ggplot()