zmbq
zmbq

Reputation: 39013

Can't use TensorFlow Variable Twice

I'm trying to get acquainted with TensorFlow, and I'm not sure about placeholders, variables and such. To make things easy, I tried to create a very simple calculation - a placeholder and a variable that is just the placeholder times two.

I've put everything in a function, like so:

import tensorflow as tf

def try_variable(value):
    x = tf.placeholder(tf.float64, name='x')
    v = tf.Variable(x * 2, name='v', validate_shape=False)

    with tf.Session() as session:
        init = tf.global_variables_initializer()
        session.run(init, feed_dict={x: value})
        return session.run(v)

I then call the function:

print(try_variable(80)) 

And indeed the output is 160.

But when I call it again:

print(try_variable(80))

I get an error:

InvalidArgumentError: You must feed a value for placeholder tensor 'x' with dtype double

What am I missing?

Upvotes: 3

Views: 385

Answers (1)

Matan Hugi
Matan Hugi

Reputation: 1130

Right now you're creating a new variable and placeholder each time you call the function, so on the second time you call the try_variable function you actually have 2 placeholders and 2 TensorFlow variables! x, x_1, v, v_1.

So, on the second time you run the init operation, you provide the initial value only for placeholder x_1 which is now binded to python variable x.

If you want to print the name of all the Tensors in the current graph, you can call

print [n.name for n in tf.get_default_graph().as_graph_def().node]

If you still want to create 2 new tensors each time you call the function, one option is to reset the default graph with the command tf.reset_default_graph() each time the function is called - it is highly unrecommended.

Upvotes: 5

Related Questions