在Tensorflow 1.9中,我希望创建一个网络,然后递归地将网络的输出(预测)反馈到网络的输入中。在这个循环中,我希望将网络所做的预测存储在一个列表中。
以下是我的尝试:
# Define the number of steps over which to loop the network
num_steps = 5
# Define the network weights
weights_1 = np.random.uniform(0, 1, [1, 10]).astype(np.float32)
weights_2 = np.random.uniform(0, 1, [10, 1]).astype(np.float32)
# Create a variable to store the predictions, one for each loop
predictions = tf.Variable(np.zeros([num_steps, 1]), dtype=np.float32)
# Define the initial prediction to feed into the loop
initial_prediction = np.array([[0.1]], dtype=np.float32)
x = initial_prediction
# Loop through the predictions
for step_num in range(num_steps):
x = tf.matmul(x, weights_1)
x = tf.matmul(x, weights_2)
predictions[step_num-1].assign(x)
# Define the final prediction
final_prediction = x
# Start a session
sess = tf.Session()
sess.run(tf.global_variables_initializer())
# Make the predictions
last_pred, all_preds = sess.run([final_prediction, predictions])
print(last_pred)
print(all_preds)
这个打印出来:
[[48.8769]]
[[0.]
[0.]
[0.]
[0.]
[0.]]
因此,虽然final_prediction
的值看起来是正确的,但predictions
的值并不如我所期望的那样。predictions
似乎从来没有被实际分配给,尽管行predictions[step_num-1].assign(x)
。
请有人给我解释一下为什么这不管用,我该做什么呢?谢谢!
发布于 2018-08-20 13:14:09
之所以会发生这种情况,是因为assign
ist和其他任何TF一样只是一个TF op,因此只有在需要时才会执行。由于到final_prediction
的路径上没有任何东西依赖于赋值op,而且predictions
只是一个变量,所以分配永远不会执行。
我认为最直截了当的解决办法是替换这条线路
predictions[step_num-1].assign(x)
通过
x = predictions[step_num-1].assign(x)
这是因为assign
还返回它正在赋值的值。现在,要计算final_prediction
TF,实际上需要“通过”assign
操作,因此应该执行任务。
另一种选择是使用tf.control_dependencies
,这是一种在计算其他操作时“强迫”TF计算特定操作的方法。但是,在这种情况下,它可能有点不舒服,因为我们要强制的op (assign
)取决于循环中正在计算的值,而且我不确定TF在这种情况下执行操作的顺序。下列措施应能发挥作用:
for step_num in range(num_steps):
x = tf.matmul(x, weights_1)
x = tf.matmul(x, weights_2)
with tf.control_dependencies([predictions[step_num-1].assign(x)]):
x = tf.identity(x)
我们使用tf.identity
作为noop,只是为了用control_dependencies
包装一些东西。我认为这是两者之间比较灵活的选择。然而,它附带了在医生们中讨论的一些注意事项。
https://stackoverflow.com/questions/51937445
复制相似问题