ROC 曲線
3つの分類器を ROC 曲線、ブートストラップ 95% 信頼区間付きの AUC、ユーデン点で比較します。

ROC 曲線は、判定の閾値を厳しい側から緩い側へ動かしたときの、感度と 1 − 特異度の関係をたどったものです。対角線はコイン投げに相当し、曲線が左上の角に近いほど優れています。AUC は、無作為に選んだ陽性例が無作為に選んだ陰性例より高いスコアを得る確率です。その 95% 信頼区間はテストセットの 1,000 回のブートストラップ再標本化から求め、対応のあるブートストラップで最良と最弱のモデルを比較しています。各曲線上の点は、ユーデンの J = 感度 + 特異度 − 1 を最大にする閾値です。
設定は Marty & Warin (2025, Journal of Economy and Technology) による、アルゴリズムによる共謀と競争法執行への示唆の研究です。データは説明のために シミュレーション したもので、論文のデータや結果ではありません。n = 2,000 市場・週(約 20% が共謀)を5つの特徴量(価格水準、コスト指数、価格のボラティリティ、同期した価格変更の割合、コストショックへの反応の遅れ)で記述し、70/30 に分割しています。共謀は価格とコストの差、および同期して かつ 硬直的な価格に現れますが、特徴量を独立とみなすナイーブベイズはこれらを組み合わせられません。scikit-learn のロジスティック回帰、ランダムフォレスト、ナイーブベイズが共謀の局面を検出し、曲線と AUC は roc_curve() と roc_auc_score() から得ています。
コードおよび図中のテキストは英語です。
import matplotlib.pyplot as plt
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, roc_curve
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
# Simulated data, set in the context of Marty & Warin (2025) [marty2025collusion]
# Data: 2,000 market-weeks; collusion is likeliest when price moves are synchronised AND sticky
rng = np.random.default_rng(2025)
n = 2000
cost, sync, lag = rng.normal(size=(3, n)) # cost index, synchrony, lag (z)
y = rng.binomial(1, np.where((sync > 0.3) & (lag > 0.3), 0.55, 0.12))
X = np.column_stack([
1.5 * cost + 0.7 * y + rng.normal(0, 0.6, n), # price level (tracks cost)
1.5 * cost + rng.normal(0, 0.6, n), # cost index
-0.5 * y + rng.normal(0, 1, n), # price volatility
sync, lag]) # synchronised changes, lag to cost shocks
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, stratify=y, random_state=1)
models = {"Logistic regression": LogisticRegression(max_iter=1000),
"Random forest": RandomForestClassifier(300, min_samples_leaf=20, random_state=1),
"Naive Bayes": GaussianNB()}
palette = ["#007AFF", "#FF9500", "#34C759"]
boot = [rng.integers(0, len(y_te), len(y_te)) for _ in range(1000)]
fig, ax = plt.subplots(figsize=(7, 6.4))
ax.plot([0, 1], [0, 1], color="#AEAEB2", lw=1, ls="--")
scores = {}
for (name, clf), c, dx in zip(models.items(), palette, (-10, -10, 10)):
score = scores[name] = clf.fit(X_tr, y_tr).predict_proba(X_te)[:, 1]
fpr, tpr, thr = roc_curve(y_te, score)
auc = roc_auc_score(y_te, score)
lo, hi = np.percentile([roc_auc_score(y_te[b], score[b]) for b in boot], [2.5, 97.5])
ax.plot(fpr, tpr, color=c, lw=2.2, label=f"{name} AUC {auc:.3f} [{lo:.3f}, {hi:.3f}]")
# Youden's J: threshold that maximises TPR − FPR
j = np.argmax(tpr - fpr)
ax.scatter(fpr[j], tpr[j], s=70, color=c, edgecolor="white", lw=2, zorder=5)
ax.annotate(f"J = {tpr[j] - fpr[j]:.2f}", (fpr[j], tpr[j]), xytext=(dx, 0),
textcoords="offset points", fontsize=8.5, color=c, ha="right" if dx < 0 else "left",
va="top" if dx > 0 else "center",
bbox=dict(boxstyle="round,pad=0.15", fc="white", ec="none", alpha=0.9))
# Paired bootstrap: is the best model really better than the weakest?
a, b = scores["Logistic regression"], scores["Naive Bayes"]
diff = [roc_auc_score(y_te[i], a[i]) - roc_auc_score(y_te[i], b[i]) for i in boot]
d_lo, d_hi = np.percentile(diff, [2.5, 97.5])
ax.set_xlim(-0.01, 1.01); ax.set_ylim(-0.01, 1.01); ax.set_aspect("equal")
ax.grid(axis="x")
ax.set_xlabel("1 − specificity (false-positive rate)")
ax.set_ylabel("Sensitivity (true-positive rate)")
ax.legend(loc="lower right", title="Model · AUC [bootstrap 95% CI]", alignment="left",
handlelength=1.4, fontsize=9.5)
ax.set_title("Logistic regression and forest tie; naive Bayes trails", pad=42)
ax.text(0, 1.02, f"Test set n = {len(y_te):,} market-weeks (simulated, {y_te.mean():.0%} collusive) · dots = Youden\n"
f"ΔAUC logistic − naive Bayes = {roc_auc_score(y_te, a) - roc_auc_score(y_te, b):.3f} "
f"[{d_lo:.3f}, {d_hi:.3f}] (paired bootstrap, 1,000 resamples)",
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. - Marty & Warin (2025), algorithmic collusion and antitrust. Marty, F., & Warin, T. (2025). Deciphering algorithmic collusion: Insights from bandit algorithms and implications for antitrust enforcement. Journal of Economy and Technology, 3, 34–43. https://doi.org/10.1016/j.ject.2024.10.001
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). ROC curves. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/model-diagnostics/roc-curve/
@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}
}