蓝色天空.知识 · 实践 · 创造
我的收藏
PyTorch 教程目录 39章
PyTorch / LEARN BY DOING

PyTorch 模型评估与调试

核对训练/验证损失曲线与过拟合诊断、深拷贝早停机制、零外部依赖混淆矩阵与 F1、学习率/梯度裁剪、参数/MACs 钩子及 PyTorch CPU Profiler。

学完这一章,你能够

  • 核对训练/验证损失曲线与过拟合诊断、深拷贝早停机制、零外部依赖混淆矩阵与 F1、学习率/梯度裁剪、参数/MACs 钩子及 PyTorch CPU Profiler。

训练/验证损失曲线分析与过拟合/欠拟合处理

系统化的评估与调试始于监控训练损失与验证损失曲线:两者同步下降代表学习正常;训练持续下降而验证停滞或回升属于过拟合(模型记忆训练噪声而非通用模式);训练损失完全不降常源于学习率或架构问题;剧烈震荡多因学习率过高或 batch 过小。本站在 3 类合成数据上对比正则化模型(Dropout(0.25)+weight_decay=2e-2)与小样本无正则大网络 30 轮训练:正则化验证损失由 0.55347 降至 0.01854(泛化差值仅 0.01414),而过拟合组训练损失归零(0.0)但验证损失高达 0.22531(高出正则化组 12 倍)。

应对过拟合可综合采用增广数据、Dropout、权重衰减、精简容量与早停(Early Stopping);应对欠拟合则可增加容量、延长训练、减弱正则或调大学习率。实现早停必须修正来源代码两处关键缺陷:(1)model.state_dict().copy() 只是浅拷贝字典,内部张量共享内存会在后续训练步骤中被原位污染(本站已实测复现原位加 5.0 后浅拷贝被篡改),应改为 {k: v.detach().clone() for k, v in model.state_dict().items()} 或 copy.deepcopy;(2)触发早停后训练循环必须执行 break 才能真正提前终止。本站实测 patience=2 的早停器在第 4 轮准确跳出并完美恢复第 2 轮最优权重。

零外部依赖混淆矩阵与精确率/召回率/F1 评估

分类任务除总体准确率外,需用混淆矩阵统计各类真阳性、假阳性与假阴性并导出精确率(Precision)、召回率(Recall)与宏/微平均 F1。来源脚本依赖第三方 scikit-learn 与 seaborn(当前精简 PyTorch 环境未预装),本站改用纯 PyTorch/NumPy 直接统计 3×3 混淆矩阵:在 90 条留出验证集上得到 [[30, 0, 0], [1, 34, 0], [0, 0, 25]],总体准确率 98.89%、宏平均 F1 达 98.97%。下图展示本次实测的正则化/过拟合损失曲线对比与 3×3 混淆矩阵热力图。

正则化与过拟合训练/验证损失对比曲线及 3 类别留出混淆矩阵热力图。
本站 PyTorch CPU 实测的训练/验证损失诊断与 3×3 混淆矩阵。

学习率调度与梯度消失/爆炸诊断裁剪

搭配 StepLR、MultiStepLR、CosineAnnealingLR、ReduceLROnPlateau 及 Warmup 等调度器能兼顾前期收敛速度与后期精细微调(注意在训练循环中补全已定义的 optimizer 并保持 optimizer.step() 先于 scheduler.step())。本站验证 StepLR(step_size=2, gamma=0.5) 产出 [0.1, 0.1, 0.05, 0.05]、ReduceLROnPlateau 在指标停滞后准确折半至 0.05。针对深层网络梯度消失/爆炸,可通过监控各参数 grad 范数并用 nn.utils.clip_grad_norm_(params, max_norm=1.0) 保护:本站构造 5 层放大线性网络实测原始梯度范数达 303,871.5,经裁剪后精确压制在 1.0。

参数量/FLOPs 统计、推理耗时、排障与 PyTorch Profiler

