最近在研究Pytorch和backward函数的封装。我明白如何使用它,但是当我尝试时
x = Variable(2*torch.ones(2, 2), requires_grad=True)
x.backward(x)
print(x.grad)
Run Code Online (Sandbox Code Playgroud)
我预计
tensor([[1., 1.],
[1., 1.]])
Run Code Online (Sandbox Code Playgroud)
因为它是恒等函数。然而,它返回
tensor([[2., 2.],
[2., 2.]]).
Run Code Online (Sandbox Code Playgroud)
为什么会出现这种情况?
我试图找到答案,但我不能。
我使用 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。我怎样才能度过难关?谢谢!