GradientTape 不计算梯度

数据挖掘 深度学习 张量流
2022-02-15 16:06:09

我知道,只要我在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))
1个回答

由于您正在尝试计算lossx您需要执行所有xloss 在 GradientTape 的范围内,以便它可以监视它们。

x = tf.Variable(2.)

with tf.GradientTape(persistent=True) as g:
    loss_ = x**2-2*x+1
    loss = loss_*1

print(g.gradient(loss,x))
# Will output: tf.Tensor(2.0, shape=(), dtype=float32)