【发布时间】:2021-04-08 06:17:38
【问题描述】:
我正在尝试区分 PyTorch 中的渐变。我找到了this 链接,但无法使用。
我的代码如下:
import torch
from torch.autograd import grad
import torch.nn as nn
import torch.optim as optim
class net_x(nn.Module):
def __init__(self):
super(net_x, self).__init__()
self.fc1=nn.Linear(2, 20)
self.fc2=nn.Linear(20, 20)
self.out=nn.Linear(20, 4)
def forward(self, x):
x=self.fc1(x)
x=self.fc2(x)
x=self.out(x)
return x
nx = net_x()
r = torch.tensor([1.0,2.0])
nx(r)
>>>tensor([-0.2356, -0.7315, -0.2100, -0.6741], grad_fn=<AddBackward0>)
但是当我尝试根据第一个参数来区分函数时
grad(nx, r[0])
我得到了错误
TypeError: 'net_x' object is not iterable
更新
试图将其扩展到张量:
由于某种原因,所有输入的梯度都是相同的。
a = torch.rand((8,2), requires_grad=True)
s = []
s_t = []
for input_tensor in a:
output_tensor = nx(input_tensor)
s.append(output_tensor[0])
s_t_value = grad(output_tensor[0], input_tensor)[0][0]
s_t.append(s_t_value)
print(s_t)
但是输出是:
[tensor(-0.1326), tensor(-0.1326), tensor(-0.1326), tensor(-0.1326), tensor(-0.1326), tensor(-0.1326), tensor(-0.1326), tensor(-0.1326)]
【问题讨论】:
-
我觉得问题在于您将模型输入到 grad 函数中。在您链接的示例中,我认为他使用中间人函数来获取梯度,因为作为第一个参数的输出需要是张量序列,而不是全尺寸模型,对吗?
-
@Canbach 你可能是对的。我不知道如何改变它。有什么建议吗?