如何在 PyTorch 中更新神经网络的参数? [英] How can I update the parameters of a neural network in PyTorch?
本文介绍了如何在 PyTorch 中更新神经网络的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我想在 PyTorch(继承自 torch.nn.Module
) 通过 0.9
.我该怎么做?
Let's say I wanted to multiply all parameters of a neural network in PyTorch (an instance of a class inheriting from torch.nn.Module
) by 0.9
. How would I do that?
推荐答案
让 net
成为你的神经网络类的一个实例.然后你可以做
Let net
an instance of your neural network class. You can then do
state_dict = net.state_dict()
for name, param in state_dict.items():
# Transform the parameter as required.
transformed_param = param * 0.9
# Update the parameter.
state_dict[name].copy_(transformed_param)
将所有参数乘以0.9
.
如果你只想更新权重而不是所有参数,你可以这样做
If you ever only want to update weights instead of all parameters, you can do
state_dict = net.state_dict()
for name, param in state_dict.items():
# Don't update if this is not a weight.
if not "weight" in name:
continue
# Transform the parameter as required.
transformed_param = param * 0.9
# Update the parameter.
state_dict[name].copy_(transformed_param)
这篇关于如何在 PyTorch 中更新神经网络的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文