Getting gradient of vectorized function in pytorch(在pytorch中获取矢量化函数的梯度)
问题描述
我是 PyTorch 的新手,想做我认为非常简单的事情,但遇到了很多困难.
I am brand new to PyTorch and want to do what I assume is a very simple thing but am having a lot of difficulty.
我有函数 sin(x) * cos(x) + x^2
并且我想在任何时候获得该函数的导数.
I have the function sin(x) * cos(x) + x^2
and I want to get the derivative of that function at any point.
如果我做到这一点,它就像
If I do this with one point it works perfectly as
x = torch.autograd.Variable(torch.Tensor([4]),requires_grad=True)
y = torch.sin(x)*torch.cos(x)+torch.pow(x,2)
y.backward()
print(x.grad) # outputs tensor([7.8545])
但是,我希望能够将向量作为 x 传入并让它按元素计算导数.例如:
However, I want to be able to pass in a vector as x and for it to evaluate the derivative element-wise. For example:
Input: [4., 4., 4.,]
Output: tensor([7.8545, 7.8545, 7.8545])
但我似乎无法使其正常工作.
But I can't seem to get this working.
我试着简单地做
x = torch.tensor([4., 4., 4., 4.], requires_grad=True)
out = torch.sin(x)*torch.cos(x)+x.pow(2)
out.backward()
print(x.grad)
但是我收到错误消息RuntimeError:grad 只能为标量输出隐式创建"
But I get the error "RuntimeError: grad can be implicitly created only for scalar outputs"
如何为向量调整此代码?
How do I adjust this code for vectors?
提前致谢,
推荐答案
在这里你可以找到关于你的错误的相关讨论.
Here you can find relevant discussion about your error.
本质上,当你不带参数调用backward()
时,它被隐式转换为backward(torch.Tensor([1]))
,其中torch.Tensor([1])
是计算梯度的输出值.
In essence, when you call backward()
without arguments it is implicitly converted to backward(torch.Tensor([1]))
, where torch.Tensor([1])
is the output value with respect to which gradients are calculated.
如果您传递 4
(或更多)个输入,则每个输入都需要一个值来计算梯度.您可以像这样将 torch.ones_like
显式传递给 backward
:
If you pass 4
(or more) inputs, each needs a value with respect to which you calculate gradient. You can pass torch.ones_like
explicitly to backward
like this:
import torch
x = torch.tensor([4.0, 2.0, 1.5, 0.5], requires_grad=True)
out = torch.sin(x) * torch.cos(x) + x.pow(2)
# Pass tensor of ones, each for each item in x
out.backward(torch.ones_like(x))
print(x.grad)
这篇关于在pytorch中获取矢量化函数的梯度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在pytorch中获取矢量化函数的梯度


基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 筛选NumPy数组 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01