python - 为 tf.while_loop 的每个时间步计算梯度

标签 python tensorflow while-loop backpropagation

给定一个 TensorFlow tf.while_loop,我如何计算每个时间步的 x_out 相对于网络所有权重的梯度?

network_input = tf.placeholder(tf.float32, [None])
steps = tf.constant(0.0)

weight_0 = tf.Variable(1.0)
layer_1 = network_input * weight_0

def condition(steps, x):
    return steps <= 5

def loop(steps, x_in):
    weight_1 = tf.Variable(1.0)
    x_out = x_in * weight_1
    steps += 1
    return [steps, x_out]

_, x_final = tf.while_loop(
    condition,
    loop,
    [steps, layer_1]
)

一些笔记

  1. 在我的网络中,条件是动态的。不同的运行将运行 while 循环不同的次数。
  2. 调用 tf.gradients(x, tf.trainable_variables()) 崩溃并出现 AttributeError: 'WhileContext' object has no attribute 'pred'。似乎在循环中使用 tf.gradients 的唯一可能性是计算关于 weight_1 的梯度和 x_in 的当前值/仅时间步长,不通过时间反向传播。
  3. 在每个时间步中,网络将输出 Action 的概率分布。然后需要梯度来实现策略梯度。

最佳答案

在基于this 的 Tensorflow 中,您永远不能在 tf.while_loop 中调用 tf.gradientsthis ,当我尝试将共轭梯度下降完全创建到 Tensorflow 图中时,我发现了这一点。

但是如果我正确理解你的模型,你可以制作你自己的 RNNCell 版本并将其包装在 tf.dynamic_rnn 中,但实际的单元格 实现会有点复杂,因为您需要在运行时动态评估条件。

初学者可以看看Tensorflow的dynamic_rnn代码here .

或者,动态图从来都不是 Tensorflow 的强项,因此请考虑使用其他框架,例如 PyTorch 或者您可以试用 eager_execution看看是否有帮助。

关于python - 为 tf.while_loop 的每个时间步计算梯度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49555016/

相关文章:

c - c中的while循环不会结束

python - pyodbc 删除 unicode 字符串

python - 如何修改sympy的打印顺序?

python - 无法记录使用 Keras 构建但使用 Tensorflow 估计器训练的模型的损失

javascript - 如何在没有唯一 ID/类的情况下淡出功能

mysql - 如何使用 IF NULL,在 MySQL 中执行此操作?

python - 我如何在 python 中多线程 SQL 查询,以便获得所有查询的结果

python - Python 2 中的字符串替换和匹配

tensorflow - 如何在 Keras 中翻转张量?

tensorflow - 当运行 hexagon nnlib 中的独立 graph_app 时,Shell 被卡住