机器学习与深度学习 / 系统课时

查看模型结构与参数

查看模型结构与参数

模型能够运行并不代表结构一定符合预期。调试网络时应同时检查模块层级、每个参数的形状、是否参与训练以及参数总量。本篇构造一个小型全连接网络,并用 PyTorch 自带接口完成这些检查,而不是只依赖打印一行模型名称。

学习目标

  • 使用 print(model)、named_modules() 和 named_parameters() 检查模型
  • 根据参数形状计算并核对参数数量
  • 区分模型总参数与 requires_grad=True 的可训练参数

查看模块层级

print(model) 会调用 nn.Module 的字符串表示,适合先检查子模块名称、嵌套关系以及层的关键构造参数。下面的网络输入特征数为 4,隐藏层宽度为 8,输出类别数为 3。

python
import torch
from torch import nn


class TinyNet(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.backbone = nn.Sequential(
            nn.Linear(4, 8),
            nn.ReLU(),
        )
        self.head = nn.Linear(8, 3)

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


model = TinyNet()
print(model)

预期输出:

text
TinyNet(
  (backbone): Sequential(
    (0): Linear(in_features=4, out_features=8, bias=True)
    (1): ReLU()
  )
  (head): Linear(in_features=8, out_features=3, bias=True)
)

这里可以直接核对数据通路:第一层把 4 维特征映射为 8 维,最后一层必须接收 8 维并输出 3 维。如果把 head 错写成 nn.Linear(4, 3),结构打印阶段就能发现接口尺寸不一致,无需等到训练时再处理矩阵乘法错误。

检查参数名称与形状

model.named_parameters() 按注册名称返回参数。Linear(4, 8) 的权重形状是 (8, 4),偏置形状是 (8,);这与前向传播中输入最后一维为 4、输出最后一维为 8 相对应。

python
for name, parameter in model.named_parameters():
    print(
        f"{name:20s} shape={str(tuple(parameter.shape)):8s} "
        f"numel={parameter.numel():2d} trainable={parameter.requires_grad}"
    )

预期输出:

text
backbone.0.weight    shape=(8, 4)   numel=32 trainable=True
backbone.0.bias      shape=(8,)     numel= 8 trainable=True
head.weight          shape=(3, 8)   numel=24 trainable=True
head.bias            shape=(3,)     numel= 3 trainable=True

参数名也会进入 state_dict() 的键,因此稳定的模块命名有助于保存、加载和定位权重。没有可学习参数的 ReLU 不会出现在 named_parameters() 中,这是正常现象。

核对参数总量

参数数量可用 parameter.numel() 计算。当前模型第一层有 8×4+8=408\times4+8=40 个参数,输出层有 3×8+3=273\times8+3=27 个参数,总计 67 个。

python
total = sum(p.numel() for p in model.parameters())
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)

print(f"total={total}")
print(f"trainable={trainable}")

预期输出:

text
total=67
trainable=67

参数量适合用于发现意外扩大网络的错误。例如把隐藏层从 8 改为 800 后,仅第一层权重就从 32 增加到 3200;在大模型中,这种尺寸错误还会直接增加显存占用和优化器状态。

验证冻结参数是否生效

迁移学习或分阶段训练经常需要冻结部分模块。设置 requires_grad_(False) 后,参数仍属于模型,也仍会出现在 state_dict() 中,但不会由反向传播计算梯度。检查时应同时打印总参数与可训练参数,不能只看模型结构。

python
for parameter in model.backbone.parameters():
    parameter.requires_grad_(False)

total = sum(p.numel() for p in model.parameters())
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)

print(f"total={total}")
print(f"trainable={trainable}")

for name, parameter in model.named_parameters():
    if parameter.requires_grad:
        print(f"trainable parameter: {name}")

预期输出:

text
total=67
trainable=27
trainable parameter: head.weight
trainable parameter: head.bias

冻结后总参数仍是 67,但只有分类头的 27 个参数可训练。创建优化器时可以显式筛选 requires_grad=True 的参数,避免把已冻结参数无意义地放进优化器参数组。

用一次前向传播检查接口

静态结构正确后,再用符合预期形状的假输入执行一次前向传播。对于这个模型,批量大小为 5、每个样本 4 个特征时,输出应为 (5, 3)。

python
x = torch.randn(5, 4)
y = model(x)

print(f"input shape={tuple(x.shape)}")
print(f"output shape={tuple(y.shape)}")
assert y.shape == (5, 3)

预期输出:

text
input shape=(5, 4)
output shape=(5, 3)

结构打印、参数枚举和一次假输入分别检查不同问题:print(model) 看模块连接,named_parameters() 看权重形状与训练状态,前向传播则确认这些模块在真实张量尺寸下能够连通。三项检查都通过后,再进入正式训练更容易定位后续问题。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

查看模型结构与参数

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通