我理解,只要我在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?
我只能计算wrt到上下文中显式使用的变量的梯度。例如,以下代码也不计算梯度:
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))发布于 2020-06-01 14:31:05
由于您试图计算\partial loss \over \partial x,所以需要在GradientTape的作用域中执行从x到loss的所有操作,以便它能够监视它们。
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)https://datascience.stackexchange.com/questions/75226
复制相似问题