带张量的移位梯度

2024-06-28 16:21:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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

或者至少我不知道怎么做。你知道吗


Tags: ofimport定义tftensorflow情况梯度移位
1条回答
网友
1楼 · 发布于 2024-06-28 16:21:03

我想我找到了一个解决方案:我的目标是计算术语,我试着用符号计算它,然后计算。然而,在再次研究我的问题之后,我意识到我只需要一个特定的的值,而不是作为的函数。因此,我可以通过以下方式计算

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

相关问题 更多 >