机器学习与深度学习 / 系统课时
完成模型评估报告
完成模型评估报告
模型训练结束后,真正可交付的不是一个最高准确率,而是一份能复核测试口径、定位错误类型并说明边界的评估报告。本课把冻结测试集结果整理成指标、混淆矩阵、错误样本和可验收结论。
学习目标
- 固定测试集、模型版本与预测口径,避免评估结果被调参过程污染。
- 生成 Accuracy、Macro F1、逐类指标、混淆矩阵和错误样本清单。
- 用明确阈值写出通过或不通过的验收结论,并记录模型局限。
固定报告口径
评估报告至少固定四件事:测试数据版本、最终模型制品、唯一一次测试预测和可重算指标。调参与选模型只看 Validation;Test 一旦被反复用于选择参数,就不再是独立的最终验收集。
| 项目 | 可直接采用的记录方式 |
|---|---|
| 测试集 | test-v3,2430 条样本,类别分布 810/795/825 |
| 模型 | best-model.keras,同时记录文件 SHA256 |
| 推理口径 | float32、batch_size=64、多分类使用 argmax |
| 主指标 | Accuracy、Macro F1、每类 Precision/Recall/F1 |
| 错误证据 | sample_id、真实标签、预测标签、置信度、样本来源 |

这张关系图的关键限制是单向性:测试结果进入报告,但不能再回流去改学习率、阈值或网络结构。若必须修改模型,应重新回到 Validation 做选择,并为下一次正式验收准备新的独立测试集或明确记录测试集已被查看。
生成可复核指标
下面的完整示例用固定数组模拟一次测试集预测,并把报告写成 evaluation/report.json,同时把全部误分类样本写入 evaluation/error_samples.csv。真实项目只需要把 y_true、y_pred、confidence 和 sample_ids 替换为冻结测试集的真实结果。
from pathlib import Path
import csv
import json
import numpy as np
import tensorflow as tf
CLASS_NAMES = ["cat", "dog", "rabbit"]
y_true = np.array([0, 0, 0, 0, 1, 1, 1, 2, 2, 2], dtype=np.int32)
y_pred = np.array([0, 0, 1, 2, 1, 1, 0, 2, 2, 1], dtype=np.int32)
confidence = np.array(
[0.92, 0.81, 0.73, 0.68, 0.88, 0.79, 0.71, 0.83, 0.76, 0.66],
dtype=np.float32,
)
sample_ids = [f"sample-{i:03d}" for i in range(1, len(y_true) + 1)]
cm = tf.math.confusion_matrix(
y_true,
y_pred,
num_classes=len(CLASS_NAMES),
).numpy()
accuracy = float(np.mean(y_true == y_pred))
per_class = []
for class_id, class_name in enumerate(CLASS_NAMES):
tp = int(cm[class_id, class_id])
fp = int(cm[:, class_id].sum() - tp)
fn = int(cm[class_id, :].sum() - tp)
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
f1 = (
2 * precision * recall / (precision + recall)
if precision + recall
else 0.0
)
per_class.append(
{
"class": class_name,
"precision": round(precision, 4),
"recall": round(recall, 4),
"f1": round(f1, 4),
}
)
macro_f1 = float(np.mean([item["f1"] for item in per_class]))
report = {
"test_samples": int(len(y_true)),
"accuracy": round(accuracy, 4),
"macro_f1": round(macro_f1, 4),
"class_names": CLASS_NAMES,
"confusion_matrix": cm.tolist(),
"per_class": per_class,
}
out_dir = Path("evaluation")
out_dir.mkdir(exist_ok=True)
with (out_dir / "report.json").open("w", encoding="utf-8") as f:
json.dump(report, f, ensure_ascii=False, indent=2)
with (out_dir / "error_samples.csv").open(
"w",
encoding="utf-8",
newline="",
) as f:
writer = csv.writer(f)
writer.writerow(["sample_id", "y_true", "y_pred", "confidence"])
for sample_id, true_id, pred_id, score in zip(
sample_ids,
y_true,
y_pred,
confidence,
):
if true_id != pred_id:
writer.writerow(
[
sample_id,
CLASS_NAMES[int(true_id)],
CLASS_NAMES[int(pred_id)],
round(float(score), 4),
]
)
print(f"accuracy={report['accuracy']:.4f}")
print(f"macro_f1={report['macro_f1']:.4f}")
print("confusion_matrix=")
print(cm)
print(f"errors={int(np.sum(y_true != y_pred))}")预期输出(TensorFlow 自身的环境初始化日志可能因机器不同而额外出现):
accuracy=0.6000
macro_f1=0.6032
confusion_matrix=
[[2 1 1]
[1 2 0]
[0 1 2]]
errors=4这个脚本的产物可直接进入 CI 或报告生成流程;评审人只要拿到同一组 y_true 和 y_pred,就能重新计算核心数字,而不是依赖截图中的手工抄录结果。
解释混淆矩阵和错误样本
混淆矩阵按“行是真实类别、列是预测类别”读取。上例可展开为下表,其中对角线是正确预测,非对角线就是需要回看的错误方向。
| True \ Pred | cat | dog | rabbit |
|---|---|---|---|
| cat | 2 | 1 | 1 |
| dog | 1 | 2 | 0 |
| rabbit | 0 | 1 | 2 |
只看 Accuracy=0.60 会遗漏结构性问题:cat 的 Recall 是 2/4=0.50,说明一半真实 cat 被漏掉;dog 的 Precision 是 2/4=0.50,说明所有预测为 dog 的样本里有一半其实属于其他类;rabbit 的 Precision 与 Recall 都是 2/3≈0.667。
对应的错误样本是 sample-003 cat→dog(0.73)、sample-004 cat→rabbit(0.68)、sample-007 dog→cat(0.71)、sample-010 rabbit→dog(0.66)。对主要混淆方向按错误置信度从高到低各抽 10 个样本复核,通常比随机看几十个错误更快找到标签错误、输入质量问题或类间边界重叠。
写清局限和验收结论
验收阈值必须来自业务成本,不能在看完 Test 后再倒推。一个可直接复用的模板是:Macro F1 >= 0.90、所有关键类别 Recall >= 0.80、每 1000 个样本的关键漏检不超过 2 个。用这个模板检查上例,Macro F1=0.6032 且最差 Recall=0.50,因此结论应明确写“未通过”,而不是只展示若干看起来较高的局部指标。
局限性也要写成可验证陈述。例如“当前 Test 不含域外设备数据”“低照度样本不足 50 条”“尚未测量在线 p95 延迟”“标签只覆盖 3 类,未知类会被强制分到已知类别”。每条局限都应对应后续补测动作,而不是使用“泛化能力仍有提升空间”这类无法验证的表述。
最终报告应让第三方只凭数据版本、模型文件、指标脚本和错误样本清单就能复核结论;这比单独保存一张 Accuracy 截图更适合作为上线、回归和后续模型版本对比的基线。