python - 使用 TensorFlow 移动梯度

标签 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

或者至少我不知道如何。

最佳答案

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

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/

相关文章:

python - 使用 Keras 编程多输入神经网络架构

python - Keras中model.compile()和model.add_loss()中loss的区别

python - keras的binary_crossentropy损失函数范围

python - 如何使用 Urllib2 更有效地抓取?

python - 正则表达式从字符串中过滤版本

python - 将变量传递给自定义 Django 模板标签

tensorflow - 有谁知道我们如何更改 DNNClassifier tensorflow 预制估计器中的损失函数?

performance - 训练某些网络时,Keras(Tensorflow 后端)在 GPU 上比在 CPU 上慢

python - 如何使用 Python 从 Twilio 获取超过 1000 条消息记录

python - Pandas:解析 CSV,区分缺失值哨兵和恰好等于它的字符串