简体   繁体   中英

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

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

You should use,

tf.global_variables_initializer()

after starting your Session to initialize variables.

Tensorflow Variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM