When global_variables_initializer() is actually required

Viewed 25668
import tensorflow as tf
x = tf.constant(35, name='x')
y = tf.Variable(x + 5, name='y')
# model = tf.global_variables_initializer()
with tf.Session() as session:
        print("x = ", session.run(x)) 
        # session.run(model)
        print("y = ", session.run(y))

I was not able to understand when global_variables_initializer() is actually required. In the above code, if we uncomment lines 4 & 7, I can execute the code and see the values. If I run as-is, I see a crash.

My question is which variables it is initializing. x is a constant which does not need initialization and y is variable which is not being initialized but is used as an arithmetic operation.

4 Answers

The tf.global_variables_initializer just initializes all variables that tf.global_variables() would list. This actually makes much sense in a distributed environment where the graph might be located in different computing nodes in a cluster.

In such a case, tf.global_variables_initializer() which is just an alias for tf.variables_initializer(tf.global_variables()) would initialize all the variables in all the computing nodes, where the graph is placed.

Related