In TensorFlow, I want to define a variable inside a function, do some processing and return a value based on some calculations. However, I cannot initialize the variable inside the function. Here is a minimal example of the code:
import tensorflow as tf
def foo():
x = tf.Variable(tf.ones([1]))
y = tf.ones([1])
return x+y
if __name__ == '__main__':
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(foo()))
Running the code yields the following error:
tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value Variable
Before you initialize all variables, the function foo() has not been called at all. So it fails to initialize the variables in foo(). We need to call the function before we run the session.
import tensorflow as tf
def foo():
x=tf.Variable(tf.zeros([1]))
y=tf.ones([1])
return x+y
with tf.Session() as sess:
result=foo()
init=tf.global_variables_initializer()
sess.run(init)
print(sess.run(result))
You are not defining those variables into default tf.Graph
before initializing them.
import tensorflow as tf
def foo():
x = tf.Variable(tf.ones([1]))
y = tf.ones([1])
return x + y
if __name__ == '__main__':
with tf.Graph().as_default():
result = foo()
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(result))
This code defines the variables into the tf.Graph
before intializing them as requested, so you can execute them at your tf.Session
through sess.run()
.
Output:
[2.]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With