我理解,只要我在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 11:06:48
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 gradienthttps://stackoverflow.com/questions/62130393
复制相似问题