機械学習モデルの比較表

繰り返し交差検証で 5 つの分類器を比較します。識別、分類、較正の指標を平均(標準偏差)で示し、最良値を太字にし、AUC の差を補正済み検定で調べます。

機械学習モデルの比較表

応用機械学習の論文で「モデル」の節を締めくくる表です。学習器ごとに 1 行でファミリー別にまとめ、指標ごとに 1 列を置きます。識別(ROC AUC、平均適合率)、しきい値 0.5 での分類(正解率、F1)、較正(ブライアスコア、対数損失)です。各セルは 5 分割交差検証を 4 回繰り返した平均で、括弧内は 20 個の分割にわたる標準偏差です。各列の最良値は太字です(2 つの較正損失では最小値)。

最後の列は、差が本物かどうかを問います。各分割は訓練データの大部分を共有するため、分割に対する単純な対応のある t 検定は楽観的すぎます。**Nadeau–Bengio の補正済み再標本化 t 検定は分散を 1/J + n_test/n_train 倍に膨らませるもので、標準的な対処法です。各モデルの AUC を最良のモデルと比べます。

設定は Melchior, Warin & Oliveira (2025) による Facebook 上のフェイクニュース検出の研究です。データは説明のためのシミュレーション**であり、論文のデータや結果ではありません。テキスト、発信元、拡散に関する 8 つの特徴量で記述した 1,500 件の投稿で、木のアンサンブルが見つけられるよう交互作用としきい値を含めています。モデルは scikit-learn(RepeatedStratifiedKFold を使った cross_validate)で、表は Great Tables で作ります。fmt_number() で数値を整え(その pattern 引数で最良の平均を太字に)、cols_merge() で各標準偏差を平均の下に置き、tab_stub() でモデルのファミリーをまとめ、gtsave() で PNG に書き出します。

コードおよび図中のテキストは英語です。

ml-model-comparison.py · 125 行
ダウンロード GitHub
import numpy as np
import pandas as pd
from scipy import stats
from great_tables import GT, loc, style
from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import RepeatedStratifiedKFold, cross_validate
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
# Simulated data, set in the context of Melchior, Warin & Oliveira (2025) [melchior2025fake]

# Data: 1,500 Facebook posts; fake posts are emotional, from low-credibility pages, shared in bursts
rng = np.random.default_rng(2025)
n = 1500
X = pd.DataFrame({
    "emotional_words": rng.gamma(2, 1.5, n), "exclamations": rng.poisson(1.2, n),
    "source_credibility": rng.uniform(0, 1, n), "page_age_years": rng.exponential(4, n),
    "share_burst": rng.gamma(1.5, 1, n), "links_out": rng.poisson(1.5, n),
    "headline_length": rng.normal(12, 4, n), "reading_level": rng.normal(9, 2.5, n),
})
eta = (-1.2 + 0.35 * X.emotional_words + 0.3 * X.exclamations - 2.5 * X.source_credibility
       + 1.4 * (X.page_age_years < 1)                                   # new pages: a threshold
       + 0.9 * X.share_burst * (X.source_credibility < 0.4)             # bursts matter on weak sources
       - 0.25 * X.links_out)
y = rng.binomial(1, 1 / (1 + np.exp(-eta)))

# Five learners in three families
models = {
    "Linear models": {
        "Logistic regression": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
        "Lasso logistic regression": make_pipeline(StandardScaler(), LogisticRegression(
            l1_ratio=1, solver="saga", C=0.1, max_iter=5000)),
    },
    "Nearest neighbours": {
        "k-nearest neighbours (k = 25)": make_pipeline(StandardScaler(), KNeighborsClassifier(25)),
    },
    "Tree ensembles": {
        "Random forest": RandomForestClassifier(300, min_samples_leaf=5, random_state=1, n_jobs=-1),
        "Gradient boosting": HistGradientBoostingClassifier(learning_rate=0.05, max_iter=200,
                                                            random_state=1),
    },
}

# Same 5 × 4 folds for every model, so the fold scores are paired
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=4, random_state=2025)
scoring = {"auc": "roc_auc", "ap": "average_precision", "acc": "accuracy", "f1": "f1",
           "brier": "neg_brier_score", "logloss": "neg_log_loss"}
scores, rows = {}, []
for family, learners in models.items():
    for name, model in learners.items():
        res = cross_validate(model, X, y, cv=cv, scoring=scoring)
        s = {k: res[f"test_{k}"] * (-1 if k in ("brier", "logloss") else 1) for k in scoring}
        scores[name] = s
        rows.append({"family": family, "model": name,
                     **{k: v.mean() for k, v in s.items()}, **{f"{k}_sd": v.std(ddof=1) for k, v in s.items()}})
tab = pd.DataFrame(rows)

