模型权值共享方法有两种:
Module类的forward函数里多次调用同一个层
在Sequential模块中重复传入同一个Module实例
linear = nn.Linear(1, 1, bias=False)
net = nn.Sequential(linear, linear)
print(net)
for name, param in net.named_parameters():
init.constant_(param, val=3)
print(name, param.data)
"""输出:
Sequential(
(0): Linear(in_features=1, out_features=1, bias=False)
(1): Linear(in_features=1, out_features=1, bias=False)
)
0.weight tensor([[3.]])
"""
print(id(net[0]) == id(net[1]))
print(id(net[0].weight) == id(net[

文章介绍了在PyTorch中两种权值共享的方法,包括在同一Module的forward函数中重复调用层和在Sequential模块中使用相同的Module实例。通过示例展示了权值共享如何影响反向传播中的梯度计算,并对比了不共享权值的情况。此外,还讨论了模型参数的初始化,通常PyTorch提供默认初始化,但用户可以自定义初始化策略,如使用正态分布或常量初始化权重和偏差。
最低0.47元/天 解锁文章
1242

被折叠的 条评论
为什么被折叠?



