【问题标题】:Custom Gradients in Tensor Flow - Unable to understand this example张量流中的自定义渐变 - 无法理解此示例
【发布时间】:2021-02-10 15:34:44
【问题描述】:

我一直认为我即将了解自定义渐变,但后来我测试了这个示例,但我无法弄清楚发生了什么。我希望有人能引导我了解下面到底发生了什么。我认为这本质上是因为我没有具体理解后向函数中的“dy”是什么。

v = tf.Variable(2.0)
with tf.GradientTape() as t:
    x = v*v 
    output = x**2
print(t.gradient(output, v)) 
**tf.Tensor(32.0, shape=(), dtype=float32)** 

这里一切都很好,渐变也如预期的那样。然后,我使用自定义渐变来测试这个示例,考虑到我在 clip_by_norm 中设置了这个巨大的阈值,它(根据我的理解)不可能影响渐变

@tf.custom_gradient
def clip_gradients2(y):
    def backward(dy):
        return tf.clip_by_norm(dy, 20000000000000000000000000)
    return y**2, backward

v = tf.Variable(2.0) 
with tf.GradientTape() as t: 
    x=v*v
    
    output = clip_gradients2(x) 


print(t.gradient(output, v))

tf.Tensor(4.0, shape=(), dtype=float32)

但它被减少到 4,所以这在某种程度上产生了影响。这究竟是如何导致更小的梯度的?

【问题讨论】:

  • 您的代码中有一个小错字,在您的custom_gradients2 函数中应该是return y**2。至于行为,我会尽量回答你的。
  • 不错,现在更新了。

标签: python tensorflow gradient differentiation autodiff


【解决方案1】:

在编写自定义渐变时,必须自己定义整个导数计算。如果没有您的自定义渐变,我们有以下导数:

((x**2)**2)dx = (x**4)dx = 4*(x**3) = 32 when x=2

当你覆盖梯度计算时,你只有

(x**2)dx = 2x = 4 when x=2

您需要计算函数中的导数,即:

@tf.custom_gradient
def clip_gradients2(y):
    def backward(dy):
        dy = dy * (2*y)
        return tf.clip_by_norm(dy, 20000000000000000000000000)
    return y**2, backward

获得所需的行为。

【讨论】:

  • 非常感谢。这就是我的原因,我无法弄清楚我的 y**2 的导数消失在哪里 - 这很有意义。干杯!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-14
  • 2018-05-04
  • 2017-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多