相关疑难解决方法(0)

如何在 Tensorflow 2.0 中使用 gradient_override_map?

我正在尝试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)

python tensorflow tensorflow2.0

5
推荐指数
1
解决办法
1072
查看次数

标签 统计

python ×1

tensorflow ×1

tensorflow2.0 ×1