AI4M
AI for Materials Science 材料人工智能实战课程 · 研究生课程门户

Module 07 · Lecture 07b · 深度视觉与科学大模型

07b · 深度网络训练动力学、正则化与不确定性校准(Deep Training Dynamics & Uncertainty)

07b_deep_training_dynamics_and_uncertainty.ipynb802.7 KB

Open In Colab

07b · 深度网络训练动力学、正则化与不确定性校准(Deep Training Dynamics & Uncertainty)

在 07a 中,我们调用 loss.backward() 和 torch.optim.Adam 轻松跑通了浅层双层网络。但当你尝试把神经网络加深到 8~20 层,或者将其部署到真实的材料主动学习(Active Learning)闭环中时,一连串棘手的工程与数学现象就会浮出水面:

  • 为什么把激活函数换成经典的 Sigmoid,一个 8 层网络的第一层梯度就会瞬间缩水一百万倍,参数纹丝不动?
  • 为什么全零初始化会让整层神经元彻底锁死成双胞胎,而标准正态 \(\mathcal{N}(0, 1)\) 初始化又会让深层激活值炸穿天际?
  • 为什么朴素 SGD 在病态狭长山谷里疯狂“之字形撞墙”,而动量法(Momentum)与 Adam 能顺滑冲向谷底?
  • 普通确定性神经网络只会吐出一个冷冰冰的数字,如何不改一行架构,用蒙特卡洛随机失活(MC Dropout)甄别模型没见过的“分布外(OOD)陌生分子”?

本节完整对标林雪平大学(LiU 2026)第 13 讲 Training and Improving Neural Networks,全部采用纯 PyTorch 与 NumPy 从第一性原理出发逐一实证拆解。

本节大纲

  1. 手推反向传播与链式法则:15 行纯 NumPy 手写双层 MLP 前反向传播,与 PyTorch autograd 精确对拍至 \(<10^{-7}\)
  2. 激活函数演进与梯度消失:8 层深网在 Sigmoid、Tanh、ReLU(含神经元死亡现象)与 GELU/SiLU 下的逐层梯度范数定量对比
  3. 权重初始化与批归一化:朴素小/大方差 vs. Xavier (Glorot) vs. Kaiming (He) 逐层激活分布演化,以及 nn.BatchNorm1d(谨记 train() vs. eval()!)
  4. 优化器动力学与梯度裁剪:病态峡谷曲面上 SGD、SGD + Momentum 与 Adam 的轨迹对决及 clip_grad_norm_
  5. 过拟合、双下降(Double Descent)与不确定性校准:早停、权重衰减、Dropout,过参数化双下降直觉,以及 AqSolDB 与分布外分子的 MC Dropout 不确定性校准

💡 参考答案提示:本节课内随堂练习(07b-1 至 07b-3)的完整代码与解析见 solutions/07_nn_solutions.ipynb。

In [1] · Python
# Colab 环境初始化(本地运行时自动跳过)
import os, sys

if "google.colab" in sys.modules:
    _repo_dir = "/content/ai-for-materials"
    if not os.path.exists(_repo_dir):
        os.system("git clone --depth 1 https://github.com/Zeshengliu213/ai-for-materials.git " + _repo_dir)
    os.chdir(os.path.join(_repo_dir, "course", "07 - Neural Networks and CNNs"))
    get_ipython().run_line_magic("pip", "install -q rdkit")
In [2] · Python
import copy
import os
import warnings
warnings.filterwarnings("ignore")

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, TensorDataset
from rdkit import Chem, RDLogger
from rdkit.Chem import Descriptors
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

%matplotlib inline
RDLogger.DisableLog("rdApp.*")
print("PyTorch version:", torch.__version__)
Out:
PyTorch version: 2.8.0+cpu

📘 课程统一绘图风格:下面这格加载课程自带的 ai4m.mplstyle(配色与课程网站同源,无上右边框,仅横向浅网格,保存默认 300 dpi)。C 是课程配色,手动指定颜色时写 color=C.crimson。

In [3] · Python
# ai4m-style:课程统一绘图风格(本地与 Colab 通用)
import pathlib, sys

sys.path.insert(0, str(pathlib.Path.cwd().parent))   # course/ 根目录
import ai4m_style as ai4m

C = ai4m.use()        # 应用 ai4m.mplstyle,返回课程配色

def set_seed(seed=0):
    torch.manual_seed(seed)
    np.random.seed(seed)
    torch.use_deterministic_algorithms(True)

set_seed(0)

1. 剥开 backward() 黑箱:手推链式法则与 15 行纯 NumPy 对拍

📘 1.1 双层感知机的矩阵微积分推导

考虑一批含 \(N\) 个样本、输入维度 \(D\)、隐藏层宽度 \(H\)、输出维度 \(1\) 的双层回归网络,采用 \(\operatorname{ReLU}\) 激活与均方误差(MSE)损失:

  • 前向传播(Forward Pass):

    \[\mathbf{Z}^{(1)} = \mathbf{X}\mathbf{W}^{(1)} + \mathbf{b}^{(1)}, \qquad \mathbf{A}^{(1)} = \max(0, \mathbf{Z}^{(1)}), \qquad \hat{\mathbf{Y}} = \mathbf{A}^{(1)}\mathbf{W}^{(2)} + \mathbf{b}^{(2)}\]
    \[L = \frac{1}{N} \sum_{i=1}^{N} (\hat{y}_i - y_i)^2\]

  • 反向传播(Backward Pass / Chain Rule):记各层对预激活值的局部误差灵敏度为 \(\boldsymbol{\delta}^{(\ell)} \equiv \frac{\partial L}{\partial \mathbf{Z}^{(\ell)}}\):

    1. 输出层误差信号:\(\boldsymbol{\delta}^{(2)} = \frac{\partial L}{\partial \hat{\mathbf{Y}}} = \frac{2}{N}(\hat{\mathbf{Y}} - \mathbf{Y}) \in \mathbb{R}^{N\times 1}\)
    2. 第二层参数梯度:\(\nabla_{\mathbf{W}^{(2)}} L = (\mathbf{A}^{(1)})^\top \boldsymbol{\delta}^{(2)}\),\(\nabla_{\mathbf{b}^{(2)}} L = \sum_{i=1}^{N} \boldsymbol{\delta}^{(2)}_i\)
    3. 误差反传过线性变换与 ReLU 门控:\(\boldsymbol{\delta}^{(1)} = \left(\boldsymbol{\delta}^{(2)} (\mathbf{W}^{(2)})^\top\right) \odot \mathbb{I}(\mathbf{Z}^{(1)} > 0) \in \mathbb{R}^{N\times H}\)
    4. 第一层参数梯度:\(\nabla_{\mathbf{W}^{(1)}} L = \mathbf{X}^\top \boldsymbol{\delta}^{(1)}\),\(\nabla_{\mathbf{b}^{(1)}} L = \sum_{i=1}^{N} \boldsymbol{\delta}^{(1)}_i\)

▶️ 运行看看:我们用 15 行纯 NumPy 实现上述四条矩阵公式,并与 PyTorch loss.backward() 自动求导算出的四个梯度张量逐元素比对最大绝对误差!

In [4] · Python
# 构造同一份随机输入与初始权重(float32)
rng = np.random.RandomState(42)
N_b, D_in, H_dim = 16, 5, 8
X_np = rng.randn(N_b, D_in).astype(np.float32)
Y_np = rng.randn(N_b, 1).astype(np.float32)
W1_np = (rng.randn(D_in, H_dim) * 0.3).astype(np.float32)
b1_np = np.zeros(H_dim, dtype=np.float32)
W2_np = (rng.randn(H_dim, 1) * 0.3).astype(np.float32)
b2_np = np.zeros(1, dtype=np.float32)

# ================= 15 行纯 NumPy 手写前向 + 反向传播 =================
Z1 = X_np @ W1_np + b1_np                       # (N, H)
A1 = np.maximum(0.0, Z1)                        # ReLU 前向
Y_hat = A1 @ W2_np + b2_np                      # (N, 1)
loss_np = np.mean((Y_hat - Y_np) ** 2)          # MSE Loss

delta2 = (2.0 / N_b) * (Y_hat - Y_np)           # dL / dY_hat: (N, 1)
dW2_np = A1.T @ delta2                          # dL / dW2:    (H, 1)
db2_np = delta2.sum(axis=0)                     # dL / db2:    (1,)
delta1 = (delta2 @ W2_np.T) * (Z1 > 0)          # 链式回传 + ReLU 导数门控: (N, H)
dW1_np = X_np.T @ delta1                        # dL / dW1:    (D, H)
db1_np = delta1.sum(axis=0)                     # dL / db1:    (H,)
# =====================================================================

# 用 PyTorch autograd 对同一组张量自动求导校验
X_pt = torch.tensor(X_np)
Y_pt = torch.tensor(Y_np)
W1_pt = torch.tensor(W1_np, requires_grad=True)
b1_pt = torch.tensor(b1_np, requires_grad=True)
W2_pt = torch.tensor(W2_np, requires_grad=True)
b2_pt = torch.tensor(b2_np, requires_grad=True)

loss_pt = F.mse_loss(F.relu(X_pt @ W1_pt + b1_pt) @ W2_pt + b2_pt, Y_pt)
loss_pt.backward()

diffs = {
    "dW1": np.max(np.abs(dW1_np - W1_pt.grad.numpy())),
    "db1": np.max(np.abs(db1_np - b1_pt.grad.numpy())),
    "dW2": np.max(np.abs(dW2_np - W2_pt.grad.numpy())),
    "db2": np.max(np.abs(db2_np - b2_pt.grad.numpy())),
}
print(f"Forward Loss -> NumPy: {loss_np:.7f} | PyTorch: {loss_pt.item():.7f}")
for name, err in diffs.items():
    print(f"Max |{name}_numpy - {name}_autograd| = {err:.3e}")
assert max(diffs.values()) < 1e-7, "Gradient mismatch!"
print("验证通过:手写矩阵反向传播与 PyTorch Autograd 误差严格小于 1e-7!")
Out:
Forward Loss -> NumPy: 0.9277653 | PyTorch: 0.9277653
Max |dW1_numpy - dW1_autograd| = 5.960e-08
Max |db1_numpy - db1_autograd| = 1.118e-08
Max |dW2_numpy - dW2_autograd| = 5.960e-08
Max |db2_numpy - db2_autograd| = 2.980e-08
验证通过:手写矩阵反向传播与 PyTorch Autograd 误差严格小于 1e-7!

仔细体会第 8 行 delta1 = (delta2 @ W2_np.T) * (Z1 > 0):

  1. 前向传播缓存(Activation Caching):反向传播算 dW2 需要用到前向的 A1,算 delta1 需要用到前向的 Z1——这就是为什么训练深度神经网络比纯推理耗费多倍显存(必须把每一层的中间激活张量留在内存里等反向传播用完才能释放!);
  2. 局部导数连乘:每往回穿过一层,误差信号都要乘一次激活函数导数 \(\sigma'(Z^{(\ell)})\)。如果这个导数恒小于 \(0.25\),连乘 8 次会发生什么?这直接引出了下一节的核心危机。

🏋️ 练习 07b-1:将手写反向传播推广到 LeakyReLU 激活函数

为了避免负半轴梯度彻底归零,LeakyReLU 定义为 \(f(z) = z \ (z > 0)\) 否则 \(\alpha z\)(取 \(\alpha = 0.1\))。请修改上面的纯 NumPy 前向与反向传播(将 (Z1 > 0) 替换为 np.where(Z1 > 0, 1.0, 0.1)),并与 F.leaky_relu(..., negative_slope=0.1) 的 PyTorch autograd 梯度核对误差是否依然 \(< 10^{-7}\)。

In [5] · Python
# 练习 07b-1:在此编写 LeakyReLU (alpha=0.1) 的 NumPy 反向传播并与 PyTorch 对拍

2. 激活函数演进与深层梯度消失(Vanishing Gradients)定量实验

📘 2.1 四代激活函数及其导数曲线剖析

回顾链式法则:第 1 层权重的梯度等于输出误差一路连乘后面 \(L\) 层的权重矩阵与激活导数 \(\prod_{\ell=1}^{L} \sigma'(\mathbf{z}^{(\ell)})\):

  • Sigmoid:\(\sigma(z) = \frac{1}{1+e^{-z}}\),其导数 \(\sigma'(z) = \sigma(z)(1-\sigma(z))\) 最大值在 \(z=0\) 处仅为 \(0.25\)!穿过 8 层后,仅激活导数一项就衰减了 \(0.25^8 \approx 1.5 \times 10^{-5}\),两端饱和区更是趋于 \(0\);
  • Tanh:输出零中心化(\([-1, 1]\)),\(z=0\) 处导数为 \(1\),但在 \(|z| > 2\) 饱和区导数依然迅速归零;
  • ReLU:正半轴导数恒为 \(1\),彻底打通深层梯度高速公路;但如果学习率过大或偏置过负导致某个神经元对所有样本都有 \(z < 0\),其梯度永远为 \(0\),再也无法复活——即神经元死亡(Dying ReLU);
  • GELU / SiLU(Swish):如 \(\operatorname{SiLU}(z) = z \cdot \sigma(z)\),处处无穷阶光滑可微(二阶导连续!这对需要求能量对原子坐标负梯度 \(-\nabla_{\mathbf{R}} E\) 算受力的机器学习原子间势能 MLIP 如 SchNet / MACE 至关重要!),且在零点左侧保留微小负梯度,兼顾抗梯度消失与平滑性。

▶️ 运行看看:左图对比四类激活函数及其一阶导数,右图定量测量一个 8 层深层网络在单步反向传播中第 1 层到第 8 层的权重梯度范数 \(\|\nabla \mathbf{W}^{(\ell)}\|_F\)(对数坐标)!

In [6] · Python
z_grid = torch.linspace(-4.5, 4.5, 400, requires_grad=True)
act_dict = {
    "Sigmoid": nn.Sigmoid(),
    "Tanh": nn.Tanh(),
    "ReLU": nn.ReLU(),
    "SiLU / GELU": nn.GELU(),
}
colors_act = [C.crimson, C.gold, C.teal, C.navy]

fig, axes = plt.subplots(1, 3, figsize=(13.6, 3.8))

# (a) 激活函数曲线 & (b) 一阶导数曲线
for (name, fn), col in zip(act_dict.items(), colors_act):
    z_tmp = z_grid.detach().clone().requires_grad_(True)
    y_tmp = fn(z_tmp)
    y_tmp.sum().backward()
    axes[0].plot(z_tmp.detach().numpy(), y_tmp.detach().numpy(), lw=2.0, color=col, label=name)
    axes[1].plot(z_tmp.detach().numpy(), z_tmp.grad.numpy(), lw=2.0, color=col, label=name)

axes[0].axhline(0, color="gray", lw=0.6); axes[0].axvline(0, color="gray", lw=0.6)
axes[0].set_xlabel("Pre-activation $z$"); axes[0].set_ylabel("Activation $\\sigma(z)$")
axes[0].set_title("a) Activation Functions"); axes[0].legend(fontsize=8.3)

axes[1].axhline(0.25, color=C.crimson, ls=":", lw=1.1, label="Sigmoid max slope = 0.25")
axes[1].set_xlabel("Pre-activation $z$"); axes[1].set_ylabel("Derivative $\\sigma'(z)$")
axes[1].set_title("b) First Derivatives $\\sigma'(z)$"); axes[1].legend(fontsize=8.0)

# (c) 8 层隐藏层深度网络的逐层梯度范数定量对比(统一使用 Xavier 初始化公平比较激活函数本身)
set_seed(12)
x_deep = torch.randn(128, 32)
y_deep = torch.randn(128, 1)

for name, act_cls, col, mk in [
    ("Sigmoid", nn.Sigmoid, C.crimson, "o"),
    ("Tanh", nn.Tanh, C.gold, "s"),
    ("ReLU", nn.ReLU, C.teal, "^"),
    ("SiLU", nn.SiLU, C.navy, "D"),
]:
    set_seed(12)
    linear_layers = []
    mods = []
    in_c = 32
    for _ in range(8):
        lin = nn.Linear(in_c, 64)
        nn.init.xavier_normal_(lin.weight)
        nn.init.zeros_(lin.bias)
        linear_layers.append(lin)
        mods.extend([lin, act_cls()])
        in_c = 64
    head = nn.Linear(64, 1)
    nn.init.xavier_normal_(head.weight)
    mods.append(head)
    deep_net = nn.Sequential(*mods)

    loss_d = F.mse_loss(deep_net(x_deep), y_deep)
    loss_d.backward()
    grad_norms = [lin.weight.grad.norm().item() for lin in linear_layers]
    axes[2].plot(range(1, 9), grad_norms, marker=mk, lw=2.0, color=col, label=name)
    print(f"{name:7s} -> Layer 8 grad norm: {grad_norms[-1]:.3e} | Layer 1 grad norm: {grad_norms[0]:.3e} (Ratio L1/L8 = {grad_norms[0]/grad_norms[-1]:.2e})")

axes[2].set_yscale("log")
axes[2].set_xticks(range(1, 9))
axes[2].set_xlabel("Hidden Layer Index $\\ell$ (1 = Earliest, 8 = Deepest)")
axes[2].set_ylabel("Gradient Norm $\\|\\nabla W^{(\\ell)}\\|_F$ (log scale)")
axes[2].set_title("c) 8-Layer Gradient Flow: Sigmoid Vanishes by $10^5\\times$!")
axes[2].legend(fontsize=8.3)
plt.tight_layout()
plt.show()

# 补充演示:Dying ReLU(当初始偏置偏负 b = -3.0 时,多少比例的 ReLU 神经元彻底死亡?)
dead_lin = nn.Linear(32, 128)
nn.init.constant_(dead_lin.bias, -3.0)
act_relu = F.relu(dead_lin(x_deep))
dead_frac = float((act_relu.max(dim=0).values == 0).float().mean().item()) * 100
print(f"\n[Dying ReLU 警示] 当偏置异常偏移至 -3.0 时,128 个 ReLU 神经元中有 {dead_frac:.1f}% 在全批次上恒输出 0(永久脑死亡)!")
Out:
Sigmoid -> Layer 8 grad norm: 1.310e+00 | Layer 1 grad norm: 1.345e-05 (Ratio L1/L8 = 1.03e-05)
Tanh    -> Layer 8 grad norm: 8.996e-01 | Layer 1 grad norm: 7.676e-01 (Ratio L1/L8 = 8.53e-01)
ReLU    -> Layer 8 grad norm: 2.182e-01 | Layer 1 grad norm: 8.856e-02 (Ratio L1/L8 = 4.06e-01)
SiLU    -> Layer 8 grad norm: 1.964e-02 | Layer 1 grad norm: 9.091e-03 (Ratio L1/L8 = 4.63e-01)
Notebook 输出图像
[Dying ReLU 警示] 当偏置异常偏移至 -3.0 时,128 个 ReLU 神经元中有 100.0% 在全批次上恒输出 0(永久脑死亡)!

实验数字触目惊心:在仅仅 8 层深度的网络里,Sigmoid 第 1 层接收到的梯度比第 8 层缩小了超过 \(10^5\) 倍!靠近输入的底层特征提取器几乎处于完全冻结状态。相比之下,ReLU 与 SiLU 让首尾各层的梯度始终保持在同一数量级内。


3. 权重初始化(Xavier vs. Kaiming He)与批归一化(BatchNorm1d)

📘 3.1 为什么方差差几倍,深层网络的信号就会坍缩成 0 或爆炸饱和?

即使选对了激活函数,如果初始权重 \(\mathbf{W}^{(\ell)} \sim \mathcal{N}(0, \sigma_w^2)\) 的标准差 \(\sigma_w\) 设得不对,前向激活值的方差也会逐层呈指数级坍缩或膨胀!设输入各分量独立且方差为 \(1\),经过宽度为 \(n_{\text{in}}\) 的线性层 \(z = \sum_{i=1}^{n_{\text{in}}} w_i x_i\) 后,输出方差为:

\[\operatorname{Var}(z) = n_{\text{in}} \cdot \sigma_w^2 \cdot \operatorname{Var}(x)\]

为了令信号穿过数十层后方差依然保持在 \(\mathcal{O}(1)\) 黄金区间:

  • Xavier / Glorot 初始化(2010,适配 Tanh / Sigmoid 近似线性区):兼顾前向输入维度 \(n_{\text{in}}\) 与反向输出维度 \(n_{\text{out}}\),令 \(\sigma_w = \sqrt{\frac{2}{n_{\text{in}} + n_{\text{out}}}}\);
  • Kaiming / He 初始化(2015,专为 ReLU / SiLU 设计):因为 ReLU 直接砍掉了负半轴一半的方差(\(\operatorname{Var}(\operatorname{ReLU}(z)) = \frac{1}{2}\operatorname{Var}(z)\)),必须把权重方差翻倍补偿,令 \(\sigma_w = \sqrt{\frac{2}{n_{\text{in}}}}\)!

▶️ 运行看看:我们在一个 8 层、每层宽 256 的 ReLU 网络上对比四种初始化方案——过小(\(\sigma=0.02\))、过大(\(\sigma=0.5\))、Xavier 与 Kaiming He,直接观察第 1~8 层输出激活标准差的剧烈分野:

In [7] · Python
def probe_activation_stats(init_mode, width=256, depth=8):
    set_seed(0)
    x_probe = torch.randn(512, width)
    stds_per_layer = []
    h = x_probe
    for _ in range(depth):
        lin = nn.Linear(width, width, bias=False)
        if init_mode == "Too Small (std=0.02)":
            nn.init.normal_(lin.weight, mean=0.0, std=0.02)
        elif init_mode == "Too Large (std=0.50)":
            nn.init.normal_(lin.weight, mean=0.0, std=0.50)
        elif init_mode == "Xavier (1/sqrt(n))":
            nn.init.xavier_normal_(lin.weight)
        elif init_mode == "Kaiming He (sqrt(2/n))":
            nn.init.kaiming_normal_(lin.weight, nonlinearity="relu")
        h = F.relu(lin(h))
        stds_per_layer.append(h.std().item())
    return stds_per_layer

modes_init = [
    ("Too Small (std=0.02)", C.slate, "o--"),
    ("Too Large (std=0.50)", C.crimson, "v--"),
    ("Xavier (1/sqrt(n))", C.gold, "s-"),
    ("Kaiming He (sqrt(2/n))", C.teal, "D-"),
]

fig, ax = plt.subplots(figsize=(6.8, 3.8))
for label, col, style in modes_init:
    stds = probe_activation_stats(label)
    ax.plot(range(1, 9), stds, style, color=col, lw=2.0, label=f"{label} -> L8 std={stds[-1]:.2e}")

ax.axhline(1.0, color="k", ls=":", lw=1.0)
ax.set_yscale("log")
ax.set_xticks(range(1, 9))
ax.set_xlabel("Hidden Layer Index $\\ell$ (Width = 256, ReLU)")
ax.set_ylabel("Activation Std Dev $\\mathrm{std}(a^{(\\ell)})$ (log scale)")
ax.set_title("Layer-by-Layer Activation Scale Across Weight Initializations")
ax.legend(fontsize=8.3, loc="center left")
plt.tight_layout()
plt.show()
Out:
Notebook 输出图像

看得多清楚:

  • std=0.02 到第 8 层激活标准差坍缩到了 \(10^{-6}\);std=0.50 则一路狂飙超过 \(10^{5}\)!
  • 连 Xavier 在 ReLU 网络中每层也会损失 \(\sqrt{1/2} \approx 0.707\) 倍标准差(8 层后衰减至 \(\approx 0.06\));唯有 **Kaiming He(\(\sqrt{2/n_{\text{in}}}\))**让第 1 层到第 8 层的激活幅度稳如磐石地停留在 \(\sim 0.8\) 附近!

📘 3.2 批归一化(nn.BatchNorm1d)与 model.train() vs. model.eval() 铁律

在训练过程中,随着前面各层权重不断更新,后面层看到的输入分布仍在持续漂移。**批归一化(Batch Normalization, Ioffe & Szegedy 2015)**干脆在每一层线性变换后强行把当前小批量激活拉回零均值、单位方差,再乘上可学习的缩放 \(\gamma\) 与平移 \(\beta\):

\[\hat{\mathbf{z}} = \frac{\mathbf{z} - \boldsymbol{\mu}_{\mathcal{B}}}{\sqrt{\boldsymbol{\sigma}^2_{\mathcal{B}} + \epsilon}}, \qquad \mathbf{y} = \gamma \odot \hat{\mathbf{z}} + \beta\]

⚠️ 工程大忌:推理单条分子时忘记切回 model.eval()!

  • 在 model.train() 模式下,BatchNorm1d 使用当前 Mini-batch 的均值 \(\boldsymbol{\mu}_{\mathcal{B}}\) 和方差 \(\boldsymbol{\sigma}^2_{\mathcal{B}}\),同时用指数移动平均(EMA)后台更新全局统计量 running_mean 与 running_var;
  • 在 model.eval() 模式下,BatchNorm1d 冻结并改用存好的全局 running_mean 与 running_var——这保证了单样本推理(Batch Size = 1)不会因方差为 0 而报错或输出乱码,且推理结果与测试集怎么凑 Batch 完全无关!

▶️ 运行看看:读取 AqSolDB 数据集,在一个故意采用糟糕小初始化(std=0.03)的 6 层深网中对比“无 BatchNorm”与“加 nn.BatchNorm1d”的收敛曲线,并现场验证 train() vs eval() 的推理行为差异:

In [8] · Python
# 加载与 07a 完全一致的 AqSolDB 80/10/10 划分
DATA_FILE = "data/solubility.csv" if os.path.exists("data/solubility.csv") else "solubility.csv"
df = pd.read_csv(DATA_FILE)
df = df[df["SMILES"].apply(Chem.MolFromSmiles).notna()].reset_index(drop=True)
feature_cols = [
    "MolWt", "MolLogP", "MolMR", "HeavyAtomCount", "NumHAcceptors", "NumHDonors",
    "NumHeteroatoms", "NumRotatableBonds", "NumValenceElectrons", "NumAromaticRings",
    "NumSaturatedRings", "NumAliphaticRings", "RingCount", "TPSA", "LabuteASA",
    "BalabanJ", "BertzCT",
]
X_all = df[feature_cols].values
y_all = df["Solubility"].values

X_trval, X_test, y_trval, y_test = train_test_split(X_all, y_all, test_size=0.2, random_state=42)
X_train, X_valid, y_train, y_valid = train_test_split(X_trval, y_trval, test_size=0.1, random_state=42)
scaler = StandardScaler().fit(X_train)
to_t = lambda a: torch.tensor(a, dtype=torch.float32)
Xtr, Xva, Xte = (to_t(scaler.transform(a)) for a in (X_train, X_valid, X_test))
ytr, yva, yte = (to_t(a) for a in (y_train, y_valid, y_test))
train_loader = DataLoader(TensorDataset(Xtr, ytr), batch_size=128, shuffle=True)

class Deep6LayerNet(nn.Module):
    def __init__(self, use_bn=False):
        super().__init__()
        blocks = []
        in_d = 17
        for _ in range(6):
            lin = nn.Linear(in_d, 64)
            # 故意使用偏小的初始化 std=0.03 模拟未调优深层网络
            nn.init.normal_(lin.weight, 0.0, 0.03)
            nn.init.zeros_(lin.bias)
            blocks.append(lin)
            if use_bn:
                blocks.append(nn.BatchNorm1d(64))
            blocks.append(nn.ReLU())
            in_d = 64
        blocks.append(nn.Linear(64, 1))
        self.net = nn.Sequential(*blocks)

    def forward(self, x):
        return self.net(x).squeeze(-1)

def quick_train(model, epochs=25, lr=2e-3):
    opt = torch.optim.Adam(model.parameters(), lr=lr)
    va_curve = []
    for _ in range(epochs):
        model.train()
        for xb, yb in train_loader:
            loss = F.mse_loss(model(xb), yb)
            opt.zero_grad(); loss.backward(); opt.step()
        model.eval()
        with torch.no_grad():
            va_curve.append(torch.sqrt(F.mse_loss(model(Xva), yva)).item())
    return va_curve

set_seed(0); curve_no_bn = quick_train(Deep6LayerNet(use_bn=False))
set_seed(0); net_bn = Deep6LayerNet(use_bn=True); curve_bn = quick_train(net_bn)

fig, ax = plt.subplots(figsize=(6.2, 3.5))
ax.plot(curve_no_bn, "--", color=C.crimson, lw=2.0, label=f"6-Layer Plain (Poor Init) -> Val RMSE={curve_no_bn[-1]:.2f}")
ax.plot(curve_bn, "-", color=C.navy, lw=2.2, label=f"6-Layer + BatchNorm1d -> Val RMSE={curve_bn[-1]:.2f}")
ax.set_xlabel("Epoch"); ax.set_ylabel("Validation RMSE (logS)")
ax.set_title("BatchNorm1d Rescues Deep Network with Suboptimal Initialization")
ax.legend()
plt.tight_layout()
plt.show()

# 演示 eval() 的重要性:同一分子单独输入 vs 混在批次中输入
net_bn.eval()
with torch.no_grad():
    p_single = net_bn(Xte[:1]).item()
    p_in_batch = net_bn(Xte[:32])[0].item()
print(f"model.eval() 下单分子预测 = {p_single:.6f} vs 混入 32 分子批次中预测 = {p_in_batch:.6f} (完全一致!)")
Out:
Notebook 输出图像
model.eval() 下单分子预测 = -2.136090 vs 混入 32 分子批次中预测 = -2.136090 (完全一致!)

🏋️ 练习 07b-2:用 Kaiming He 初始化拯救无 BatchNorm 的 6 层深网

如果不加 BatchNorm1d,仅靠把 Deep6LayerNet(use_bn=False) 中每一层线性权重改为 nn.init.kaiming_normal_(m.weight, nonlinearity="relu"),能否同样救活这个 6 层网络?请编写代码训练 25 轮并对比最终验证集 RMSE!

In [9] · Python
# 练习 07b-2:在此用 kaiming_normal_ 初始化无 BatchNorm 的 6 层网络并训练 25 轮验证

4. 优化器动力学与梯度裁剪(SGD vs. Momentum vs. Adam + clip_grad_norm_)

📘 4.1 病态曲率峡谷(Ill-Conditioned Ravine)上的三类优化器轨迹

在高维参数空间中,损失曲面往往像一条狭长的峡谷:横向山壁极陡(曲率大,梯度大),而顺着谷底通往全局极小值的纵向坡度极缓(曲率小,梯度微弱)。以二维病态二次函数 \(L(w_1, w_2) = 0.5 w_1^2 + 12 w_2^2\) 为例:

  • 朴素 SGD:学习率稍大就在陡峭的 \(w_2\) 方向来回剧烈震荡,学习率调小又在平缓的 \(w_1\) 方向寸步难行;
  • SGD + Momentum(动量法,\(\mathbf{v}_t = \beta \mathbf{v}_{t-1} + \nabla L\)):像有惯性的重球滚下山坡——来回反向震荡的垂直分量正负抵消,而始终朝向谷底的纵向分量不断加速!
  • Adam(自适应矩估计):同时维护梯度的一阶动量 \(m_t\) 与二阶平方均值 \(v_t\),用 \(\frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon}\) 为每个参数坐标自动定制专属步长——陡峭方向除以大 \(\sqrt{v_t}\) 自动降速,平缓方向除以小 \(\sqrt{v_t}\) 自动提速!

此外,在深层网络或序列模型(第 08 讲 RNN/Transformer)遇到悬崖式尖锐损失壁垒时,单步异常大梯度会把权重一脚踹飞。梯度范数裁剪 nn.utils.clip_grad_norm_(params, max_norm) 在 \(\|\mathbf{g}\|_2 > \tau\) 时按比例缩放 \(\mathbf{g} \leftarrow \tau \frac{\mathbf{g}}{\|\mathbf{g}\|_2}\):既保留了正确的下降方向,又锁死了单步最大破坏半径!

In [10] · Python
def trace_optimizer_2d(opt_builder, n_steps=45):
    w = torch.tensor([-7.5, 2.2], requires_grad=True)
    opt = opt_builder([w])
    traj = [w.detach().numpy().copy()]
    for _ in range(n_steps):
        loss = 0.5 * w[0] ** 2 + 12.0 * w[1] ** 2
        opt.zero_grad()
        loss.backward()
        opt.step()
        traj.append(w.detach().numpy().copy())
    return np.array(traj)

traj_sgd = trace_optimizer_2d(lambda p: torch.optim.SGD(p, lr=0.075))
traj_mom = trace_optimizer_2d(lambda p: torch.optim.SGD(p, lr=0.055, momentum=0.85))
traj_adam = trace_optimizer_2d(lambda p: torch.optim.Adam(p, lr=0.35))

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.8, 4.1))

