如何在每个时间步中针对网络的所有权重计算x_out
的梯度,给定一个TensorFlow中的tf.while_loop
?
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
的可能性是仅根据当前的x_in
值 / 时间步长计算相对于weight_1
的梯度,而不是在时间上反向传播。 - 在每个时间步骤中,网络将输出一个关于动作的概率分布。然后需要梯度来实现策略梯度。
x_out
感兴趣而不是x_final
吗? - bentf.while_loop
迭代中创建一个新变量?这在TensorFlow中是不可能的。根据你当前的代码,你只创建了两个变量,一个用于layer_1
,另一个用于每个循环迭代。 - jdehesax_out
相对于weight_0
和weight_1
的梯度。 - Geniusweight_1 = tf.Variable(1.0)
呢?你的意图是实际上想使用tf.get_variable
吗? - ldavid