我正在将一些 TF1 代码迁移到 TF2。对于完整代码,您可以查看 here 行 [155-176]。 TF1 中有一条线在给定损失(浮点值)和 (m, n) 张量的情况下获得梯度
编辑:问题仍然存在
注意:TF2 代码应该兼容并且应该在 tf.function
g = tf.gradients(-loss, f) # loss being a float and f being a (m, n) tensor
k = -f_pol / (f + eps) # f_pol another (m, n) tensor and eps a float
k_dot_g = tf.reduce_sum(k * g, axis=-1)
adj = tf.maximum(
0.0,
(tf.reduce_sum(k * g, axis=-1) - delta)
/ (tf.reduce_sum(tf.square(k), axis=-1) + eps),
)
g = g - tf.reshape(adj, [nenvs * nsteps, 1]) * k
grads_f = -g / (nenvs * nsteps)
grads_policy = tf.gradients(f, params, grads_f) # params being the model parameters
在 TF2 代码中我正在尝试:
with tf.GradientTape() as tape:
f = calculate_f()
f_pol = calculate_f_pol()
others = do_further_calculations()
loss = calculate_loss()
g = tape.gradient(-loss, f)
但是,无论我使用 g = [None]
还是创建具有 tape.watch(f)
值的 tf.Variable
,甚至在 f
中使用 tf.gradients()
}} 因为否则,它会抱怨。
答案 0 :(得分:1)
很可能是以下情况之一
tf.Variable
修饰的函数中定义 @tf.funtion
吗?