如何在pytorch自定义模型的模块类中添加参数?

CSH*_*CSH 6 deep-learning pytorch

我试图找到答案,但我不能。

我使用 pytorch 制作了一个自定义的深度学习模型。例如,

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
Run Code Online (Sandbox Code Playgroud)

如果我打印

model = Net()
print(list(model.parameters()))
Run Code Online (Sandbox Code Playgroud)

它不包含model.bias,所以optimizer = optimizer.Adam(model.parameters()) 不会更新model.bias。我怎样才能度过难关?谢谢!

Sha*_*hai 8

您需要注册您的参数:

self.register_parameter(name='bias', param=torch.nn.Parameter(torch.randn(3)))
Run Code Online (Sandbox Code Playgroud)