如何在 PyTorch 中更新神经网络的参数?
How can I update the parameters of a neural network in PyTorch?
假设我想将 PyTorch(从 torch.nn.Module
继承的 class 的一个实例)中的神经网络的所有参数乘以 0.9
。我该怎么做?
让 net
成为神经网络 nn.Module
的一个实例。
然后,将所有参数乘以 0.9
:
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.
param.copy_(transformed_param)
如果您只想更新 权重 而不是每个参数:
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.
param.copy_(transformed_param)
实现此目的的另一种方法是使用 tensor.parameters()
。
初始化模块:
>>> a = torch.nn.Linear(2, 2)
>>> a.state_dict()
OrderedDict([('weight',
tensor([[-0.1770, -0.2151],
[-0.6543, 0.6637]])),
('bias', tensor([-0.0524, 0.6807]))])
更改参数:
for p in a.parameters():
p.data *= 0
查看效果:
>>> a.state_dict()
OrderedDict([('weight',
tensor([[-0., -0.],
[-0., 0.]])),
('bias', tensor([-0., 0.]))])
假设我想将 PyTorch(从 torch.nn.Module
继承的 class 的一个实例)中的神经网络的所有参数乘以 0.9
。我该怎么做?
让 net
成为神经网络 nn.Module
的一个实例。
然后,将所有参数乘以 0.9
:
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.
param.copy_(transformed_param)
如果您只想更新 权重 而不是每个参数:
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.
param.copy_(transformed_param)
实现此目的的另一种方法是使用 tensor.parameters()
。
初始化模块:
>>> a = torch.nn.Linear(2, 2)
>>> a.state_dict()
OrderedDict([('weight',
tensor([[-0.1770, -0.2151],
[-0.6543, 0.6637]])),
('bias', tensor([-0.0524, 0.6807]))])
更改参数:
for p in a.parameters():
p.data *= 0
查看效果:
>>> a.state_dict()
OrderedDict([('weight',
tensor([[-0., -0.],
[-0., 0.]])),
('bias', tensor([-0., 0.]))])