我是 TensorFlow 新手,我在以下方面遇到了一些困难:给定 和 ,我想计算 .
我了解如何在没有平移的情况下计算梯度,以及如何对有平移的梯度进行数值计算,但我不知道如何计算 象征性地。
import tensorflow as tf
x = tf.placeholder(tf.float32)
f = (x + 1.0)**2
s = tf.constant(1.0, tf.float32)
# Gradient of f(.)
grad_f = tf.gradients(f, x)[0]
# Gradient of f(. + s)
grad_f_shifted = ?
请注意,我不知道 的定义,所以我不能简单地定义
f_shifted = (x + s + 1.0)**2
或者至少我不知道如何。
最佳答案
我想我找到了一个解决方案:我的目标是计算术语 ,我尝试以符号方式计算它,然后评估 。然而,再次查看我的问题后,我意识到我只需要 的值。对于特定的而不是 的函数。因此,我可以计算通过以下方式:
x = tf.Variable(0.0, tf.float32)
f = (x + 1.0)**2.0
grad_f = tf.gradients(f, x)[0]
y = tf.Variable(0.0, tf.float32)
x0 = tf.constant(1.0, tf.float32)
s = tf.constant(1.0, tf.float32)
tensors = []
tensors.append(tf.assign(x, x0))
tensors.append(tf.assign(y, -grad_f))
tensors.append(tf.assign(x, x0 + s))
# Coming from a numerical background, the line below confused me a bit,
# because the dependency of grad_f on x is not "visible" in the code.
tensors.append(tf.assign_add(y, grad_f))
with tf.Session():
for t in tensors:
t.eval()
关于python - 使用 TensorFlow 移动梯度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56158563/