【发布时间】: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