【问题标题】:How do I recalculate the gradient after changing the input? Pytorch更改输入后如何重新计算梯度?火炬
【发布时间】:2021-04-29 04:16:20
【问题描述】:

我正在尝试在不重新定义 a = f(x,y) 的情况下做这样的事情:

a = f(x,y)
find gradient of a with respect to x
change x
find gradient of a with respect to x
find gradient of a with respect to y

我在下面尝试了一个部分示例,但它只是给了我一个错误。有谁知道我可以如何做到这一点,而无需每次都重新定义原始功能?

>>> x = torch.tensor([2.], requires_grad=True)
>>> y = 10*x**2
>>> torch.autograd.grad(y,x, retain_graph=True)
(tensor([40.]),)
>>> x = torch.tensor([1.], requires_grad=True)
>>> torch.autograd.grad(y,x, retain_graph=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/Philip/anaconda3/lib/python3.7/site-packages/torch/autograd/__init__.py", line 157, in grad
    inputs, allow_unused)
RuntimeError: One of the differentiated Tensors appears to not have been used in the graph. Set allow_unused=True if this is the desired behavior.

【问题讨论】:

    标签: pytorch gradient


    【解决方案1】:

    更改输入后如何重新计算梯度?

    通常您需要使用新输入重新计算输出。

    考虑反向传播算法的工作方式。根据f 的形式,需要保存不同的中间结果以供反向传播算法以后使用。这些中间结果可能取决于也可能不取决于 x 的原始值,即使在计算梯度 w.r.t 时也是如此。 y.

    例如,如果f(x,y) = g(h(x,y)),则通过链式法则df/dy = dg/dh * dh/dy。为了更具体一点,让我们考虑g 是一些非线性函数和h(x,y) = x*y 的情况。然后我们有df/dy = g'(h(x,y))*x。反向传播在这里高效工作的原因是它在前向传递期间缓存了h(x,y) 的中间值,所以它需要做的就是在反向传递期间将该值插入g'。如果您更改x 的值,那么h(x,y) 的缓存值将不再是计算您感兴趣的梯度所需的正确值(应该使用h 的值计算使用新值x)。因此,您必须再次重新计算前向传递以存储正确的缓存值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-09
      • 2015-06-02
      • 2020-04-03
      • 2017-08-31
      • 1970-01-01
      • 2017-08-14
      • 2020-03-27
      • 2019-09-24
      相关资源
      最近更新 更多