您可以使用张量的data 属性来修改值,因为对data 的修改不会影响图形。
因此,图形仍然是完整的,data 属性本身的修改对图形没有影响。 (data 上的操作和更改不会被 autograd 跟踪,因此不会出现在图中)
由于您没有给出示例,因此此示例基于您的评论声明:
'假设我想更改图层的权重。'
我在这里使用了普通张量,但这对于层的 weight.data 和 bias.data 属性同样适用。
这是一个简短的例子:
import torch
import torch.nn.functional as F
# Test 1, random vector with CE
w1 = torch.rand(1, 3, requires_grad=True)
loss = F.cross_entropy(w1, torch.tensor([1]))
loss.backward()
print('w1.data', w1)
print('w1.grad', w1.grad)
print()
# Test 2, replacing values of w2 with w1, before CE
# to make sure that everything is exactly like in Test 1 after replacing the values
w2 = torch.zeros(1, 3, requires_grad=True)
w2.data = w1.data
loss = F.cross_entropy(w2, torch.tensor([1]))
loss.backward()
print('w2.data', w2)
print('w2.grad', w2.grad)
print()
# Test 3, replace data after computation
w3 = torch.rand(1, 3, requires_grad=True)
loss = F.cross_entropy(w3, torch.tensor([1]))
# setting values
# the graph of the previous computation is still intact as you can in the below print-outs
w3.data = w1.data
loss.backward()
# data were replaced with values from w1
print('w3.data', w3)
# gradient still shows results from computation with w3
print('w3.grad', w3.grad)
输出:
w1.data tensor([[ 0.9367, 0.6669, 0.3106]])
w1.grad tensor([[ 0.4351, -0.6678, 0.2326]])
w2.data tensor([[ 0.9367, 0.6669, 0.3106]])
w2.grad tensor([[ 0.4351, -0.6678, 0.2326]])
w3.data tensor([[ 0.9367, 0.6669, 0.3106]])
w3.grad tensor([[ 0.3179, -0.7114, 0.3935]])
这里最有趣的部分是w3。在调用backward 时,这些值将替换为w1 的值。
但梯度是基于 CE 函数计算的,其值为原始w3。替换的值对图表没有影响。
所以图连接没有断开,替换对图有没有影响。我希望这就是你要找的东西!