在torch.autograd.grad
的documentation中,指出对于参数,
我尝试以下方法:
a = torch.rand(2, requires_grad=True)
b = torch.rand(2, requires_grad=True)
c = a+b
d = a-b
torch.autograd.grad([c, d], [a, b]) #ValueError: only one element tensors can be converted to Python scalars
torch.autograd.grad(torch.tensor([c, d]), torch.tensor([a, b])) #RuntimeError: grad can be implicitly created only for scalar outputs
我想获得张量列表的梯度而没有其他张量列表的梯度。输入参数的正确方法是什么?
最佳答案
正如torch.autograd.grad所述,torch.autograd.grad
计算并返回输出w.r.t的梯度总和。输入。由于您的c
和d
不是标量值,因此grad_outputs
是必需的。
import torch
a = torch.rand(2,requires_grad=True)
b = torch.rand(2, requires_grad=True)
a
# tensor([0.2308, 0.2388], requires_grad=True)
b
# tensor([0.6314, 0.7867], requires_grad=True)
c = a*a + b*b
d = 2*a+4*b
torch.autograd.grad([c,d], inputs=[a,b], grad_outputs=[torch.Tensor([1.,1.]), torch.Tensor([1.,1.])])
# (tensor([2.4616, 2.4776]), tensor([5.2628, 5.5734]))
解释:
dc/da = 2*a = [0.2308*2, 0.2388*2]
dd/da = [2.,2.]
因此,第一个输出是dc/da*grad_outputs[0]+dd/da*grad_outputs[1] = [2.4616, 2.4776]
。第二个输出的计算相同。如果您只想获取
c
和d
w.r.t的渐变,输入,可能您可以执行以下操作:a = torch.rand(2,requires_grad=True)
b = torch.rand(2, requires_grad=True)
a
# tensor([0.9566, 0.6066], requires_grad=True)
b
# tensor([0.5248, 0.4833], requires_grad=True)
c = a*a + b*b
d = 2*a+4*b
[torch.autograd.grad(t, inputs=[a,b], grad_outputs=[torch.Tensor([1.,1.])]) for t in [c,d]]
# [(tensor([1.9133, 1.2132]), tensor([1.0496, 0.9666])),
# (tensor([2., 2.]), tensor([4., 4.]))]
关于python-3.x - pytorch autograd.grad如何编写多个输出的参数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58059268/