tensorflow: how to assign an updated numpy

泄露秘密 提交于 2020-03-04 04:21:26

问题


I'm new in tensorflow and I'm trying to understand its behaviors; I'm trying to define all the operations outside the session scope so to optimize the computation time. In the following code:

import tensorflow as tf
import numpy as np  
Z_tensor = tf.Variable(np.float32( np.zeros((1, 10)) ), name="Z_tensor")
Z_np = np.zeros((1,10))
update_Z = tf.assign(Z_tensor, Z_np)

Z_np[0][2:4] = 4

with tf.Session() as sess:
    sess.run(Z_tensor.initializer)
    print(Z_tensor.eval())
    print(update_Z.eval(session=sess))

I obtain as ouput:

[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]

Instead I expected as output:

[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
[[0. 0. 4. 4. 0. 0. 0. 0. 0. 0.]]

It seems that the Z_np array is not updated in the assign operation and I don't understand why. Doesn't the operation

  update_Z = tf.assign(Z_tensor, Z_np)

make a link with Z_np?


回答1:


When you use tf.assign, it expects a tensor as the second argument. Because you provided a Numpy array, it automatically promotes it to a CONSTANT tensor and places it in the graph at that moment. Because of this, no changes you make to the Numpy array will have any effect on the TensorFlow graph. In order to get the desired functionality, you should use a placeholder:

Z_placeholder = tf.placeholder(tf.float32, Z_np.shape)

with tf.Session() as sess:
    sess.run(Z_tensor.initializer)
    print(Z_tensor.eval(feed_dict={Z_placeholder: Z_np}, session=sess))
    Z_np[0][2:4] = 4
    print(Z_tensor.eval(feed_dict={Z_placeholder: Z_np}, session=sess))


来源:https://stackoverflow.com/questions/53141762/tensorflow-how-to-assign-an-updated-numpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!