import torch
import torch.nn as nn# 定义线性层
linear_layer = nn.Linear(in_features=10, out_features=5, bias=True)# 输入数据
input_data = torch.randn(32, 10) # (batch_size=32, in_features=10)# 前向传播
output = linear_layer(input_data)
print(output.shape) # 输出形状: (32, 5)
维度变化
-
输入:
(batch_size, in_features)
。 -
输出:
(batch_size, out_features)
。
示例
-
输入形状:
(32, 10)
。 -
线性层:
nn.Linear(10, 5)
。 -
输出形状:
(32, 5)
。
实现细节:矩阵乘法
关键点
-
权重和偏置的初始化:
-
如果两个
nn.Linear
层的权重和偏置相同,输入相同矩阵时,输出一定相同。 -
如果权重和偏置不同(例如随机初始化),即使输入相同,输出也会不同。
-
-
手动设置权重和偏置:
-
使用
nn.Parameter
和clone()
可以手动设置相同的权重和偏置。
-
-
默认行为:
-
nn.Linear
的权重和偏置默认是随机初始化的,因此通常情况下,两个nn.Linear
层的输出会不同。
-
总结
-
如果两个
nn.Linear
层的权重和偏置相同,输入相同矩阵时,输出一定相同。 -
如果权重和偏置不同(例如随机初始化),即使输入相同,输出也会不同。