模型权值共享/参数访问/初始化

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模型权值共享方法有两种:

  1. Module类的forward函数里多次调用同一个层

  1. 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[1].weight))
"""输出:因为在内存中,这两个线性层其实一个对象
True
True
"""

x = torch.ones(1, 1)
y = net(x).sum()
print(y)
y.backward()
print(net[0].weight.grad)     # 单次梯度是3,两次所以就是6
"""因为模型参数里包含了梯度,所以在反向传播计算时,这些共享的参数的梯度是累加的:
tensor(9., grad_fn=<SumBackward0>)
tensor([[6.]])
"""

与之相比较的是:

linear1 = nn.Linear(1, 1, bias=False)
linear2 = nn.Linear(1, 1, bias=False)
net = nn.Sequential(linear1, linear2) 
print(net)
for name, param innet.named_parameters():
    init.constant_(param, val=3)
    print(name, param.data)

x = torch.ones(1, 1)
y = net(x).sum()
print(y)
y.backward()
print(net[0].weight.grad)
"""
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.]])
1.weight tensor([[3.]])

tensor(9., grad_fn=<SumBackward0>)
tensor([[3.]])
"""

这里linear1和linear2不是同一个对象.所以net的参数是有两个的.反向传播后,net[0].weight.grad是tensor([[3.]])

模型参数访问

这两个方法是在nn.Module类中实现的.继承自该类的子类也有相同方法.

  1. .parameters()

  1. .named_parameters()

具体实现细节:https://www.cnblogs.com/sdu20112013/p/12134330.html

模型参数初始化

通常对各种layer,pytorch已经实现好了默认的比较合理的初始化方式,不需要我们操心。如果要自己初始化权重,则遍历net的所有参数,对其执行相应的初始化策略.例如在下面的例子中,我们将权重参数初始化成均值为0、标准差为0.01的正态分布随机数,并依然将偏差参数清零。

forname, param in net.named_parameters():
    if'weight'inname:
        init.normal_(param, mean=0, std=0.01)
        print(name, param.data)
    elif 'bias'inname:
        init.constant_(param,0)
        print(name, param.data)

上面使用了torch.nn.init中自带的初始化方法,也可以自己实现一个满足自己需求的初始化方法.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值