本习题集紧扣第七讲三大主干模块——07a(感知机 XOR 空间折叠、Autograd 与 MLP)、07b(手写反向传播、He 初始化、BatchNorm 与 MC Dropout)与 07c(二维卷积尺寸推导、残差块 ResBlock 与显微语义分割 IoU/Dice 指标)——设计了 8 道自包含编程练习。
- 请在
# TODO位置补全代码并运行自检断言; - 完整参考答案见
solutions/07_exercises_solutions.ipynb。
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch import nn
import torch.nn.functional as F
%matplotlib inline
torch.manual_seed(42)
np.random.seed(42)
📘 课程统一绘图风格:加载课程自带的
ai4m.mplstyle与配色C(本地与solutions/子目录自动兼容)。
import pathlib, sys
for cand in [pathlib.Path.cwd().parent, pathlib.Path.cwd().parent.parent]:
if (cand / "ai4m_style.py").exists():
sys.path.insert(0, str(cand))
break
import ai4m_style as ai4m
C = ai4m.use()
习题 1:XOR 双掺杂协同效应与二维 ReLU 隐藏层“空间折叠”(对应 07a)
给定 4 个双元素掺杂角点 X_xor(形状 (4, 2))与目标活性标签 y_xor = [0, 1, 1, 0]:
- 用矩阵运算实现 2 单元隐藏层映射 \(\mathbf{H} = \operatorname{ReLU}(\mathbf{X}\mathbf{W}_1 + \mathbf{b}_1)\),其中 \(\mathbf{W}_1 = \begin{bmatrix}1 & 1 \\ 1 & 1\end{bmatrix}\),\(\mathbf{b}_1 = \begin{bmatrix}0 & -1\end{bmatrix}\);
- 用输出层权重 \(\mathbf{w}_2 = \begin{bmatrix}1 \\ -2\end{bmatrix}\)、偏置 \(b_2 = 0\) 计算预测值
y_pred = (H @ w2) + b2,验证它精确还原了线性不可分的[0, 1, 1, 0]!
X_xor = torch.tensor([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]])
y_xor = torch.tensor([0.0, 1.0, 1.0, 0.0])
# TODO: 构造 W1, b1, w2 并计算折叠后的隐藏层表示 H 与最终预测 y_pred
H = None
y_pred = None
# print("Folded hidden representations H:\n", H)
# print("Exact XOR predictions:", y_pred)
习题 2:用 Autograd 求固溶体自由能偏导并排查梯度累加陷阱(对应 07a)
设某二元固溶体自由能函数在温度 \(T = 3.0\)、组分 \(c = 2.0\) 处的简化模型为:
- 创建开启
requires_grad=True的标量张量T与c,计算G并调用G.backward()得到化学势项偏导 \(\partial G / \partial T\) 与 \(\partial G / \partial c\); - 梯度清零练习:将
T.grad.zero_()与c.grad.zero_()清零后,重新计算 \(G_2 = T \cdot c\) 的偏导数,确保旧梯度没有残留累加。
# TODO: 1) 定义 T=3.0, c=2.0 (requires_grad=True),求 G 的偏导数 dG_dT, dG_dc
# 2) 调用 .grad.zero_() 清零后,再求 (T * c) 的偏导数
T = None
c = None
dG_dT, dG_dc = None, None
习题 3:手写双层感知机反向传播并与 PyTorch autograd 精确对拍(对应 07b)
给定单隐藏层 Tanh 网络:\(\mathbf{Z}_1 = \mathbf{X}\mathbf{W}_1 + \mathbf{b}_1\),\(\mathbf{A}_1 = \tanh(\mathbf{Z}_1)\),\(\hat{\mathbf{Y}} = \mathbf{A}_1 \mathbf{W}_2 + \mathbf{b}_2\),损失函数 \(L = \frac{1}{N}\sum (\hat{y}_i - y_i)^2\)。
已知 \(\tanh'(z) = 1 - \tanh^2(z) = 1 - a^2\),请用纯 NumPy 写出 dW2_np, db2_np, dW1_np, db1_np,并验证与 PyTorch autograd 的最大绝对误差 \(< 10^{-7}\)!
rng = np.random.RandomState(0)
X_np = rng.randn(12, 4).astype(np.float64)
Y_np = rng.randn(12, 1).astype(np.float64)
W1_np = (rng.randn(4, 6) * 0.4).astype(np.float64)
b1_np = np.zeros(6, dtype=np.float64)
W2_np = (rng.randn(6, 1) * 0.4).astype(np.float64)
b2_np = np.zeros(1, dtype=np.float64)
# TODO: 用纯 NumPy 计算 Z1, A1=np.tanh(Z1), Y_hat 以及反向梯度 dW2_np, db2_np, dW1_np, db1_np
dW1_np, db1_np, dW2_np, db2_np = None, None, None, None
习题 4:手写 Kaiming (He) 正态初始化稳定 6 层深层 ReLU 激活方差(对应 07b)
给定一个 6 层无偏置 ReLU 网络(每层宽度 \(n_{\text{in}} = n_{\text{out}} = 128\))与标准正态输入 x_in = torch.randn(512, 128)。
请编写函数 he_init_depth_std(x_in, depth=6):不用 nn.init.kaiming_normal_,而是直接按公式从 \(\mathcal{N}(0, \sigma_w^2)\)(其中 \(\sigma_w = \sqrt{2 / n_{\text{in}}}\))采样每层权重矩阵,返回第 6 层经过 ReLU 后的激活标准差 std_l6,验证它稳定在 \([0.5, 1.2]\) 的健康区间内(而朴素 std=0.02 会坍缩到 \(< 10^{-5}\))!
torch.manual_seed(7)
x_in = torch.randn(512, 128)
def he_init_depth_std(x, depth=6):
# TODO: 按 sigma_w = sqrt(2 / n_in) 生成每层权重矩阵并前向穿过 6 层 ReLU,返回末尾激活的 std().item()
pass
# print("Layer-6 activation std:", he_init_depth_std(x_in))
习题 5:同时含 BatchNorm1d 与 Dropout 时的安全 MC Dropout 采样(对应 07b)
下面为您预训练好了一个同时包含 nn.BatchNorm1d 与 nn.Dropout(0.25) 的回归网络 bn_drop_net(训练区间 \(x \in [-2, 2]\))。
如果要对单个分子样本(batch_size = 1!)执行 \(T = 80\) 次 MC Dropout 采样,直接调用 bn_drop_net.train() 会直接触发 ValueError: Expected more than 1 value per channel when training(因为 BatchNorm1d 无法在单样本上计算批方差!)。
请实现函数 safe_mc_dropout(model, x_single, T=80):
- 先调用
model.eval()冻结BatchNorm1d的全局移动平均统计量; - 仅将模型中属于
nn.Dropout的子模块单独切换为.train(); - 在
torch.no_grad()下重复前向计算 \(T\) 次,分别返回内插点 \(x=0.5\) 与外推点 \(x=6.0\) 的预测标准差(std_in, std_out),验证单样本推理不报错且std_out > 2.0 * std_in!
torch.manual_seed(42)
bn_drop_net = nn.Sequential(
nn.Linear(1, 64), nn.BatchNorm1d(64), nn.ReLU(), nn.Dropout(0.25),
nn.Linear(64, 64), nn.BatchNorm1d(64), nn.ReLU(), nn.Dropout(0.25),
nn.Linear(64, 1),
)
x_tr5 = torch.linspace(-2.0, 2.0, 96).unsqueeze(1)
y_tr5 = torch.sin(1.5 * x_tr5)
opt5 = torch.optim.Adam(bn_drop_net.parameters(), lr=1e-2)
for _ in range(160):
bn_drop_net.train()
l5 = F.mse_loss(bn_drop_net(x_tr5), y_tr5)
opt5.zero_grad(); l5.backward(); opt5.step()
def safe_mc_dropout(model, x_single, T=80):
# TODO: 冻结 BatchNorm (eval),仅开启 nn.Dropout (train),对单样本 x_single 采样 T 次返回 (mean, std)
pass
# _, std_in = safe_mc_dropout(bn_drop_net, torch.tensor([[0.5]]))
# _, std_out = safe_mc_dropout(bn_drop_net, torch.tensor([[6.0]]))
# print(std_in, std_out)
习题 6:推导编码器下采样与转置卷积上采样的特征图尺寸(对应 07c)
给定单通道显微图批次 x_img = torch.zeros(4, 1, 48, 48),依次经过:
enc1 = nn.Conv2d(1, 12, kernel_size=3, stride=1, padding=1)pool = nn.MaxPool2d(kernel_size=2, stride=2)bot = nn.Conv2d(12, 24, kernel_size=3, stride=2, padding=1)(注意步幅stride=2!)up = nn.ConvTranspose2d(24, 12, kernel_size=2, stride=2)
请先心算第 3 步 bot 输出与第 4 步 up 输出的空间形状,再编写代码构建上述层,验证 up 的输出恰好与第 2 步 pool(enc1(x_img)) 空间尺寸一致,从而可以沿通道维 dim=1 执行 U-Net 跳跃拼接 torch.cat!
x_img = torch.zeros(4, 1, 48, 48)
# TODO: 构建 enc1, pool, bot, up 并验证 torch.cat([h_up, h_enc], dim=1) 的形状为 (4, 24, 24, 24)
h_cat = None
习题 7:实现二维残差块 SimpleResBlock 并验证恒等梯度高速公路(对应 07c)
请实现继承自 nn.Module 的残差模块 SimpleResBlock(channels):
- 主分支
self.conv_path:Conv2d(c, c, 3, padding=1) -> ReLU -> Conv2d(c, c, 3, padding=1); - 前向传播:
return F.relu(self.conv_path(x) + x)。
梯度高速公路检验:将 self.conv_path 中的所有权重和偏置全部手工置零(此时普通无跳跃网络梯度会彻底死绝为 0!),对非负输入 x = torch.rand(2, 8, 16, 16, requires_grad=True) 计算 y = block(x); y.sum().backward(),验证输入梯度 x.grad 全等于 1.0!
class SimpleResBlock(nn.Module):
def __init__(self, channels):
super().__init__()
# TODO: 定义双层 3x3 卷积残差支路
pass
def forward(self, x):
# TODO: 返回 F.relu(conv_path(x) + x)
pass
# TODO: 将 conv_path 参数置零,验证正值输入 x_res 的反向传播梯度恒为 1.0
习题 8:手写显微图像语义分割的交并比(IoU)与 Dice 评估函数(对应 07c)
给定单张 \(32\times 32\) 显微图的真实析出相二值掩膜 true_mask 与分割模型预测掩膜 pred_mask(元素为 0 或 1):
- 实现函数
seg_metrics(pred_mask, true_mask),精确计算并返回字典:"pixel_acc":全部像素分类正确的比例(观察它在前景稀疏时有多具欺骗性!);"iou":\(\frac{|P \cap G|}{|P \cup G|}\);"dice":\(\frac{2|P \cap G|}{|P| + |G|}\);"area_frac_abs_err":\(|\bar{P} - \bar{G}|\)(面积分数绝对误差)。
- 验证数学恒等关系:\(\operatorname{Dice} = \frac{2 \operatorname{IoU}}{1 + \operatorname{IoU}}\)!
yy, xx = np.mgrid[0:32, 0:32]
true_mask = (((yy - 14) ** 2 + (xx - 14) ** 2) <= 6 ** 2).astype(np.int32)
pred_mask = (((yy - 16) ** 2 + (xx - 15) ** 2) <= 6 ** 2).astype(np.int32)
def seg_metrics(pred, target):
# TODO: 计算并返回 {"pixel_acc": ..., "iou": ..., "dice": ..., "area_frac_abs_err": ...}
pass
# m8 = seg_metrics(pred_mask, true_mask)
# print(m8)