Skip to main content
 首页 » 编程设计

python之在递归循环期间分配给 TensorFlow 变量

2024年09月07日37虾米姐

在 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[step_num-1].assign(x) 行似乎从未实际分配给 predictions。

有人可以向我解释为什么这不起作用,以及我应该做什么吗?谢谢!

请您参考如下方法:

发生这种情况是因为 assign 只是一个 TF 操作,与其他任何操作一样,因此仅在需要时执行。由于 final_prediction 路径上的任何内容都不依赖于赋值操作,并且 predictions 只是一个变量,因此永远不会执行赋值。

我认为最直接的解决方案是更换线路

predictions[step_num-1].assign(x) 

由

x = predictions[step_num-1].assign(x) 

这是有效的,因为 assign 也返回它分配的值。现在,要计算 final_prediction,TF 实际上需要“通过”assign 操作,以便执行分配。

另一种选择是使用 tf.control_dependencies,这是一种在 TF 计算其他操作时“强制”计算特定操作的方法。然而,在这种情况下,它可能有点恶心,因为我们想要强制执行的操作 (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 包装一些东西。我认为这是两者之间更灵活的选择。然而,它带有一些在 the docs 中讨论的注意事项.