PAYATHON 2026

如何生成二分类 Confusion Matrix 并导出为 json 文件?

技术老齐

先将模型输出转换为 0/1 类别,再合并各个 batch 的结果,就可以计算二分类混淆矩阵。导出 JSON 时,用 .tolist() 将矩阵转为 Python 列表,再调用 json.dump()。

以下代码适用于每个样本输出一个原始 logit 的模型,输出形状为 [batch_size] 或 [batch_size, 1],配合现有的 nn.BCEWithLogitsLoss() 使用。

两个报错分别是什么原因?

sklearn 收到了连续预测值

BCEWithLogitsLoss 接收的 logits 是连续数值,不能直接作为预测类别传给 confusion_matrix()。先将它们转换为类别:

probabilities = torch.sigmoid(logits)
predictions = (probabilities >= 0.5).long()

这里将概率大于或等于 0.5 的样本预测为类别 1。使用这个阈值时,也可以直接写:

predictions = (logits >= 0).long()

logits.long() 只会转换数值类型,不能代替分类判断。

TorchMetrics 收到了 Python 列表

原代码通过以下方式收集结果:

y_true.append(y)
y_pred.append(output)

这样得到的是 Tensor 列表,每个元素对应一个 batch。TorchMetrics 需要的是 Tensor,访问列表的 .shape 时就会报错。

用 torch.cat() 沿样本维度拼接即可:

y_true = torch.cat(y_true, dim=0)
y_pred = torch.cat(y_pred, dim=0)

即使最后一个 batch 的长度与其他 batch 不同,torch.cat() 也能正常拼接。

使用 sklearn 计算并导出 JSON

创建优化器前,先将模型移动到对应设备:

device = "cuda" if torch.cuda.is_available() else "cpu"
model = model.to(device)

optim = torch.optim.Adam(model.parameters(), lr=1e-3)

将原代码中从 test_loss = 0.0 开始的测试部分替换为以下代码,沿用已有的 test_loader、normalize、loss_fn 和 model_save_dir。

import json

import torch
from sklearn.metrics import confusion_matrix

threshold = 0.5
test_loss = 0.0
true_batches = []
pred_batches = []

model.eval()

with torch.no_grad():
    for x, y in test_loader:
        x = normalize(x.to(device))
        targets = y.to(device=device, dtype=torch.float32).reshape(-1)

        output = model(x)

        # 仅适用于每个样本输出一个 logit 的二分类模型。
        if output.shape != targets.shape and output.shape != (
            targets.numel(), 1
        ):
            raise ValueError(
                f"Expected one logit per sample, got {tuple(output.shape)}"
            )

        logits = output.reshape(-1)

        # BCEWithLogitsLoss 使用原始 logits 和浮点标签。
        loss = loss_fn(logits, targets)
        test_loss += loss.item() * targets.numel()

        # 混淆矩阵使用离散类别标签。
        probabilities = torch.sigmoid(logits)
        predictions = (probabilities >= threshold).long()

        true_batches.append(targets.long().cpu())
        pred_batches.append(predictions.cpu())

if not true_batches:
    raise ValueError("The test loader produced no samples.")

y_true = torch.cat(true_batches, dim=0)
y_pred = torch.cat(pred_batches, dim=0)

test_loss /= y_true.numel()

# 固定类别顺序,即使测试集中缺少某一类,也保留 2×2 矩阵。
cm = confusion_matrix(
    y_true.numpy(),
    y_pred.numpy(),
    labels=[0, 1],
)

print(f"Test BCE loss: {test_loss:.6f}")
print(cm)

tn, fp, fn, tp = cm.ravel()

payload = {
    "labels": [0, 1],
    "positive_label": 1,
    "threshold": threshold,
    "row_axis": "true",
    "column_axis": "predicted",
    "matrix": cm.tolist(),
    "counts": {
        "tn": int(tn),
        "fp": int(fp),
        "fn": int(fn),
        "tp": int(tp),
    },
    "num_samples": int(y_true.numel()),
}

