我正在尝试gradient_override_map与 Tensorflow 2.0一起使用。文档中有一个示例,我也将在此处用作示例。
在 2.0 中,GradientTape可用于计算梯度如下:
import tensorflow as tf
print(tf.version.VERSION) # 2.0.0-alpha0
x = tf.Variable(5.0)
with tf.GradientTape() as tape:
s_1 = tf.square(x)
print(tape.gradient(s_1, x))
Run Code Online (Sandbox Code Playgroud)
还有tf.custom_gradient装饰器,可用于定义新函数的渐变(再次使用文档中的示例):
import tensorflow as tf
print(tf.version.VERSION) # 2.0.0-alpha
@tf.custom_gradient
def log1pexp(x):
e = tf.exp(x)
def grad(dy):
return dy * (1 - 1 / (1 + e))
return tf.math.log(1 + e), grad
x = tf.Variable(100.)
with tf.GradientTape() as tape:
y …Run Code Online (Sandbox Code Playgroud)