【问题标题】:How dy(upstream gradient in Tensorflow) is getting calculated below?下面如何计算 dy(Tensorflow 中的上游梯度)?
【发布时间】:2021-10-02 03:05:43
【问题描述】:

在下面的代码中:

  • dy 被计算为 1。如何计算这个值(数学是什么)?根据 tf.custom_gradient 指南,dy 是梯度上游

  • 为什么最终梯度会乘以 clip_norm 值(0.6)? (这意味着(v * v)的final_gradients被乘以0.6,v * v的梯度是2v,为什么要乘以0.6?)

     @tf.custom_gradient
    
     def clip_gradients(y):
    
       print('y',y)
    
       def backward(dy):
    
         print('dy',dy)
    
         return tf.clip_by_norm(dy, 0.6)
       return y, backward
    
    
     v = tf.Variable(3.0)
    
     with tf.GradientTape() as t:
       output = clip_gradients(v * v)
       print('output',output)
    
     print('Final Gradient is ',t.gradient(output, v))
    

'''

代码输出

y tf.Tensor(9.0, shape=(), dtype=float32)
output tf.Tensor(9.0, shape=(), dtype=float32)
dy tf.Tensor(1.0, shape=(), dtype=float32)
Final Gradient is  tf.Tensor(3.6000001, shape=(), dtype=float32)

【问题讨论】:

  • Why final gradients is getting multiplied by clip_norm value(0.6)? 是什么意思另外,也许answer(虽然是关于 TF1)可以帮助你理解。
  • 已编辑问题,请查看它意味着(v * v)的final_gradients乘以0.6,v * v的梯度为2v,为什么乘以0.6?

标签: python tensorflow gradient


【解决方案1】:

dy 在反向传播开始时被初始化为1.,因为这是恒等函数的导数。通过应用chain rule,我们知道f(g(x))'f'(g(x))*g'(x)。如果f 是恒等函数(f(x) = x),那么前面的表达式就变成了1*g'(x)

您的函数clip_gradients0.6 上的任何渐变值剪切为0.6dy 的初始值为 1.0(如上所述)。

如果我们将链式规则应用于您的示例,我们有:

  • 身份的导数是1.0,然后剪裁为0.6
  • v*v 的导数是2*v

通过应用链式法则,我们得到最终的梯度为0.6*2*v,当v=3时等于3.6

【讨论】:

  • 'dy 在反向传播开始时被初始化为 1,因为这是恒等函数的导数' 这个陈述是否总是成立 - 无论我们在模型参数中给出什么函数?
  • 是的。因为您始终可以应用f(model),其中f 是标识函数,而不会更改最终结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
  • 2019-11-16
  • 2021-09-11
  • 2018-04-13
  • 1970-01-01
  • 2018-06-28
相关资源
最近更新 更多