机器学习模型比较表
用重复交叉验证比较五个分类器——区分度、分类和校准指标以均值(标准差)表示,最优值加粗,并对 AUC 差距做校正检验。

应用机器学习论文中“模型”一节的收尾表格:每个学习器一行,按模型族分组,每个指标一列——区分度(ROC AUC、平均精确率)、阈值 0.5 下的分类(准确率、F1)和校准(Brier 分数、对数损失)。每个单元格是重复 4 次的 5 折交叉验证的均值,括号中是 20 个折的标准差;每列的最优值加粗(两个校准损失取最小值)。
最后一列检验差距是否真实。各折共享大部分训练数据,因此对各折做简单的配对 t 检验过于乐观;**Nadeau–Bengio 校正重抽样 t 检验把方差放大 1/J + n_test/n_train 倍,是常用的修正方法。它把每个模型的 AUC 与最优模型比较。
背景是 Melchior, Warin & Oliveira (2025) 关于在 Facebook 上识别假新闻的研究。数据为说明用的模拟数据**,并非论文的数据或结果:1,500 条帖子,由其文本、来源和传播的八个特征描述,并加入交互和阈值,让树集成模型有可发现的结构。模型来自 scikit-learn(cross_validate 配合 RepeatedStratifiedKFold);表格用 Great Tables 构建:fmt_number() 格式化数字(其 pattern 参数把最优均值加粗),cols_merge() 把每个标准差放在均值下方,tab_stub() 按模型族分组,gtsave() 导出 PNG。
代码及图中文字均为英文。
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}
}