Feeding values to a Variable using feed_dict in TensorFlow

二次信任 提交于 2021-02-10 15:42:58

问题


I'm through https://www.tensorflow.org/get_started/mnist/pros. Reading "Note that you can replace any tensor in your computation graph using feed_dict -- it's not restricted to just placeholders," I tried to give values to a Variable using feed_dict as follows:

print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, 
                           W[:, :]: np.zeros((784, 10))}))

However, it gave the original accuracy 0.9149 (I expected around 0.1). Can I give constant values to Variables after initialization using feed_dict?


回答1:


In your answer you have already passed the constants zeros to W which is a variable. And in the statement that

Note that you can replace any tensor in your computation graph using feed_dict -- it's not restricted to just placeholders

All what you pass into the graph by feed_dict are (often numpy) constants, so you can also get a positive answer.




回答2:


While feeding values to a (non-resource) Variable used to work by accident, it should not work actually. I highly suspect you are using a resource Variable.

What you can do is to use load:

with tf.Session() as sess:
    var1 = tf.get_variable('var1', initializer=5.)  # var1 has value 5.
    sess.run(tf.global_variables_initializer())
    x = var1 ** 2 + 1.
    sess.run(x)  # -> 26 (=5**2 + 1)
    var1.load(value=3., session=sess)  # now var1 has value 3.
    sess.run(x)  # -> 10 (=3**2 + 1)


来源:https://stackoverflow.com/questions/43798599/feeding-values-to-a-variable-using-feed-dict-in-tensorflow

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