python - tensorflow 中的自定义梯度 - 无法理解此示例

标签 python tensorflow gradient differentiation autodiff

我一直认为我即将了解自定义渐变,但后来我测试了这个示例,但我无法弄清楚发生了什么。我希望有人能引导我了解下面到底发生了什么。我认为这本质上是因为我没有具体理解向后函数中的“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,所以这在某种程度上产生了影响。这究竟是如何导致较小的梯度的?

最佳答案

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

((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

获得所需的行为。

关于python - tensorflow 中的自定义梯度 - 无法理解此示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66139974/

相关文章:

CSS3 径向渐变边缘颜色与周围的最终颜色停止不匹配

html - 如何用一个渐变填充多个 svg 路径?

python - 是否有一个库可以检测代码块的源代码语言?

python - python 中 scipy.signal.medfilt2d 背后的概念

python - keras ValueError : output of generator should be a tuple (x, y, sample_weight) 或 (x, y)。发现:无

python - 如何在 RNN 模型中使用图像集

python - 仅 1 个标量的 Tensorboard 摘要标量错误

ios - 应用渐变时按钮拉伸(stretch)

python - 简单的 Python 正则表达式查找模式

python - Pygame - 赋值前引用的局部变量