性能画像包含参数量、计算量(MACs/FLOPs)、推理延迟与内存占用。在未安装外部 thop 库时,可用纯 PyTorch 前向钩子(register_forward_hook)统计 Conv2d 与 Linear 乘加次数:本站对轻量 CNN([1, 3, 16, 16])精确测得总参数 869、MACs 55,936(约 111,872 FLOPs),在 inference_mode() 下预热后 30 次平均 CPU 推理耗时 0.0948 ms。当前纯 CPU 环境 cuda_available=False,GPU 显存监控(torch.cuda.memory_allocated)保留为 GPU 阶段核验项。

日常排障可按症状对照速查表逐项排查(如检查学习率、数据预处理、梯度范数、NaN 检测 autograd.detect_anomaly 及单批次过拟合测试)。需要算子级耗时定位时,使用官方 torch.profiler.profile(activities=[ProfilerActivity.CPU], record_shapes=True) 采集真实算子表:本站实测捕获 22 条 CPU 算子事件,主耗时算子定位为 aten::conv2d;如需导出 Chrome Trace 或 TensorBoard 看板可在安装对应插件后结合 on_trace_ready 使用。

缓解过拟合常用策略

方法描述代码实现
增加数据量扩充训练样本覆盖分布补充标注或数据增强
Dropout训练期随机丢弃神经元防止共适应nn.Dropout(0.25~0.5)
权重衰减对权重施加 L2 惩罚控制复杂度AdamW(weight_decay=2e-2)
早停 (Early Stopping)验证损失停止改善时深拷贝恢复最优权重并 breakEarlyStopping(patience=2)
减少模型复杂度降低隐藏维度或减少堆叠层数调小 hidden_size
数据增强对输入施加语义不变随机变换翻转、裁剪、噪声注入

缓解欠拟合常用策略

方法描述
增加模型复杂度增加网络深度或隐藏单元数提升表达能力
训练更久增加迭代轮数使模型充分拟合
减小正则化调低 Dropout 概率或 weight_decay 系数
调整学习率适当提高过小的学习率并配合调度器

常见学习率调度策略速查

策略描述适用场景
StepLR每隔固定步长按 gamma 等比衰减节奏清晰的分段训练
MultiStepLR在指定里程碑 epoch 触发衰减非均匀阶段降学习率
CosineAnnealingLR按余弦曲线平滑退火至最低学习率固定轮数追求平稳收敛
ReduceLROnPlateau监控验证指标停滞时自动缩减学习率不确定衰减节点时自适应调优
Warmup初期由极小值线性升至目标学习率再衰减大模型与 Transformer 初期稳定

模型训练故障快速诊断表

症状可能原因解决方案
Loss 不下降学习率失当、梯度消失或标签/数据错配核对学习率、单批过拟合测试与梯度范数
Loss 震荡学习率过高或 batch size 过小降低学习率、增大 batch 或加预热
NaN 出现除零、log(0) 或梯度爆炸加 eps 保护、clip_grad_norm_ 与 detect_anomaly
过拟合容量过大或样本不足增广数据、加 Dropout/weight_decay 与早停
欠拟合模型过简或正则过强增容量、降正则、延长训练
显存不足batch 过大或计算图泄漏减小 batch、梯度累积、验证加 inference_mode

运行过拟合诊断、深拷贝早停、零依赖混淆矩阵、梯度裁剪与 CPU Profiler 实验

含完整源码 · 389 行
展开查看收起
python
"""Independent PyTorch 2.10 CPU model evaluation, debugging, metrics, and profiler lab."""
import argparse
import hashlib
import json
import platform
import time
from pathlib import Path

import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.profiler import ProfilerActivity, profile
from torch.utils.data import DataLoader, TensorDataset


def make_three_class_data(seed: int = 2026):
    g = torch.Generator().manual_seed(seed)
    centers = torch.tensor([[2.2, 0.0, -1.5, 0.8, 0.4, -0.6],
                            [-1.8, 2.0, 0.6, -1.2, 0.9, 0.5],
                            [0.0, -2.0, 1.8, 0.5, -1.4, 1.1]])
    xs, ys = [], []
    for cls in range(3):
        pts = centers[cls] + 0.95 * torch.randn((90, 6), generator=g)
        xs.append(pts)
        ys.append(torch.full((90,), cls, dtype=torch.long))
    x = torch.cat(xs, dim=0)
    y = torch.cat(ys, dim=0)
    perm = torch.randperm(len(y), generator=g)
    x, y = x[perm], y[perm]
    return (x[:180], y[:180]), (x[180:], y[180:])


class TabularMLP(nn.Module):
    def __init__(self, hidden: int = 32, dropout: float = 0.0):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(6, hidden),
            nn.ReLU(),
            nn.Dropout(dropout),
            nn.Linear(hidden, hidden),
            nn.ReLU(),
            nn.Dropout(dropout),
            nn.Linear(hidden, 3),
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.net(x)


class EarlyStopping:
    """Patience-based early stopping with deep-cloned state_dict restoration."""

    def __init__(self, patience: int = 3, min_delta: float = 1e-4):
        self.patience = patience
        self.min_delta = min_delta
        self.best_loss = float("inf")
        self.counter = 0
        self.best_state = None
        self.should_stop = False

    def step(self, val_loss: float, model: nn.Module) -> bool:
        if val_loss < self.best_loss - self.min_delta:
            self.best_loss = val_loss
            self.counter = 0
            self.best_state = {k: v.detach().clone() for k, v in model.state_dict().items()}
        else:
            self.counter += 1
            if self.counter >= self.patience:
                self.should_stop = True
        return self.should_stop


def confusion_matrix_np(y_true: np.ndarray, y_pred: np.ndarray, num_classes: int) -> np.ndarray:
    cm = np.zeros((num_classes, num_classes), dtype=np.int64)
    for t, p in zip(y_true, y_pred):
        cm[int(t), int(p)] += 1
    return cm


def classification_metrics(cm: np.ndarray) -> dict:
    total = int(cm.sum())
    acc = float(np.trace(cm) / max(total, 1))
    precisions, recalls, f1s = [], [], []
    for c in range(cm.shape[0]):
        tp = float(cm[c, c])
        fp = float(cm[:, c].sum() - tp)
        fn = float(cm[c, :].sum() - tp)
        p = tp / (tp + fp) if (tp + fp) > 0 else 0.0
        r = tp / (tp + fn) if (tp + fn) > 0 else 0.0
        f1 = 2 * p * r / (p + r) if (p + r) > 0 else 0.0
        precisions.append(round(p, 4))
        recalls.append(round(r, 4))
        f1s.append(round(f1, 4))
    return dict(
        accuracy=round(acc, 4),
        precision_per_class=precisions,
        recall_per_class=recalls,
        f1_per_class=f1s,
        macro_f1=round(float(np.mean(f1s)), 4),
    )


