我想使用 PyTorch 获取输出和输入之间的偏导数。假设我有一个函数Y = 5*x1^4 + 3*x2^3 + 7*x1^2 + 9*x2 - 5
,然后我训练一个网络来替换这个函数,然后我使用 autograd 来计算dYdx1, dYdx2
:
net = torch.load('net_723.pkl')
x = torch.tensor([[1,-1]],requires_grad=True).type(torch.FloatTensor)
y = net(x)
grad_c = torch.autograd.grad(y,x,create_graph=True,retain_graph=True)[0]
然后我得到一个错误的导数:
>>>tensor([[ 7.5583, -5.3173]])
但是当我使用函数计算时,我得到了正确的答案:
Y = 5*x[0,0]**4 + 3*x[0,1]**3 + 7*x[0,0]**2 + 9*x[0,1] - 5
grad_c = torch.autograd.grad(Y,x,create_graph=True,retain_graph=True)[0]
>>>tensor([[ 34., 18.]])
为什么会出现这种情况?