学习曲线
随着训练集增大,两个预测哪些 Facebook 用户会分享 COVID-19 假新闻的模型的训练准确率与交叉验证准确率。

在收集更多数据之前,学习曲线回答两个问题:模型是否 过拟合(训练得分与交叉验证得分差距大),还是 欠拟合(两个得分都低且接近)?更多观测是否还有帮助(验证曲线是否仍在上升)?线条为重复交叉验证各折的均值;条带为 ±1 个标准差,其宽度显示换一种划分时估计会变动多少。
在同一任务上比较两个模型:一棵会记住训练集的深决策树,以及一个标准化的逻辑回归。本例以 Melchior、Warin 和 Oliveira(2025,Technological Forecasting and Social Change)的研究为背景,该研究采用混合方法考察 Facebook 上与 COVID-19 相关的假新闻分享。数据为说明用途而 模拟,并非 论文的数据或结果:n = 3,000 名用户,其中约八分之一分享过假新闻,用年龄、使用 Facebook 的时间、加入的 COVID-19 群组、对主流媒体的信任、阴谋论信念以及分享过假新闻的朋友占比来描述。曲线来自 sklearn.model_selection.learning_curve,采用 5 × 2 重复分层划分。虚线为多数类基线:类别稀少时,准确率必须对照它来解读;这里逻辑回归仅勉强超过它——增加用户无济于事,更好的预测变量才有用。
代码及图中文字均为英文。
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import RepeatedStratifiedKFold, learning_curve
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier
# Simulated data, set in the context of Melchior, Warin & Oliveira (2025) [melchior2025fake]
# Data: 3,000 Facebook users; 1 = shared a COVID-19 fake-news post (a minority class)
rng = np.random.default_rng(2024)
n = 3000
X = pd.DataFrame({"age": rng.integers(18, 80, n), # years
"hours": rng.gamma(2, 0.9, n), # daily hours on Facebook
"groups": rng.poisson(3, n), # COVID-19 groups joined
"trust_media": rng.integers(1, 8, n), # 1-7 scale
"conspiracy": rng.integers(1, 8, n), # 1-7 scale
"friends_shared": rng.beta(1, 8, n)}) # share of friends who shared
logit = (-4.3 + 0.025 * (X.age - 45) + 0.35 * X.hours + 0.15 * X.groups
- 0.3 * (X.trust_media - 4) + 0.45 * (X.conspiracy - 4) + 6 * X.friends_shared)
y = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int).to_numpy()
baseline = 1 - y.mean()
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=2, random_state=0)
sizes = np.linspace(0.08, 1.0, 10)
models = {"Decision tree": DecisionTreeClassifier(random_state=0),
"Logistic regression": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))}
plt.rcParams["figure.constrained_layout.use"] = False # manual margins leave room for the subtitle
fig, axes = plt.subplots(1, 2, figsize=(10, 5), sharey=True)
fig.subplots_adjust(left=0.08, right=0.97, top=0.80, bottom=0.12, wspace=0.12)
for ax, (name, model) in zip(axes, models.items()):
m_, train, valid = learning_curve(model, X, y, cv=cv, train_sizes=sizes, n_jobs=-1,
shuffle=True, random_state=0)
ax.axhline(baseline, color="#8E8E93", ls="--", lw=1)
for scores, c, lab in [(train, "#8E8E93", "Training"), (valid, "#007AFF", "Cross-validated")]:
m, s = scores.mean(axis=1), scores.std(axis=1)
ax.fill_between(m_, m - s, m + s, color=c, alpha=0.18, lw=0)
ax.plot(m_, m, color=c, lw=2.2, marker="o", ms=4)
dy = 0.012 if lab == "Training" else -0.012
ax.text(m_[-1] + 40, m[-1] + dy, lab, va="center", fontsize=9.5, color=c, fontweight="semibold")
gap = train.mean(axis=1)[-1] - valid.mean(axis=1)[-1]
ax.annotate("", xy=(m_[-1], valid.mean(axis=1)[-1]), xytext=(m_[-1], train.mean(axis=1)[-1]),
arrowprops=dict(arrowstyle="<->", color="#FF3B30", lw=1.2))
ax.text(m_[-1] - 50, valid.mean(axis=1)[-1] + (gap / 2 if gap > 0.05 else -0.04), f"gap {gap:.2f}",
ha="right", va="center", fontsize=9.5, color="#FF3B30", fontweight="semibold")
ax.set_title(name)
ax.set_xlabel("Training observations")
ax.set_xlim(0, m_[-1] * 1.32)
axes[0].text(60, baseline + 0.008, f"majority-class baseline {baseline:.2f}", fontsize=9, color="#6E6E73")
axes[0].set_ylabel("Accuracy")
axes[0].set_ylim(0.7, 1.02)
fig.suptitle("The tree memorises its training set; logistic regression plateaus just above the baseline",
x=0.02, y=0.97, ha="left")
fig.text(0.02, 0.885, f"n = {n:,} users (simulated), {y.mean():.0%} shared fake news · "
"5-fold × 2 repeats · lines = mean, bands = ±1 SD across folds",
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. - 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). Learning curve. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/machine-learning/learning-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}
}更多机器学习图表
带指标的混淆矩阵
分类器把推文归入环境、社会和治理主题的准确程度——样本外 3 × 3 混淆矩阵,并为各项指标给出自助法区间。
yardstick::conf_mat() + autoplot()精确率–召回率曲线
两个分类器预测哪些 Facebook 用户会分享 COVID-19 假新闻的样本外精确率–召回率曲线,附平均精确率与无技能基线。
yardstick::pr_curve() + autoplot()交叉验证模型比较
六个模型预测生产批次废料率的逐折 R²,附均值与校正后的 95% 区间。
caret::resamples() + bwplot() / tune::autoplot()