使用TensorFlow改变梯度

时间:2019-05-15 22:42:29

标签: python tensorflow

我是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

或者至少我不知道如何。

1 个答案:

答案 0 :(得分:0)

我想我找到了一个解决方案:我的目标是计算术语,然后尝试以符号方式对其进行计算,然后求值。但是,再次查看问题后,我意识到对于特定的,我只需要的值,而不是的函数。因此,我可以通过以下方式计算

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()