model_save_dir.mkdir(parents=True, exist_ok=True)
json_path = model_save_dir / "confusion_matrix.json"

with json_path.open("w", encoding="utf-8") as f:
    json.dump(payload, f, ensure_ascii=False, indent=2)

print(f"Saved to: {json_path.resolve()}")

训练和验证时,传入 BCEWithLogitsLoss 的预测与标签也要保持形状一致。对于上述单 logit 模型,可以统一写成:

logits = model(x).reshape(-1)
targets = y.to(dtype=torch.float32).reshape(-1)
loss = loss_fn(logits, targets)

sigmoid 只用于生成分类预测,计算 BCEWithLogitsLoss 时仍然传入原始 logits。

如何读取矩阵?

当 labels=[0, 1] 且类别 1 为正类时,矩阵的行表示真实类别,列表示预测类别:

真实类别 \ 预测类别 0 1
0 TN FP
1 FN TP

对应的矩阵结构为:

[[TN, FP],
 [FN, TP]]

现有标签代码将 label == "(N" 的样本标为 0,其他样本标为 1。为 JSON 添加类别名称前,应先核对这一规则是否对应预期的窦性心律与房颤类别。

JSON 不能直接序列化 NumPy 数组或 PyTorch Tensor。代码中的 cm.tolist() 和 int(...) 用于将结果转换为 JSON 支持的数据类型。

如果改用 TorchMetrics

如果安装的 TorchMetrics 提供 BinaryConfusionMatrix,可以保留前面的测试循环和 Tensor 拼接,只替换 sklearn 计算矩阵的部分:

from torchmetrics.classification import BinaryConfusionMatrix

metric = BinaryConfusionMatrix()

# 注意参数顺序:预测在前,真实标签在后。
cm_tensor = metric(y_pred, y_true)

# 转成 NumPy 数组,以复用前面的 JSON 导出代码。
cm = cm_tensor.cpu().numpy()

这里传入的 y_pred 和 y_true 都是整数 Tensor,其中 y_pred 保存预测类别,避免了直接传入 batch 列表的问题。

两个库的参数顺序不同:

# sklearn
confusion_matrix(y_true, y_pred, labels=[0, 1])

# TorchMetrics
metric(y_pred, y_true)

测试集较大时,可以在每个 batch 中调用 metric.update(predictions, targets.long()),最后调用 metric.compute(),无需保存全部预测。此时,指标与输入 Tensor 应放在同一设备上,重新评估前还需调用 metric.reset()。

原代码中还需要注意的地方

  • 模型最后一层需要与损失函数匹配。上述方案要求模型输出原始 logits。如果模型内部已经执行了 sigmoid,应调整输出,避免将概率传入 BCEWithLogitsLoss。如果输出形状为 [batch_size, 2],则应按两个类别的分数处理,通常使用 argmax(dim=1),不能套用单 logit 的展平逻辑。
  • train_ds.dataset 指向完整数据集,用它计算归一化参数会包含验证集和测试集。原代码又除以 len(train_ds),导致统计范围与分母不一致。应只遍历 train_ds,再将训练集得到的参数用于验证和测试。另外,逐样本标准差的平均值不等于整个训练集的标准差。
  • 原代码按 batch 累加 loss.item() * batch_size。计算样本平均损失时,训练和验证损失应分别除以 len(train_ds)、len(val_ds),而不是 DataLoader 的 batch 数。
  • 要保存验证损失最低的模型,应将初始最佳损失设为 float("inf"),仅在损失下降时更新。测试前加载该检查点,才能得到它对应的混淆矩阵。
  • 这里使用的分类阈值是 0.5。如需调整,应在验证集上选择阈值,再固定该值评估测试集,并在 JSON 中记录实际使用的阈值。

备注:内容仅供参考。