如何在pytorch自定义模型的模块类中添加参数? [英] How to add parameters in module class in pytorch custom model?
本文介绍了如何在pytorch自定义模型的模块类中添加参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图找到答案,但是找不到。
I tried to find the answer but I can't.
我使用pytorch创建了一个自定义的深度学习模型。例如,
I make a custom deep learning model using pytorch. For example,
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.nn_layers = nn.ModuleList()
self.layer = nn.Linear(2,3).double()
torch.nn.init.xavier_normal_(self.layer.weight)
self.bias = torch.nn.Parameter(torch.randn(3))
self.nn_layers.append(self.layer)
def forward(self, x):
activation = torch.tanh
output = activation(self.layer(x)) + self.bias
return output
如果我打印
model = Net()
print(list(model.parameters()))
它不包含model.bias,因此
Optimizer = Optimizer.Adam(model.parameters())不会更新model.bias。
我该如何处理?
谢谢!
it does not contains model.bias, so optimizer = optimizer.Adam(model.parameters()) does not update model.bias. How can I go through this? Thanks!
推荐答案
您需要注册您的参数:
self.register_parameter(name='bias', param=torch.nn.Parameter(torch.randn(3)))
这篇关于如何在pytorch自定义模型的模块类中添加参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文