# 左图:等高线峡谷上的优化轨迹
w1_g, w2_g = np.meshgrid(np.linspace(-8.2, 1.5, 200), np.linspace(-2.8, 2.8, 200))
Z_loss = 0.5 * w1_g ** 2 + 12.0 * w2_g ** 2
ax1.contour(w1_g, w2_g, Z_loss, levels=np.geomspace(0.3, 80, 14), cmap="Blues", alpha=0.65)
ax1.plot(traj_sgd[:, 0], traj_sgd[:, 1], "o-", ms=3.5, lw=1.4, color=C.crimson, label="Vanilla SGD (Zig-Zag)")
ax1.plot(traj_mom[:, 0], traj_mom[:, 1], "s-", ms=3.5, lw=1.6, color=C.gold, label="SGD + Momentum (0.85)")
ax1.plot(traj_adam[:, 0], traj_adam[:, 1], "D-", ms=3.8, lw=2.0, color=C.teal, label="Adam (Adaptive Step)")
ax1.scatter([0], [0], s=130, marker="*", color="k", zorder=6, label="Minimum (0, 0)")
ax1.set_xlabel("Gentle Valley Coordinate $w_1$"); ax1.set_ylabel("Steep Wall Coordinate $w_2$")
ax1.set_title("a) Trajectories on Ill-Conditioned Ravine $0.5w_1^2 + 12w_2^2$")
ax1.legend(loc="lower right", fontsize=8.2)

