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