Tensorflow" feed"混乱

时间:2017-07-26 04:19:33

标签: tensorflow

我似乎误解了"喂养"应该在tensorflow中工作。这是一个非常简单的问题示例:

import tensorflow as tf
X = tf.Variable(0.0,dtype=tf.float32)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(X))
# prints 0.0 as expected
sess.run(X,feed_dict={X:1.0})
print(sess.run(X))
# prints 0.0 again, but expected to see 1.0

那么,我如何将一个值提供给张量并将该值传递给"坚持"?

提前致谢!

2 个答案:

答案 0 :(得分:3)

如果您希望通过某些外部数据提供Feed网络,则应使用tf.placeholder代替tf.Value

import tensorflow as tf
X = tf.Variable(0.0,dtype=tf.float32)

sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(X))
# prints 0.0 as expected

Y = tf.placeholder(dtype=tf.float32, shape=(1))
print(sess.run(Y,feed_dict={Y : [1.0]}))
# prints [1.0] 

print(sess.run(Y))
# ERROR. Needs feed_dict 

答案 1 :(得分:0)

import tensorflow as tf

y = tf.Variable(0.0, name='y')
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    print("Initial value : ", sess.run(y))
    print("Feeding values using dict :" ,sess.run(y, feed_dict={y:1.0}))
    print("Final value : ",sess.run(y))
    t = tf.assign(y,10)
    print("Assigned new value to the variable using assign method: ", t.eval())
    print("Final value : ", sess.run(y))

输出:

Initial value :  0.0
Feeding values using dict : 1.0
Final value :  0.0
Assigned new value to the variable using assign method:  10.0
Final value :  10.0

我希望它澄清了这个概念