# 右图:陡峭四次悬崖 V(x) = 0.5 x^2 + 0.08 x^4 上梯度裁剪防止单步发散
for clip_val, col, ls, lbl in [(None, C.crimson, "--", "No Clipping (Overshoots Cliff!)"),
                               (2.0, C.navy, "-", "With clip_grad_norm_(max_norm=2.0)")]:
    x_c = torch.tensor([4.5], requires_grad=True)
    opt_c = torch.optim.SGD([x_c], lr=0.18)
    losses_c = []
    for _ in range(25):
        l_c = 0.5 * x_c ** 2 + 0.08 * x_c ** 4
        losses_c.append(l_c.item())
        opt_c.zero_grad(); l_c.backward()
        if clip_val is not None:
            nn.utils.clip_grad_norm_([x_c], max_norm=clip_val)
        opt_c.step()
    ax2.plot(losses_c, ls=ls, color=col, lw=2.1, label=lbl)

ax2.set_yscale("log")
ax2.set_xlabel("Step"); ax2.set_ylabel("Cliff Objective Loss (log scale)")
ax2.set_title("b) Gradient Clipping Tames Steep Loss Cliffs")
ax2.legend(fontsize=8.5)
plt.tight_layout()
plt.show()
Out:
Notebook 输出图像

5. 正则化、双下降(Double Descent)直觉与 MC Dropout 不确定性校准

