使用 tf.function 时缺少渐变
Missing gradient when using tf.function
我发现如果我想在 tensorflow 2 中使用 tf.gradients
而不是渐变带,我可以通过将代码包装在 tf.function
装饰函数中来实现。但不知何故,我不能以这种方式获取关于变量的梯度:
import tensorflow as tf
a = tf.Variable(initial_value=1.0, dtype=tf.float32)
b = 0.01 * a
@tf.function
def get_grads():
return tf.gradients(b, a)[0]
print(get_grads())
我希望得到某种张量,一个应该评估为 0.01 的张量。但是我得到 None
。请注意,我在 Google Colab 上 运行 this,因此 tensorflow 版本或安装应该没有任何问题。
我做错了什么?
op b = 0.01 * a
是由 tf.function
装饰函数创建的图形。
您可以使用:
a = tf.Variable(initial_value=1.0, dtype=tf.float32)
@tf.function
def get_grads():
b = 0.01 * a
return tf.gradients(b, a)
print(get_grads())
我发现如果我想在 tensorflow 2 中使用 tf.gradients
而不是渐变带,我可以通过将代码包装在 tf.function
装饰函数中来实现。但不知何故,我不能以这种方式获取关于变量的梯度:
import tensorflow as tf
a = tf.Variable(initial_value=1.0, dtype=tf.float32)
b = 0.01 * a
@tf.function
def get_grads():
return tf.gradients(b, a)[0]
print(get_grads())
我希望得到某种张量,一个应该评估为 0.01 的张量。但是我得到 None
。请注意,我在 Google Colab 上 运行 this,因此 tensorflow 版本或安装应该没有任何问题。
我做错了什么?
op b = 0.01 * a
是由 tf.function
装饰函数创建的图形。
您可以使用:
a = tf.Variable(initial_value=1.0, dtype=tf.float32)
@tf.function
def get_grads():
b = 0.01 * a
return tf.gradients(b, a)
print(get_grads())