python - 急切执行: gradient computation

标签 python tensorflow

我想知道为什么这个非常简单的梯度计算无法正常工作。它实际上是生成一个[None, None]向量。显然,这不是所需的输出。

import tensorflow as tf
tf.enable_eager_execution()

a = tf.constant(0.)
with tf.GradientTape() as tape:
    b = 2 * a
da, db = tape.gradient(a + b, [a, b])
print(da)
print(db)

预期输出: da = 3 且 db = 1

最佳答案

您发布的代码片段有两个小问题:

  1. a + b 计算发生在磁带上下文之外,因此不会被记录。请注意,GradientTape 只能区分记录的计算。在磁带上下文中计算 a + b 将解决这个问题。

  2. 需要“监视”源张量。有两种方法可以向磁带发出应该监视张量的信号: (a) 显式调用 tape.watch ,或 (b) 使用 tf.Variable (监视所有变量),请参阅 documentation

长话短说,对代码片段进行两个简单的修改就可以解决问题:

import tensorflow as tf
tf.enable_eager_execution()

a = tf.constant(0.)
with tf.GradientTape() as tape:
    tape.watch(a)
    b = 2 * a
    c = a + b
da, db = tape.gradient(c, [a, b])
print(da)
print(db)

希望有帮助。

关于python - 急切执行: gradient computation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52340645/

相关文章:

python - 如何跟踪 csr 矩阵

Tensorflow 1.0 Windows + 64 位 Anaconda 4.3.0 错误

python - 索引错误 : list index out of range in TensorFlow

python - 使用 tf.io.decode_jpeg 导入后出现 TypeError : Image data cannot be converted to float with plt. imshow

python-3.x - 在 tensorflow 中获取批处理

python - 向 Keras 模型添加图层后无法导入卡住图

python - 使用 cython 和 C++ 访问结构中的 vector 的奇怪错误

Python - 如何在不使用 numpy 的情况下获取矩阵的上三角之和?

python - 命令行中的Python无法切换

python - 如何在 Tkinter 中使用 Canvas 绘制点?