📘 5.1 大容量 MLP 过拟合诊断与正则化三剑客(早停 + 权重衰减 + Dropout)

如果把 SolubilityMLP 的隐藏层宽度从 64×64(5,377 参数)盲目扩充 50 倍到 512×512(272,385 参数,远超 6,825 个训练分子!),不加正则化训练 100 轮会发生典型的死记硬背过拟合。我们对比:

  1. 无正则化大容量网络(512×512);
  2. 早停(Early Stopping):回滚到验证集 RMSE 最低轮次的参数快照;
  3. Dropout (\(p=0.25\)) + 权重衰减(Weight Decay \(10^{-4}\)):训练时随机屏蔽神经元抑制协同记忆,并惩罚过大权重范数。
In [11] · Python
class RegMLP(nn.Module):
    def __init__(self, hidden=512, dropout=0.0):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(17, hidden), nn.ReLU(), nn.Dropout(dropout),
            nn.Linear(hidden, hidden), nn.ReLU(), nn.Dropout(dropout),
            nn.Linear(hidden, 1),
        )

    def forward(self, x):
        return self.net(x).squeeze(-1)

def train_reg_exp(model, epochs=100, lr=1e-3, wd=0.0):
    opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=wd)
    hist = {"train": [], "valid": []}
    best_va, best_st = float("inf"), None
    for _ in range(epochs):
        model.train()
        for xb, yb in train_loader:
            loss = F.mse_loss(model(xb), yb)
            opt.zero_grad(); loss.backward(); opt.step()
        model.eval()
        with torch.no_grad():
            tr_r = torch.sqrt(F.mse_loss(model(Xtr), ytr)).item()
            va_r = torch.sqrt(F.mse_loss(model(Xva), yva)).item()
        hist["train"].append(tr_r); hist["valid"].append(va_r)
        if va_r < best_va:
            best_va = va_r
            best_st = copy.deepcopy(model.state_dict())
    return hist, best_st

set_seed(0)
big_plain = RegMLP(hidden=512, dropout=0.0)
h_plain, st_plain = train_reg_exp(big_plain, epochs=100, wd=0.0)

set_seed(0)
big_reg = RegMLP(hidden=512, dropout=0.25)
h_reg, st_reg = train_reg_exp(big_reg, epochs=100, wd=1e-3)

@torch.no_grad()
def test_rmse_fn(m):
    m.eval()
    return torch.sqrt(F.mse_loss(m(Xte), yte)).item()

rmse_plain_last = test_rmse_fn(big_plain)
big_plain.load_state_dict(st_plain)
rmse_plain_es = test_rmse_fn(big_plain)
big_reg.load_state_dict(st_reg)
rmse_reg_es = test_rmse_fn(big_reg)

print(f"512x512 无正则化 (第100轮末尾) 测试 RMSE = {rmse_plain_last:.3f} (训练 RMSE 已背到 {h_plain['train'][-1]:.2f}!)")
print(f"512x512 仅靠早停 (Early Stop)   测试 RMSE = {rmse_plain_es:.3f}")
print(f"512x512 Dropout+WD+早停         测试 RMSE = {rmse_reg_es:.3f}")

fig, ax = plt.subplots(figsize=(6.8, 3.7))
ax.plot(h_plain["train"], ":", color=C.crimson, lw=1.6, label="512x512 No Reg (Train)")
ax.plot(h_plain["valid"], "--", color=C.crimson, lw=2.0, label="512x512 No Reg (Valid Overfits!)")
ax.plot(h_reg["train"], ":", color=C.teal, lw=1.6, label="512x512 Dropout+WD (Train)")
ax.plot(h_reg["valid"], "-", color=C.teal, lw=2.2, label="512x512 Dropout+WD (Valid Stable)")
ax.set_xlabel("Epoch"); ax.set_ylabel("RMSE (logS)")
ax.set_title("Overfitting Diagnosis & Regularization on AqSolDB (272k Params)")
ax.legend(fontsize=8.3, ncol=2)
plt.tight_layout()
plt.show()
Out:
512x512 无正则化 (第100轮末尾) 测试 RMSE = 1.178 (训练 RMSE 已背到 0.78!)
512x512 仅靠早停 (Early Stop)   测试 RMSE = 1.156
512x512 Dropout+WD+早停         测试 RMSE = 1.136
Notebook 输出图像

