a leaf Variable that requires grad has been used in an in-place operation
程序员文章站
2022-06-15 18:45:20
...
a leaf Variable that requires grad has been used in an in-place operation
这个是因为写成了x+=2,
改为y = x + 2
此时如果是写y+=2是可以的,也就是说torch变量带requires_grad 的
不能进行+=操作
import numpy as np
import torch
from torch.autograd import Variable
x = Variable(torch.ones(2,2),requires_grad=True)
x+=2
y = x + 2
# print(x.creator) # None,用户直接创建没有creater属性
# print(y.creator) # <torch.autograd._functions.basic_ops.AddConstant object at 0x7fb9b4d4b208>
z = y*y*3
out = z.mean()
out.backward()
print(x,y,z)
print(x.grad) # 输出对out对x求倒结果
print(y.grad) # y不是自动求导变量
这个也会报错:
import numpy as np import torch from torch.autograd import Variable x = torch.ones(2,2,requires_grad=True) y= torch.ones(2,2,requires_grad=False) x[np.array(y)]=0 # print(x.creator) # None,用户直接创建没有creater属性 # print(y.creator) # <torch.autograd._functions.basic_ops.AddConstant object at 0x7fb9b4d4b208> print(x)
原因:如果自动求导,不能直接赋值,不求导的可以赋值
推荐阅读
-
RuntimeError: a leaf Variable that requires grad has been used in an in-place operation
-
a leaf Variable that requires grad has been used in an in-place operation
-
RuntimeError: a leaf Variable that requires grad has been used in an in-place operation.
-
RuntimeError: a leaf Variable that requires grad has been used in an in-place operation.a += torch.o
-
yolov5报错:RuntimeError: a view of a leaf Variable that requires grad is being used in an in-place
-
RuntimeError: a view of a leaf Variable that requires grad is being used in an in-place operation.