tensor.data
的用法举例
import torch
x = torch.ones(1,requires_grad=True)
print(x)
# tensor([1.], requires_grad=True)
y = x * x
z = x.data
z *= 100
print(x)
# tensor([100.], requires_grad=True)
这里可以看出,x
的数值被 z *= 100
修改了。
接下来再对 x
求导,可以得到:
y.backward()
print(x.grad)
# tensor([200.])
这是个很严重的错误,因为 x
已经改变了。虽然不会报错,但是结果却并不正确。
tensor.detach()
的用法举例
import torch
x = torch.ones(1,requires_grad=True)
print(x)
# tensor([1.], requires_grad=True)
y = x * x
z = x.detach()
z *= 100
print(x)
# tensor([100.], requires_grad=True)
这里可以看出,x
的数值同样被 z *= 100
修改了。
接下来再对 x
求导,可以得到:
y.backward()
print(x.grad)
# RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [1]] is at version 1; expected version 0 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).
这里报错是是因为 autograd
追踪求导的时候发现数据已经发生改变,被覆盖。
结论
.data
是不安全的,.detach()
是安全的,推荐使用 .detach()
来实现数据的脱离。