📘 5.2 现代深度学习直觉:为什么巨型过参数化模型不一定会崩溃?(Double Descent)

经典统计学习的偏差–方差权衡(第 02b 讲 U 型曲线)预言:模型参数量 \(P\) 一旦超过训练样本数 \(N\),测试误差就会无限恶化。然而现代深度学习发现了著名的双下降现象(Double Descent, Belkin et al. 2019 & LiU L13):

  1. 欠参数化区(\(P < N\)):容量增大,偏差下降,呈现经典 U 型前半段;
  2. 插值阈值尖峰(Interpolation Threshold, \(P \approx N\)):模型刚好有唯一一种极其扭曲剧烈的方式强行穿过每一个含噪训练点,测试误差达到最坏尖峰!
  3. 过参数化平滑区(\(P \gg N\)):能零误差插值训练集的解无穷多,而基于小初始权重的梯度下降隐式偏向寻找最小范数、最光滑的插值函数(Implicit Minimum-Norm Bias),测试误差竟然迎来了第二次下降!

▶️ 运行看看:用随机傅里叶/ReLU 特征在 \(N=28\) 个含噪一维点上扫描隐藏宽度 \(M \in [2, 180]\),亲眼见证在 \(M = N = 28\) 处耸立的插值共振尖峰与随后的二次下降:

In [12] · Python
# 快速演示 Double Descent:固定随机隐藏层 ReLU 特征(Random Kitchen Sinks / Extreme Learning),
# 精确求解最小范数插值解 w = Phi^+ y,观察容量穿过 M = N = 28 时的测试误差双下降!
rng_dd = np.random.RandomState(7)
N_dd = 28
x_tr_dd = np.sort(rng_dd.uniform(-1.0, 1.0, size=(N_dd, 1)))
y_tr_dd = np.sin(np.pi * x_tr_dd).ravel() + rng_dd.normal(0, 0.18, size=N_dd)
x_te_dd = np.linspace(-1.0, 1.0, 400)[:, None]
y_te_dd = np.sin(np.pi * x_te_dd).ravel()

widths_dd = [2, 4, 8, 12, 18, 22, 25, 27, 28, 29, 31, 36, 48, 75, 120, 180]
tr_errs_dd, te_errs_dd = [], []

for M_w in widths_dd:
    errs_te_runs, errs_tr_runs = [], []
    for s_r in range(12):
        r_local = np.random.RandomState(100 + s_r)
        W_rf = r_local.randn(1, M_w) * 2.2
        b_rf = r_local.uniform(-2.2, 2.2, size=(1, M_w))
        Phi_tr = np.maximum(0.0, x_tr_dd @ W_rf + b_rf)
        Phi_te = np.maximum(0.0, x_te_dd @ W_rf + b_rf)
        w_min_norm = np.linalg.pinv(Phi_tr, rcond=1e-6) @ y_tr_dd
        errs_tr_runs.append(np.sqrt(np.mean((Phi_tr @ w_min_norm - y_tr_dd) ** 2)))
        errs_te_runs.append(np.sqrt(np.mean((Phi_te @ w_min_norm - y_te_dd) ** 2)))
    tr_errs_dd.append(np.mean(errs_tr_runs))
    te_errs_dd.append(np.mean(errs_te_runs))

fig, ax = plt.subplots(figsize=(6.8, 3.6))
ax.plot(widths_dd, tr_errs_dd, "o--", color=C.navy, lw=1.7, label="Train RMSE (Hits 0 at $M \\geq N$)")
ax.plot(widths_dd, te_errs_dd, "s-", color=C.crimson, lw=2.1, label="Test RMSE (Double Descent!)")
ax.axvline(N_dd, color=C.gold, ls=":", lw=1.8, label=f"Interpolation Threshold ($M = N = {N_dd}$)")
ax.set_yscale("log")
ax.set_xscale("log")
ax.set_xlabel("Model Capacity: Number of Random ReLU Units $M$ (log scale)")
ax.set_ylabel("RMSE (log scale)")
ax.set_title("Double Descent Curve Across the Interpolation Threshold")
ax.legend(fontsize=8.3)
plt.tight_layout()
plt.show()
Out:
Notebook 输出图像

📘 5.3 Monte Carlo Dropout(MC Dropout):认知不确定性校准与分布外(OOD)预警

在第 04 讲贝叶斯优化中,高斯过程回归天然给出标准差 \(\sigma(\mathbf{x})\)。而在深度神经网络中,Gal & Ghahramani(ICML 2016)证明:推理时故意保持 model.train() 让 Dropout 持续激活,对同一个输入分子重复前向采样 \(T=50\) 次:

\[\hat{\mu}(\mathbf{x}) = \frac{1}{T}\sum_{t=1}^{T} f_{\hat{\mathbf{w}}_t}(\mathbf{x}), \qquad \hat{\sigma}(\mathbf{x}) = \sqrt{\frac{1}{T}\sum_{t=1}^{T}\left(f_{\hat{\mathbf{w}}_t}(\mathbf{x}) - \hat{\mu}(\mathbf{x})\right)^2}\]

这组随机子网络的分歧度 \(\hat{\sigma}(\mathbf{x})\) 直接刻画了模型的认知不确定性(Epistemic Uncertainty)!下面我们用刚训好的 big_reg 同时检验两件事:

  1. 分布内校准(In-Domain Calibration):把 AqSolDB 测试集 1,896 个分子按 mc_std 从小到大分成五档(Quintiles),看模型越“拿不准”的分子,真实预测误差是否确实越大;
  2. 分布外化学空间预警(Out-of-Domain / OOD Detection):对比常见小分子(乙醇、苯甲酸)与极端分布外怪异分子(全氟辛烷 C8F18、十溴二苯醚阻燃剂、超大稠环),观察 mc_std 是否自动亮起高危红灯!
In [13] · Python
def mc_dropout_predict(model, X_tensor, n_samples=50):
    # 注意:如果模型中同时含 BatchNorm,应只把 nn.Dropout 设为 train() 而保持 BatchNorm 为 eval()!
    model.eval()
    for m in model.modules():
        if isinstance(m, nn.Dropout):
            m.train()
    preds = []
    with torch.no_grad():
        for _ in range(n_samples):
            preds.append(model(X_tensor).unsqueeze(0))
    preds = torch.cat(preds, dim=0)  # (T, N)
    return preds.mean(dim=0).numpy(), preds.std(dim=0).numpy()

set_seed(0)
mc_mean, mc_std = mc_dropout_predict(big_reg, Xte, n_samples=60)
sq_err = (mc_mean - yte.numpy()) ** 2

