在运行代码时出现以下错误:
a view of a leaf Variable that requires grad is being used in an in-place operation.
原因是张量的 梯度 为 True:
import torch
a = torch.ones(2, 2, requires_grad=True)
b = torch.ones(2, 2, requires_grad=True)
c = a * b
如果直接修改数据就会报错,所以正确的修改方式应该是:
a.data[0] = torch.tensor([2,1])
print("a", a)
print("c", c)
得到输出结果为:
a tensor([[2., 1.],
[1., 1.]], requires_grad=True)
c tensor([[1., 1.],
[1., 1.]], grad_fn=<MulBackward0>)
这是因为
a.data 的 requires_grad= False ,所以直接更改不会影响张量 a 的梯度选项
参考文章链接:链接