Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何计算PyTorch中张量的梯度?_Pytorch - Fatal编程技术网

如何计算PyTorch中张量的梯度?

如何计算PyTorch中张量的梯度?,pytorch,Pytorch,我想计算张量的梯度,但它给出的误差为 RunTimeerror: grad can be implicitly created only for scalar outputs 以下是我试图编写的代码: x = torch.full((2,3), 4,requires_grad=True) y = (2*x**2+3) y.backward() 在这一点上,它抛出了一个错误。因为没有求和/减少损失值,比如.sum() 因此,可以通过以下方式解决该问题: y.backward(torch.one

我想计算张量的梯度,但它给出的误差为

RunTimeerror: grad can be implicitly created only for scalar outputs
以下是我试图编写的代码:

x = torch.full((2,3), 4,requires_grad=True)
y = (2*x**2+3)
y.backward()

在这一点上,它抛出了一个错误。

因为没有求和/减少损失值,比如
.sum()
因此,可以通过以下方式解决该问题:

y.backward(torch.ones_like(x))
对张量为1的张量进行雅可比矢量积,得到梯度