# 1. 按不确定性分 5 档统计每档的平均 mc_std 与真实测试集 RMSE
quantiles = np.quantile(mc_std, np.linspace(0, 1, 6))
bin_stds, bin_rmses = [], []
for i in range(5):
    mask = (mc_std >= quantiles[i]) & (mc_std <= quantiles[i + 1])
    bin_stds.append(mc_std[mask].mean())
    bin_rmses.append(np.sqrt(sq_err[mask].mean()))

# 2. 计算典型分布内常规分子 vs. 极端分布外 (OOD) 分子的 MC Dropout 标准差
probe_mols = [
    ("Ethanol (In-Domain)", "CCO"),
    ("Benzoic acid (In-Domain)", "O=C(O)c1ccccc1"),
    ("Perfluorooctane C8F18 (OOD)", "FC(F)(F)C(F)(F)C(F)(F)C(F)(F)C(F)(F)C(F)(F)C(F)(F)C(F)(F)F"),
    ("Decabromodiphenyl ether (OOD)", "Brc1c(Br)c(Br)c(Oc2c(Br)c(Br)c(Br)c(Br)c2Br)c(Br)c1Br"),
]
probe_feats = []
for _, smi in probe_mols:
    m = Chem.MolFromSmiles(smi)
    probe_feats.append([getattr(Descriptors, c)(m) for c in feature_cols])
X_probe_t = to_t(scaler.transform(np.array(probe_feats)))
set_seed(1)
probe_mu, probe_sd = mc_dropout_predict(big_reg, X_probe_t, n_samples=60)

print("=== 分布内 vs. 分布外 (OOD) 分子的 MC Dropout 认知不确定性预警 ===")
for (name, _), mu_v, sd_v in zip(probe_mols, probe_mu, probe_sd):
    print(f"  {name:32s} -> Pred logS = {mu_v:6.2f} ± {sd_v:.3f}")

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.2, 3.9))
ax1.plot(bin_stds, bin_rmses, "o-", lw=2.2, ms=7, color=C.navy)
for q_i, (xs, yr) in enumerate(zip(bin_stds, bin_rmses), 1):
    ax1.annotate(f"Q{q_i}", (xs + 0.008, yr + 0.02), fontsize=8.8)
ax1.set_xlabel("Mean MC Dropout Predictive Std $\\hat{\\sigma}(x)$")
ax1.set_ylabel("Empirical Test RMSE (logS)")
ax1.set_title("a) Uncertainty Calibration Across 5 Test Quintiles")

names_short = ["Ethanol\n(ID)", "Benzoic\n(ID)", "C8F18\n(OOD)", "Deca-BDE\n(OOD)"]
bar_cols = [C.teal, C.teal, C.crimson, C.crimson]
bars = ax2.bar(names_short, probe_sd, color=bar_cols, width=0.52)
ax2.axhline(np.median(mc_std), color=C.slate, ls="--", lw=1.3, label=f"AqSolDB Test Median $\\hat{{\\sigma}}$ ({np.median(mc_std):.2f})")
for b in bars:
    ax2.text(b.get_x() + b.get_width() / 2, b.get_height() + 0.02, f"{b.get_height():.2f}", ha="center", fontsize=8.8, fontweight="bold")
ax2.set_ylabel("MC Dropout Uncertainty $\\hat{\\sigma}(x)$")
ax2.set_title("b) OOD Exotic Molecules Trigger High Uncertainty")
ax2.set_ylim(0, max(probe_sd) * 1.22)
ax2.legend(fontsize=8.3)
plt.tight_layout()
plt.show()
Out:
=== 分布内 vs. 分布外 (OOD) 分子的 MC Dropout 认知不确定性预警 ===
  Ethanol (In-Domain)              -> Pred logS =   0.84 ± 0.304
  Benzoic acid (In-Domain)         -> Pred logS =  -0.93 ± 0.187
  Perfluorooctane C8F18 (OOD)      -> Pred logS =  -7.12 ± 0.747
  Decabromodiphenyl ether (OOD)    -> Pred logS =  -8.26 ± 1.058
Notebook 输出图像

注意上方 mc_dropout_predict 中的工程黄金细节:当网络同时包含 BatchNorm 与 Dropout 时,做 MC Dropout 绝对不能粗暴地对整个模型调 model.train()(那会把 BatchNorm 的归一化统计量也搅乱!),而应当先 model.eval() 冻结全局统计量,再单独遍历 isinstance(m, nn.Dropout) 开启随机失活!

🏋️ 练习 07b-3:基于 MC Dropout 置信度过滤的“拒绝预测(Selective Prediction)”曲线

在自动化高通量筛选中,如果允许模型拒绝回答它最没把握(mc_std 最高)的 \(k\%\) 疑难分子(转交昂贵的湿实验或量子化学复核),剩余被模型接受的分子准确率会提升多少? 请利用上面算好的 mc_mean, mc_std, yte,计算当保留比例(Coverage)从 \(100\%\) 逐步收紧到 \(80\%, 60\%, 40\%, 20\%\)(每次只保留 mc_std 最小的那部分测试分子)时,留存样本的测试集 RMSE 变化并画出曲线!

In [14] · Python
# 练习 07b-3:在此计算并绘制 Selective Prediction (Coverage vs. Retained Test RMSE) 曲线

本节小结

训练动力学维度 故障机理与现代深度学习标准处方
反向传播链式法则 局部雅可比连乘 + 缓存前向激活张量;手写 15 行矩阵求导与 PyTorch autograd 严格一致
激活函数选型 弃用隐藏层 Sigmoid(导数上限 \(0.25\) 致严重梯度消失);分类/通用首选 ReLU / GELU,平滑物理势能面首选无穷阶可导的 SiLU
权重初始化与归一化 Tanh 配 Xavier,ReLU/SiLU 配 Kaiming He(\(\sqrt{2/n_{\text{in}}}\));BatchNorm1d 稳定深层分布,推理时切记 model.eval()
优化器与梯度裁剪 动量抵消峡谷横壁震荡,AdamW 自适应各参数步长并解耦权重衰减;遇悬崖损失配合 clip_grad_norm_ 锁死步幅
双下降与 MC Dropout \(P \approx N\) 插值阈值处过拟合最剧烈;推理期仅激活 nn.Dropout 采样 \(T\) 次即可低成本获取校准良好的认知不确定性与 OOD 预警

掌握了深层网络的全部训练内功后,下一节 07c_cnn_resnet_and_microstructure_segmentation.ipynb 我们将正式告别手工表格描述符,进入计算机视觉与定量金相学——从二维卷积、残差跳跃连接(ResBlock)一直实战到轻量级 U-Net 显微图像像素级语义分割与析出相粒径统计!

读完了?

标记为已学完,进度会同步到课程大纲与首页的元素周期表。

返回模块 07