我想在参数中添加一些错误,比如下面的代码。
import torch
import torch.nn as nn
layer = nn.Linear(10, 100)
plus_weight = torch.randn(100, 10)
layer.weight += plus_weight
但我犯了这个错误。
RuntimeError: a leaf Variable that requires grad is being used in an in-place operation.
如何避免此错误?为什么我不能直接更改图层参数值?
您可以使用.data修改叶节点的值
layer.weight.data += plus_weight
如果您想要初始化或更新参数,那么分配给.data是一种方法。但是,在前向传递的中间进行原地操作来修改叶节点的值是非常危险的,因为这可能会破坏后向传递的结果。
例如
import torch
a = torch.randn(1,1,requires_grad=True)
print(a)
b = a**2
c = torch.sum(b**2)
a.data += 1
c.backward()
print(a.grad)
输出结果将是
tensor([[0.9123]], requires_grad=True)
tensor([[6.3666]])
对于上面的代码,我们得到了c=b**2=a**2c相对于a的导数应为4*a**3。但由于您在正向过程中更新了a的值,因此b将是0.9123**2,而不是(0.9123+1(**2。a.grad的最终结果为2*(0.9123**2(*2*1.9123