机器学习与深度学习 / 系统课时
线性层与参数
线性层与参数
nn.Linear 是全连接网络的基础模块,但它的权重形状、批次维度和参数注册方式很容易混淆。本课将用一个可运行示例检查线性层内部参数,并建立输入到输出的形状规则。
学习目标
- 能说明线性层的计算规则和形状变化。
- 能查看权重、偏置及其注册名称。
- 能判断输入维度不匹配等常见问题。
线性层做了什么
对于 nn.Linear(in_features, out_features),每个样本都会执行一次仿射变换:
PyTorch 将权重保存为 (out_features, in_features),偏置保存为 (out_features,)。输入最后一维必须等于 in_features,输出最后一维会变为 out_features。
| 对象 | 形状 | 作用 |
|---|---|---|
输入 X |
(batch_size, in_features) |
一批样本的输入特征 |
权重 W |
(out_features, in_features) |
将输入特征映射到输出特征 |
偏置 b |
(out_features,) |
为每个输出特征增加偏移 |
输出 Y |
(batch_size, out_features) |
线性层的计算结果 |

图中的批次维度不会被线性层改变,真正参与映射的是输入的最后一维。
查看参数注册和形状
下面创建一个输入维度为 4、输出维度为 3 的线性层,并检查参数名称与前向传播结果。
python
import torch
from torch import nn
if __name__ == "__main__":
torch.manual_seed(0)
layer = nn.Linear(in_features=4, out_features=3, bias=True)
x = torch.randn(2, 4)
y = layer(x)
print("weight:", tuple(layer.weight.shape))
print("bias:", tuple(layer.bias.shape))
print("input:", tuple(x.shape))
print("output:", tuple(y.shape))
print("parameters:", [name for name, _ in layer.named_parameters()])预期输出
text
weight: (3, 4)
bias: (3,)
input: (2, 4)
output: (2, 3)
parameters: ['weight', 'bias']named_parameters() 能找到 weight 和 bias,说明它们已经作为 nn.Parameter 注册。优化器接收 model.parameters() 后,就能自动更新这些参数。
参数注册与关键边界
参数一旦挂载到 nn.Module,就会出现在 parameters()、named_parameters() 和 state_dict() 中。这套机制让优化器能够获取待更新变量,也让模型保存和 .to(device) 设备迁移保持一致。
权重形状是 (输出特征数, 输入特征数),不要按直觉写反。若输入为三维或更高维,nn.Linear 仍只变换最后一维,前面的批次或序列维度会被保留。
设置 bias=False 后,线性层只保留权重参数,named_parameters() 中不会出现 bias。输入最后一维与 in_features 不一致时,矩阵乘法会直接报形状不匹配错误。
按自己的节奏,确认真正理解。