您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

为什么在Pytorch中对网络的权重进行复制时,它将在反向传播后自动更新?

为什么在Pytorch中对网络的权重进行复制时,它将在反向传播后自动更新?

您必须clone使用参数,否则只需复制引用即可。

weights = []

for param in model.parameters():
    weights.append(param.clone())

criterion = nn.bceloss() # criterion and optimizer setup
optimizer = optim.Adam(model.parameters(), lr=0.001)

foo = torch.randn(3, 10) # fake input
target = torch.randn(3, 5) # fake target

result = model(foo) # predictions and comparison and backprop
loss = criterion(result, target)
optimizer.zero_grad()
loss.backward()
optimizer.step()


weights_after_backprop = [] # weights after backprop
for param in model.parameters():
    weights_after_backprop.append(param.clone()) # only layer1's weight should update, layer2 is not used

for i in zip(weights, weights_after_backprop):
    print(torch.equal(i[0], i[1]))

这使

False
False
True
True
其他 2022/1/1 18:42:54 有463人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