# Nadeau–Bengio corrected resampled t-test of each model's AUC against the best one
best = tab.loc[tab.auc.idxmax(), "model"]
J = cv.get_n_splits()                                     # 20 paired fold scores
ratio = 1 / (5 - 1)                                       # n_test / n_train with 5 folds
for i, name in enumerate(tab.model):
    if name == best:
        tab.loc[i, "gap"], tab.loc[i, "stars"] = np.nan, "(reference)"
        continue
    d = scores[name]["auc"] - scores[best]["auc"]
    t = d.mean() / np.sqrt((1 / J + ratio) * d.var(ddof=1))
    p = 2 * stats.t.sf(abs(t), J - 1)
    tab.loc[i, "gap"] = d.mean()
    tab.loc[i, "stars"] = "***" if p < .01 else "**" if p < .05 else "*" if p < .1 else ""

metrics = list(scoring)
higher_is_better = {"auc": True, "ap": True, "acc": True, "f1": True, "brier": False, "logloss": False}
table = (
    GT(tab)
    .tab_stub(rowname_col="model", groupname_col="family")
    .tab_stub_indent(rows=list(range(len(tab))), indent=2)
    .tab_header(title="TABLE III", subtitle="Out-of-sample performance of five classifiers")
    .fmt_number(columns=metrics + [f"{k}_sd" for k in metrics] + ["gap"], decimals=3)
    .sub_missing(columns=["gap", "stars"], missing_text="")
    .cols_merge(columns=["gap", "stars"], pattern="{0}{1}")
)
for k in metrics:                                          # best mean of each column in bold
    i = int(tab[k].idxmax() if higher_is_better[k] else tab[k].idxmin())
    table = table.fmt_number(columns=k, rows=[i], decimals=3, pattern="<strong>{x}</strong>")
for k in metrics:                                          # mean, then (SD) on the line below
    table = table.cols_merge(columns=[k, f"{k}_sd"], pattern="{0}<br>({1})")
table = (
    table
    .tab_spanner(label="Discrimination", columns=["auc", "ap"], id="disc")
    .tab_spanner(label="Classification", columns=["acc", "f1"], id="class")
    .tab_spanner(label="Calibration", columns=["brier", "logloss"], id="calib")
    .cols_label(auc="ROC AUC", ap="Avg. precision", acc="Accuracy", f1="F1",
                brier="Brier score", logloss="Log loss", gap="ΔAUC vs. best")
    .cols_align("center", columns=metrics + ["gap"])
    .tab_source_note(f"Notes: n = {n:,} posts (simulated), {y.mean():.0%} fake. Mean over 5-fold cross-validation "
                     f"repeated 4 times; SD across the {J} folds in parentheses. Bold: best in column.")
    .tab_source_note(f"ΔAUC: difference from the best model ({best}), Nadeau–Bengio corrected resampled "
                     "t-test: *p < 0.1; **p < 0.05; ***p < 0.01.")
    # Same journal look as Tables I and II: serif type, small-caps title, horizontal rules only
    .opt_table_font(font=["Latin Modern Roman", "Times New Roman", "Georgia", "serif"])
    .tab_options(
        table_width="960px", table_font_size="15px", table_font_color="#000",
        heading_title_font_size="15px", heading_subtitle_font_size="15px", heading_padding="1px",
        table_border_top_style="hidden", table_border_bottom_style="hidden",
        heading_border_bottom_style="none",
        column_labels_border_top_style="solid", column_labels_border_top_width="1.5px",   # top rule
        column_labels_border_top_color="#000",
        column_labels_border_bottom_style="solid", column_labels_border_bottom_width="1px",
        column_labels_border_bottom_color="#000",
        table_body_border_top_style="solid", table_body_border_top_width="1px",
        table_body_border_top_color="#000",
        row_group_border_top_style="none", row_group_border_bottom_style="none",
        row_group_padding="6px",
        table_body_hlines_style="none", stub_border_style="none",
        table_body_border_bottom_style="solid", table_body_border_bottom_width="1.5px",
        table_body_border_bottom_color="#000",
        data_row_padding="3px", source_notes_font_size="13px", source_notes_padding="1px",
    )
    .tab_style(style.css("font-variant: small-caps; padding-bottom: 8px;"), loc.subtitle())
    .tab_style(style.text(style="italic"),
               [loc.row_groups(), loc.spanner_labels(ids=["disc", "class", "calib"])])
)
table.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.
  • Melchior, Warin & Oliveira (2025), COVID-19 fake-news sharing on Facebook. Melchior, C., Warin, T., & Oliveira, M. (2025). An investigation of the COVID-19-related fake news sharing on Facebook using a mixed methods approach. Technological Forecasting and Social Change, 213, 123969. https://doi.org/10.1016/j.techfore.2024.123969
    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). Machine learning model comparison table. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/academic-tables/ml-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}
}

学術論文の表のその他のグラフ