def estimate_macs(model: nn.Module, sample: torch.Tensor) -> int:
    total_macs = 0
    hooks = []

    def conv_hook(mod: nn.Conv2d, _inp, out):
        nonlocal total_macs
        b, c_out, h_out, w_out = out.shape
        k_h, k_w = mod.kernel_size
        total_macs += b * c_out * h_out * w_out * (mod.in_channels // mod.groups) * k_h * k_w

    def linear_hook(mod: nn.Linear, _inp, out):
        nonlocal total_macs
        total_macs += int(out.numel() * mod.in_features)

    for m in model.modules():
        if isinstance(m, nn.Conv2d):
            hooks.append(m.register_forward_hook(conv_hook))
        elif isinstance(m, nn.Linear):
            hooks.append(m.register_forward_hook(linear_hook))
    model.eval()
    with torch.inference_mode():
        model(sample)
    for h in hooks:
        h.remove()
    return int(total_macs)


def sha(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def run_cases(fig_dir: Path | None):
    torch.manual_seed(2026)
    cases = []
    figures = {}

    (x_tr, y_tr), (x_val, y_val) = make_three_class_data()
    tr_loader = DataLoader(TensorDataset(x_tr, y_tr), batch_size=32, shuffle=True, generator=torch.Generator().manual_seed(7))
    criterion = nn.CrossEntropyLoss()

    # 1. Train/val loss curve tracking & overfitting vs regularized comparison
    torch.manual_seed(11)
    reg_model = TabularMLP(hidden=24, dropout=0.25)
    reg_opt = optim.AdamW(reg_model.parameters(), lr=1e-2, weight_decay=2e-2)
    reg_tr_hist, reg_val_hist = [], []
    for _ in range(30):
        reg_model.train()
        ep = 0.0
        for xb, yb in tr_loader:
            reg_opt.zero_grad(set_to_none=True)
            loss = criterion(reg_model(xb), yb)
            loss.backward()
            reg_opt.step()
            ep += float(loss.item()) * len(yb)
        reg_tr_hist.append(round(ep / len(y_tr), 5))
        reg_model.eval()
        with torch.inference_mode():
            reg_val_hist.append(round(float(criterion(reg_model(x_val), y_val).item()), 5))

    # Intentionally overfit a large unregularized MLP on a tiny noisy 24-sample slice
    torch.manual_seed(12)
    g_noise = torch.Generator().manual_seed(99)
    x_tiny = x_tr[:24] + 0.5 * torch.randn((24, 6), generator=g_noise)
    y_tiny = y_tr[:24]
    ov_model = TabularMLP(hidden=128, dropout=0.0)
    ov_opt = optim.Adam(ov_model.parameters(), lr=2e-2)
    ov_tr_hist, ov_val_hist = [], []
    for _ in range(30):
        ov_model.train()
        ov_opt.zero_grad(set_to_none=True)
        loss = criterion(ov_model(x_tiny), y_tiny)
        loss.backward()
        ov_opt.step()
        ov_tr_hist.append(round(float(loss.item()), 5))
        ov_model.eval()
        with torch.inference_mode():
            ov_val_hist.append(round(float(criterion(ov_model(x_val), y_val).item()), 5))

    ov_gap = round(ov_val_hist[-1] - ov_tr_hist[-1], 5)
    reg_gap = round(reg_val_hist[-1] - reg_tr_hist[-1], 5)
    c1_ok = reg_val_hist[-1] < reg_val_hist[0] * 0.35 and ov_gap > 0.15 and ov_val_hist[-1] > reg_val_hist[-1] * 5.0
    cases.append(dict(
        name="train_val_curves_and_overfit_diagnosis",
        inputs=dict(epochs=30, train_samples=180, val_samples=90, overfit_tiny_samples=24),
        prerequisites="固定随机种子比较正则化模型(Dropout+weight_decay)与小样本大网络过拟合曲线",
        action="跟踪训练与验证损失曲线,核验正常收敛与过拟合(训练损失趋近 0 而验证损失高出正则化模型 5 倍以上)的定量判据。",
        expected=dict(reg_val_dropped=True, overfit_gap_gt_015=True, reg_beats_overfit_5x=True),
        actual=dict(reg_val_dropped=reg_val_hist[-1] < reg_val_hist[0] * 0.35, overfit_gap_gt_015=ov_gap > 0.15, reg_beats_overfit_5x=ov_val_hist[-1] > reg_val_hist[-1] * 5.0),
        measurements=dict(reg_val_start=reg_val_hist[0], reg_val_end=reg_val_hist[-1], ov_tr_end=ov_tr_hist[-1], ov_val_end=ov_val_hist[-1], overfit_gap=ov_gap, reg_gap=reg_gap),
        passed=c1_ok,
    ))

    # 2. EarlyStopping: prove shallow state_dict().copy() bug vs deep clone + real break
    torch.manual_seed(21)
    probe = nn.Linear(4, 2)
    shallow_copy = probe.state_dict().copy()
    deep_copy = {k: v.detach().clone() for k, v in probe.state_dict().items()}
    orig_w0 = float(probe.weight[0, 0].item())
    with torch.no_grad():
        probe.weight.add_(5.0)
    shallow_corrupted = abs(float(shallow_copy["weight"][0, 0].item()) - orig_w0) > 4.0
    deep_preserved = abs(float(deep_copy["weight"][0, 0].item()) - orig_w0) < 1e-6

    es = EarlyStopping(patience=2, min_delta=1e-4)
    val_seq = [0.90, 0.60, 0.62, 0.65, 0.70, 0.75]
    stopped_epoch = None
    m_es = nn.Linear(4, 2)
    saved_ref = None
    for ep, v_loss in enumerate(val_seq, start=1):
        with torch.no_grad():
            m_es.weight.fill_(float(ep))
        if ep == 2:
            saved_ref = float(m_es.weight[0, 0].item())
        if es.step(v_loss, m_es):
            stopped_epoch = ep
            break
    m_es.load_state_dict(es.best_state)
    restored_val = float(m_es.weight[0, 0].item())
    c2_ok = shallow_corrupted and deep_preserved and stopped_epoch == 4 and abs(restored_val - saved_ref) < 1e-6
    cases.append(dict(
        name="early_stopping_deepcopy_and_break",
        inputs=dict(val_losses=val_seq, patience=2),
        prerequisites="核对 state_dict().copy() 浅拷贝陷阱与 detach().clone() 深拷贝及真实 break 提前停止",
        action="原位修改权重验证浅拷贝随原张量被污染,并验证 EarlyStopping 在第 4 轮提前跳出并恢复第 2 轮最优权重。",
        expected=dict(shallow_corrupted=True, deep_preserved=True, stopped_epoch=4, restored_best_weight=2.0),
        actual=dict(shallow_corrupted=shallow_corrupted, deep_preserved=deep_preserved, stopped_epoch=stopped_epoch, restored_best_weight=restored_val),
        passed=c2_ok,
    ))

    # 3. Pure-PyTorch/NumPy confusion matrix & precision/recall/F1 metrics (no sklearn dep)
    reg_model.eval()
    with torch.inference_mode():
        preds = reg_model(x_val).argmax(dim=1).numpy()
    y_true = y_val.numpy()
    cm = confusion_matrix_np(y_true, preds, num_classes=3)
    metrics = classification_metrics(cm)
    c3_ok = int(cm.sum()) == len(y_val) and metrics["accuracy"] >= 0.85 and metrics["macro_f1"] >= 0.85
    cases.append(dict(
        name="confusion_matrix_and_classification_metrics",
        inputs=dict(num_classes=3, val_samples=len(y_val)),
        prerequisites="零外部 sklearn/seaborn 依赖,纯 NumPy/PyTorch 计算混淆矩阵与分类指标",
        action="在 90 条留出验证集上统计 3×3 混淆矩阵、准确率、各类精确率/召回率与宏平均 F1。",
        expected=dict(cm_sum=90, acc_ge_85=True, macro_f1_ge_85=True),
        actual=dict(cm_sum=int(cm.sum()), acc_ge_85=metrics["accuracy"] >= 0.85, macro_f1_ge_85=metrics["macro_f1"] >= 0.85),
        measurements=dict(confusion_matrix=cm.tolist(), **metrics),
        passed=c3_ok,
    ))

    # 4. LR schedulers + gradient monitoring & clip_grad_norm_
    p_lr = [nn.Parameter(torch.zeros(2))]
    opt_s = optim.SGD(p_lr, lr=0.1)
    sched_step = optim.lr_scheduler.StepLR(opt_s, step_size=2, gamma=0.5)
    lrs = []
    for _ in range(4):
        lrs.append(round(opt_s.param_groups[0]["lr"], 5))
        opt_s.step()
        sched_step.step()

    opt_p = optim.SGD([nn.Parameter(torch.zeros(2))], lr=0.1)
    sched_plat = optim.lr_scheduler.ReduceLROnPlateau(opt_p, mode="min", factor=0.5, patience=1)
    for vl in (1.0, 1.0, 1.0):
        sched_plat.step(vl)
    plat_lr = round(opt_p.param_groups[0]["lr"], 5)

    # Exploding gradient simulation & clipping
    torch.manual_seed(33)
    deep_lin = nn.Sequential(*[nn.Linear(8, 8, bias=False) for _ in range(5)])
    for m in deep_lin:
        nn.init.constant_(m.weight, 1.2)
    out = deep_lin(torch.ones(2, 8)).sum()
    out.backward()
    raw_norm = float(nn.utils.clip_grad_norm_(deep_lin.parameters(), max_norm=1.0).item())
    clipped_norm = float(torch.sqrt(sum(p.grad.pow(2).sum() for p in deep_lin.parameters())).item())
    c4_ok = lrs == [0.1, 0.1, 0.05, 0.05] and plat_lr == 0.05 and raw_norm > 10.0 and clipped_norm <= 1.0001
    cases.append(dict(
        name="lr_schedulers_and_gradient_clipping",
        inputs=dict(step_size=2, gamma=0.5, max_norm=1.0),
        prerequisites="核对 StepLR、ReduceLROnPlateau 学习率变化及梯度范数监控与裁剪",
        action="验证学习率按预期衰减,且大于 10 的异常梯度范数经 clip_grad_norm_ 压制到 <= 1.0。",
        expected=dict(step_lrs=[0.1, 0.1, 0.05, 0.05], plateau_lr=0.05, raw_gt_10=True, clipped_le_1=True),
        actual=dict(step_lrs=lrs, plateau_lr=plat_lr, raw_gt_10=raw_norm > 10.0, clipped_le_1=clipped_norm <= 1.0001),
        measurements=dict(raw_grad_norm=round(raw_norm, 2), clipped_grad_norm=round(clipped_norm, 5)),
        passed=c4_ok,
    ))

    # 5. Parameters, hook-based MACs/FLOPs, CPU latency, and real PyTorch CPU Profiler
    cnn = nn.Sequential(
        nn.Conv2d(3, 8, kernel_size=3, padding=1),
        nn.ReLU(),
        nn.AdaptiveAvgPool2d((4, 4)),
        nn.Flatten(),
        nn.Linear(8 * 4 * 4, 5),
    )
    total_params = sum(p.numel() for p in cnn.parameters())
    trainable_params = sum(p.numel() for p in cnn.parameters() if p.requires_grad)
    sample_img = torch.randn(1, 3, 16, 16)
    macs = estimate_macs(cnn, sample_img)
    expected_macs = 8 * 16 * 16 * 3 * 3 * 3 + 5 * 128  # 55296 + 640 = 55936

    cnn.eval()
    with torch.inference_mode():
        for _ in range(5):
            cnn(sample_img)
        t0 = time.perf_counter()
        for _ in range(30):
            cnn(sample_img)
        avg_ms = (time.perf_counter() - t0) / 30.0 * 1000.0

    with profile(activities=[ProfilerActivity.CPU], record_shapes=True) as prof:
        with torch.inference_mode():
            cnn(sample_img)
    prof_events = list(prof.key_averages())
    top_op = sorted(prof_events, key=lambda e: e.cpu_time_total, reverse=True)[0].key if prof_events else ""
    c5_ok = total_params == trainable_params == (3 * 8 * 9 + 8 + 128 * 5 + 5) and macs == expected_macs and avg_ms > 0 and len(prof_events) >= 3
    cases.append(dict(
        name="params_macs_latency_and_profiler",
        inputs=dict(input_shape=[1, 3, 16, 16], runs=30),
        prerequisites="纯 PyTorch 前向钩子统计参数量与 MACs/FLOPs,并运行 torch.profiler CPU 分析",
        action="验证参数量 869、精确 MACs 55936、CPU 单次推理耗时 >0 及 Profiler 返回非空算子表。",
        expected=dict(total_params=869, exact_macs=55936, latency_positive=True, profiler_has_ops=True, cuda_available=False),
        actual=dict(total_params=total_params, exact_macs=macs, latency_positive=avg_ms > 0, profiler_has_ops=len(prof_events) >= 3, cuda_available=bool(torch.cuda.is_available())),
        measurements=dict(flops=macs * 2, avg_cpu_ms=round(avg_ms, 4), profiler_event_count=len(prof_events), top_cpu_op=top_op),
        passed=c5_ok,
    ))

    # 6. Plot loss curves and confusion matrix
    mpl_ver = None
    if fig_dir is not None:
        import matplotlib
        matplotlib.use("Agg")
        import matplotlib.pyplot as plt
        fig_dir.mkdir(parents=True, exist_ok=True)
        ep = list(range(1, len(reg_tr_hist) + 1))
        fig, axes = plt.subplots(1, 2, figsize=(9.4, 3.8), dpi=140)
        axes[0].plot(ep, reg_tr_hist, label="Reg Train", color="#174d79", linewidth=1.8)
        axes[0].plot(ep, reg_val_hist, label="Reg Val", color="#2a7f62", linewidth=1.8)
        axes[0].plot(ep, ov_tr_hist, "--", label="Overfit Train", color="#ae511d", linewidth=1.4)
        axes[0].plot(ep, ov_val_hist, "--", label="Overfit Val", color="#b91c1c", linewidth=1.8)
        axes[0].set_title("Regularized vs Overfitting Loss Curves", fontsize=10)
        axes[0].set_xlabel("Epoch")
        axes[0].set_ylabel("CrossEntropyLoss")
        axes[0].grid(True, alpha=0.3)
        axes[0].legend(fontsize=8)

        im = axes[1].imshow(cm, cmap="Blues")
        axes[1].set_title(f"3-Class Confusion Matrix (Acc {metrics['accuracy']*100:.1f}%)", fontsize=10)
        axes[1].set_xlabel("Predicted")
        axes[1].set_ylabel("True")
        axes[1].set_xticks([0, 1, 2])
        axes[1].set_yticks([0, 1, 2])
        for i in range(3):
            for j in range(3):
                axes[1].text(j, i, str(cm[i, j]), ha="center", va="center",
                             color="white" if cm[i, j] > cm.max() * 0.5 else "black", fontsize=11)
        fig.colorbar(im, ax=axes[1], fraction=0.046, pad=0.04)
        fig.tight_layout()
        out_png = fig_dir / "eval-confusion-and-loss.png"
        fig.savefig(out_png)
        plt.close(fig)
        figures["eval-confusion-and-loss.png"] = sha(out_png)
        mpl_ver = matplotlib.__version__

    cases.append(dict(
        name="observed_eval_and_confusion_plot",
        inputs=dict(epochs=len(reg_tr_hist), matrix_shape=[3, 3]),
        prerequisites="留出验证集混淆矩阵与两组训练/验证损失曲线",
        action="输出正则化/过拟合损失曲线对比与 3×3 混淆矩阵图。",
        expected=dict(epochs_plotted=30),
        actual=dict(epochs_plotted=len(reg_tr_hist)),
        measurements=dict(figure_generated="eval-confusion-and-loss.png" in figures),
        passed=len(reg_tr_hist) == 30,
    ))

    payload = dict(version=platform.python_version(), torch=torch.__version__, system=platform.system(), cases=cases)
    if mpl_ver:
        payload["matplotlib"] = mpl_ver
        payload["figures"] = figures
    print(json.dumps(payload, ensure_ascii=False))


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--figures", type=Path, default=None)
    args = parser.parse_args()
    run_cases(args.figures)
核对正则化与过拟合损失差异、浅拷贝污染与深拷贝早停 break 恢复、3×3 混淆矩阵(准确率 98.89%、宏 F1 98.97%)、梯度范数由 303,871.5 裁剪至 1.0、参数 869/MACs 55,936 及 Profiler 22 算子事件,并生成对比图。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 选择对应构建并运行脚本。

下载本章实验包 (mbskycom202612a409.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:PyTorch

课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip

下载课程关联工程包:PyTorch

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a419.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

dict.copy() 只复制字典外层键映射,值仍是原模型参数张量的引用;后续 optimizer.step() 原位更新参数时也会同步改写已保存张量。必须用 {k: v.detach().clone() for k, v in model.state_dict().items()} 或 copy.deepcopy 深拷贝。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习