带指标的混淆矩阵
分类器把推文归入环境、社会和治理主题的准确程度——样本外 3 × 3 混淆矩阵,并为各项指标给出自助法区间。

混淆矩阵将真实类别与预测类别交叉列出。每个格子显示计数及其在真实类别(行)中的占比,因此对角线可直接读作各类别的召回率,而非对角线格子显示模型混淆了哪些类别。预测为 样本外(out-of-fold) 预测:在 10 折交叉验证中,每个观测都由一个从未见过它的模型来预测——这正是矩阵在新数据上的样子。
本例以 Kouloukoui、de Marcellis-Warin、Gomes 和 Warin(2023,Journal of Cleaner Production)的研究为背景,该研究用自然语言处理描绘 Twitter 上关于环境、社会和治理(ESG)话题的讨论。数据为说明用途而 模拟,并非 论文的数据或结果:n = 900 条推文,每条用六个小型主题词表(每个 ESG 支柱两个)中的词频来描述,并有意让社会与治理词汇相互重叠。模型为标准化的多项逻辑回归;预测来自 cross_val_predict,指标(精确率、召回率和 F1 的宏平均、准确率、MCC,均附 95% 自助法区间)来自 sklearn.metrics。
代码及图中文字均为英文。
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (accuracy_score, confusion_matrix, f1_score, matthews_corrcoef,
precision_score, recall_score)
from sklearn.model_selection import StratifiedKFold, cross_val_predict
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
# Simulated data, set in the context of Kouloukoui et al. (2023) [kouloukoui2023esg]
# Data: 900 tweets, true topic 0 = E, 1 = S, 2 = G; features = hits on six topic lexicons
rng = np.random.default_rng(2023)
labels = ["Environmental", "Social", "Governance"]
y = rng.choice(3, size=900, p=[0.45, 0.30, 0.25])
lam = np.array([[2.0, 1.6, 0.3, 0.3, 0.2, 0.2], # expected lexicon hits for an E tweet
[0.3, 0.3, 1.4, 1.0, 0.8, 0.6], # S tweets borrow governance words ...
[0.3, 0.2, 0.7, 0.6, 1.3, 1.1]]) # ... and G tweets social ones
X = np.log1p(rng.poisson(lam[y]))
# Out-of-fold predictions from a 10-fold cross-validation
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
cv = StratifiedKFold(n_splits=10, shuffle=True, random_state=0)
pred = cross_val_predict(model, X, y, cv=cv)
cm = confusion_matrix(y, pred)
# Metrics (macro-averaged over the three classes) with 95% bootstrap intervals
metrics = {"Accuracy": accuracy_score,
"Precision": lambda a, b: precision_score(a, b, average="macro"),
"Recall": lambda a, b: recall_score(a, b, average="macro"),
"F1": lambda a, b: f1_score(a, b, average="macro"), "MCC": matthews_corrcoef}
boot = {k: [] for k in metrics}
for _ in range(1000):
i = rng.integers(0, len(y), len(y))
for k, f in metrics.items():
boot[k].append(f(y[i], pred[i]))
point = {k: f(y, pred) for k, f in metrics.items()}
ci = {k: np.percentile(v, [2.5, 97.5]) for k, v in boot.items()}
plt.rcParams["figure.constrained_layout.use"] = False # manual margins leave room for the subtitle
fig, (ax, axm) = plt.subplots(1, 2, figsize=(10, 5), gridspec_kw=dict(width_ratios=(1, 1)))
fig.subplots_adjust(left=0.13, right=0.97, top=0.80, bottom=0.13, wspace=0.42)
# Confusion matrix: colour = share of the true class
share = cm / cm.sum(axis=1, keepdims=True)
ax.imshow(share, cmap="Blues", vmin=0, vmax=1)
for r in range(3):
for c in range(3):
ax.text(c, r, f"{cm[r, c]}\n{share[r, c]:.0%}", ha="center", va="center", fontsize=11.5,
fontweight="semibold", color="white" if share[r, c] > 0.5 else "#1d1d1f")
ax.set_xticks(range(3), ["E", "S", "G"])
ax.set_yticks(range(3), labels)
ax.set_xlabel("Predicted topic")
ax.set_ylabel("True topic")
ax.grid(False)
for s in ax.spines.values():
s.set_visible(False)
# Metrics with intervals
names = list(metrics)[::-1]
for j, k in enumerate(names):
axm.plot(ci[k], [j, j], color="#007AFF", lw=3, solid_capstyle="round", alpha=0.35)
axm.scatter(point[k], j, s=70, color="#007AFF", zorder=3, edgecolor="white", lw=1.5)
axm.text(ci[k][1] + 0.01, j, f"{point[k]:.2f} [{ci[k][0]:.2f}, {ci[k][1]:.2f}]",
va="center", fontsize=9.5, color="#3A3A3C")
axm.set_yticks(range(len(names)), names)
axm.set_xlim(0.4, 1.0)
axm.set_xlabel("Score (out-of-fold, macro average, 95% bootstrap CI)")
axm.grid(axis="x"); axm.grid(axis="y", visible=False)
sg = cm[1, 2] + cm[2, 1]
fig.suptitle(f"{point['Accuracy']:.0%} of tweets get the right topic; {sg} of the "
f"{len(y) - np.trace(cm)} errors mix up S and G", x=0.02, y=0.97, ha="left")
fig.text(0.02, 0.885, f"Multinomial logistic regression · 10-fold out-of-fold predictions · n = {len(y)} "
"tweets (simulated) · 1,000 bootstrap resamples", 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. - Kouloukoui et al. (2023), global conversations on ESG topics. Kouloukoui, D., de Marcellis-Warin, N., Gomes, S. M. S., & Warin, T. (2023). Mapping global conversations on twitter about environmental, social, and governance topics through natural language processing. Journal of Cleaner Production, 414, 137369. https://doi.org/10.1016/j.jclepro.2023.137369
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). Confusion matrix with metrics. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/machine-learning/confusion-matrix/
@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}
}更多机器学习图表
精确率–召回率曲线
两个分类器预测哪些 Facebook 用户会分享 COVID-19 假新闻的样本外精确率–召回率曲线,附平均精确率与无技能基线。
yardstick::pr_curve() + autoplot()学习曲线
随着训练集增大,两个预测哪些 Facebook 用户会分享 COVID-19 假新闻的模型的训练准确率与交叉验证准确率。
caret::learning_curve_dat() + ggplot()交叉验证模型比较
六个模型预测生产批次废料率的逐折 R²,附均值与校正后的 95% 区间。
caret::resamples() + bwplot() / tune::autoplot()