Ari Herman
Ari Herman

Reputation: 965

Tensorflow "feed" confusion

I seem to be misunderstanding the way that "feeding" is supposed to work in tensorflow. Here is a very simple example of the issue:

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

So, how do I feed a value to a tensor and get that value to "stick"?

Thanks in advance!

Upvotes: 1

Views: 126

Answers (2)

enterML
enterML

Reputation: 2285

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))

Output:

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

I hope it clarifies the concept

Upvotes: 0

Vladimir Bystricky
Vladimir Bystricky

Reputation: 1330

You should use tf.placeholder instead tf.Value if you want feed network by some external data:

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 

Upvotes: 3

Related Questions