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