Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 449
mehrtash Avatar asked May 02 '18 15:05

mehrtash


2 Answers

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))
like image 101
lishu luo Avatar answered Nov 18 '22 20:11

lishu luo


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

like image 40
Ferran Parés Avatar answered Nov 18 '22 21:11

Ferran Parés