mehrtash
mehrtash

Reputation: 930

How to initialize variables defined in tensorflow function?

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

Upvotes: 5

Views: 17368

Answers (3)

floflo29
floflo29

Reputation: 2341

You should use,

tf.global_variables_initializer()

after starting your Session to initialize variables.

Tensorflow Variable

Upvotes: 0

Ferran Parés
Ferran Parés

Reputation: 636

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.]

Upvotes: 1

lishu luo
lishu luo

Reputation: 116

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

Upvotes: 9

Related Questions