运行时错误:叶变量已移至图形内部

Yib*_*ang 3 pytorch

我尝试使用 pytorch 进行自动渐变。当我测试时,我遇到了错误。我的代码如下:

w11 = torch.rand((100,2), requires_grad=True)
w12 = torch.rand((100,2), requires_grad=True)
w12[:,1] = w12[:,1] + 1
w13 = torch.rand((100,2), requires_grad=True)
w13[:,1] = w13[:,1] + 2
out1=(w11-w12)**2
out2=out1.mean()
out2.backward(retain_graph=True)
Run Code Online (Sandbox Code Playgroud)

kob*_*ako 6

with torch.no_grad()当你想用requires_grad=True替换张量中的某些内容时使用,

w11 = torch.rand((100,2), requires_grad=True)
w12 = torch.rand((100,2), requires_grad=True)
w13 = torch.rand((100,2), requires_grad=True)
with torch.no_grad():
  w12[:,1] = w12[:,1] + 1
  w13[:,1] = w13[:,1] + 2
out1=(w11-w12)**2
out2=out1.mean()
out2.backward(retain_graph=True)
Run Code Online (Sandbox Code Playgroud)

一切都会顺利。