-1

我知道,只要我在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))
4

1 回答 1

0

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

换句话说,尝试在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
于 2020-06-01T11:06:48.557 回答