简体   繁体   English

使用TensorFlow改变梯度

[英]Shifted gradient with TensorFlow

I am new to TensorFlow, and I am struggling a bit with the following: Given 我是TensorFlow的新手,但我在以下方面苦苦挣扎: and , I would like to compute ,我想计算 .

I understand how to compute the gradient without the shift, and how I can numerically evaluate the gradient with the shift, but I do not see how to compute 我了解如何在不发生偏移的情况下计算梯度,以及如何通过偏移在数值上评估梯度,但是我看不到如何计算 symbolically. 象征性地。

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 = ?

Note that I do not know the definition of 请注意,我不知道 , so I cannot simply define ,所以我不能简单地定义

f_shifted = (x + s + 1.0)**2

or at least I do not know how. 或者至少我不知道如何。

I think I found a solution: My goal was to compute the term 我想我找到了一个解决方案:我的目标是计算条件 , and I tried to compute it symbolically and then evaluate ,我尝试进行符号计算,然后求值 . However, after looking at my problem again, I realized that I only need the value of 但是,再次看完我的问题后,我意识到我只需要 for a specific 对于特定 and not as a function of 而不是作为 . Hence, I can compute 因此,我可以计算 in the following way: 通过以下方式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM