【问题标题】:GradientTape not computing gradientGradientTape 不计算梯度
【发布时间】:2020-09-19 15:30:12
【问题描述】:

我知道,只要我在 tf.GradientTape() 上下文中定义计算,梯度磁带就会计算计算输出所依赖的所有变量的梯度。但是,我认为我并没有完全掌握渐变的细微之处,因为以下代码没有像我预期的那样执行:

import tensorflow as tf
x = tf.Variable(2.)
loss_ = x**2-2*x+1
with tf.GradientTape(persistent=True) as g:
    loss = loss_*1
print(g.gradient(loss,x))
output: None

为什么不计算梯度 wrt x?

我只能计算与上下文中显式使用的变量相关的梯度。例如下面的代码也不计算梯度:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
x = tf.Variable(2.)
t1 = x**2
t2 = -2*x
t3 = 1.
with tf.GradientTape(persistent=True) as g:
    loss = t1+t2+t3
print(g.gradient(loss,x))

【问题讨论】:

  • 你需要在磁带上下文中计算loss_
  • 但我在上下文中计算loss,我正在计算loss 的梯度而不是loss_ .. ??究竟有什么方法可以做到这一点?
  • 从头到尾的整个计算需要在范围内。范围之外发生的事情不会被追踪。正如您现在的代码一样,磁带知道loss 来自loss_,但它不知道loss_ 来自x,因此无法计算梯度。

标签: tensorflow deep-learning tensorflow2.0 gradienttape


【解决方案1】:

GradientTape 对象 gwith 语句结束后超出范围。

换句话说,尝试在with 语句中打印渐变。

这对我有用:

def get_gradients(inputs, target, model):
    with tf.GradientTape() as tape:
        prediction = model(inputs)
        loss = loss_object(target, prediction)
        gradient = tape.gradient(loss, model.trainable_variables)

    return gradient

【讨论】:

  • 不,它没有。事实上,我收到警告:WARNING:tensorflow:Calling GradientTape.gradient 在其上下文内的持久磁带上的效率明显低于在上下文外调用它(它导致梯度操作被记录在磁带上,从而导致 CPU 和内存使用情况)。如果您确实想要跟踪梯度以计算高阶导数,请仅在上下文中调用 GradientTape.gradient。无
  • 好的,所以我的第二个猜测可能是您的损失定义不正确。也许尝试使用 Keras.backend 操作(以及变量本身)来定义它
  • 同时查看我的示例:colab.research.google.com/drive/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多