你对 张量 进行了梯度求值
解决方法在求梯度的时候传一个同维度的张量即可。
错误示例代码如下import torch # 第一步:创建 tensor x = torch.ones(2,2,requires_grad=True) print(x) # 第二步:对 tensor 做处理 # x的平方 y = x**2 print(y) # 第三步:求梯度 y.backward() # 错误出现在这里,因为 y 是一个张量 print(x.grad)正确示例代码
import torch # 第一步:创建 tensor x = torch.ones(2,2,requires_grad=True) print(x) # 第二步:对 tensor 做处理 y = x**2 print(y) # 第三步:求梯度 y.backward(torch.ones(2,2)) # 传入一个相同维度的张量即可 print(x.grad)



