Python PyTorch autograd--只能为标量输出隐式创建梯度
我正在使用Python PyTorch autograd--只能为标量输出隐式创建梯度,python,pytorch,autograd,Python,Pytorch,Autograd,我正在使用PyTorch中的autograd工具,发现自己处于需要通过整数索引访问一维张量中的值的情况。大概是这样的: def basic_fun(x_cloned): res = [] for i in range(len(x)): res.append(x_cloned[i] * x_cloned[i]) print(res) return Variable(torch.FloatTensor(res)) def get_grad(inp,
PyTorch
中的autograd
工具,发现自己处于需要通过整数索引访问一维张量中的值的情况。大概是这样的:
def basic_fun(x_cloned):
res = []
for i in range(len(x)):
res.append(x_cloned[i] * x_cloned[i])
print(res)
return Variable(torch.FloatTensor(res))
def get_grad(inp, grad_var):
A = basic_fun(inp)
A.backward()
return grad_var.grad
x = Variable(torch.FloatTensor([1, 2, 3, 4, 5]), requires_grad=True)
x_cloned = x.clone()
print(get_grad(x_cloned, x))
我收到以下错误消息:
[tensor(1., grad_fn=<ThMulBackward>), tensor(4., grad_fn=<ThMulBackward>), tensor(9., grad_fn=<ThMulBackward>), tensor(16., grad_fn=<ThMulBackward>), tensor(25., grad_fn=<ThMulBackward>)]
Traceback (most recent call last):
File "/home/mhy/projects/pytorch-optim/predict.py", line 74, in <module>
print(get_grad(x_cloned, x))
File "/home/mhy/projects/pytorch-optim/predict.py", line 68, in get_grad
A.backward()
File "/home/mhy/.local/lib/python3.5/site-packages/torch/tensor.py", line 93, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File "/home/mhy/.local/lib/python3.5/site-packages/torch/autograd/__init__.py", line 90, in backward
allow_unreachable=True) # allow_unreachable flag
RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
在basic_fun函数中,res变量已经是torch autograd变量,您无需再次转换它。伊姆霍
def basic_fun(x_cloned):
res = []
for i in range(len(x)):
res.append(x_cloned[i] * x_cloned[i])
print(res)
#return Variable(torch.FloatTensor(res))
return res[0]
def get_grad(inp, grad_var):
A = basic_fun(inp)
A.backward()
return grad_var.grad
x = Variable(torch.FloatTensor([1, 2, 3, 4, 5]), requires_grad=True)
x_cloned = x.clone()
print(get_grad(x_cloned, x))
我将我的
basic\u fun
更改为以下内容,解决了我的问题:
def basic_fun(x_cloned):
res = torch.FloatTensor([0])
for i in range(len(x)):
res += x_cloned[i] * x_cloned[i]
return res
此版本返回标量值。您的
PyTorch
版本是什么。我在版本0.3.1
中执行了您的代码,您的代码正常工作。没有错误。我正在使用Python3.5中的0.4.1版。请看我的最新更新。谢谢你的观察!我想从张量列表中找出一个张量。我通过将返回变量(torch.FloatTensor(res))
更改为torch.stack(res,dim=0)
解决了这个问题。
def basic_fun(x_cloned):
res = torch.FloatTensor([0])
for i in range(len(x)):
res += x_cloned[i] * x_cloned[i]
return res