【发布时间】:2018-09-08 08:23:09
【问题描述】:
给定一个 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]
)
一些笔记
- 在我的网络中,条件是动态的。不同的运行将运行 while 循环不同的次数。
- 调用
tf.gradients(x, tf.trainable_variables())与AttributeError: 'WhileContext' object has no attribute 'pred'崩溃。似乎在循环中使用tf.gradients的唯一可能性是计算相对于weight_1的梯度和x_in的当前值/时间步长,而无需通过时间反向传播。 - 在每个时间步,网络将输出动作的概率分布。然后需要梯度来实现策略梯度。
【问题讨论】:
-
你确定你对
x_out感兴趣而不是x_final吗? -
是的,网络是像image captioning这样的自注册模型。网络在每个时间步输出动作的概率分布,直到它决定“完成”。我需要每个输出(动作)的梯度,而不仅仅是最后一个。
-
您是否尝试在每次
tf.while_loop迭代中创建一个新变量? TensorFlow 无法做到这一点。使用您当前的代码,您只创建了两个变量,一个用于layer_1,另一个用于每次循环迭代。 -
不,我不想在每次迭代中都创建新变量。我只是想通过时间反向传播:计算每个时间步的
x_out相对于weight_0和weight_1的梯度。 -
那么你为什么要在循环内声明
weight_1 = tf.Variable(1.0)?你真的打算tf.get_variable吗?
标签: python tensorflow while-loop backpropagation