From the documentation:
When you launch the graph, variables have to be explicitly
initialized before you can run Ops that use their value. You can
initialize a variable by running its initializer op, restoring the
variable from a save file, or simply running an assign
Op that
assigns a value to the variable. In fact, the variable initializer
op is just an assign
Op that assigns the variable's initial value
to the variable itself.
# Launch the graph in a session.
with tf.Session() as sess:
# Run the variable initializer.
sess.run(w.initializer)
# ...you now can run ops that use the value of 'w'...
The most common initialization pattern is to use the convenience function
global_variables_initializer()
to add an Op to the graph that initializes
all the variables. You then run that Op after launching the graph.
# Add an Op to initialize global variables.
init_op = tf.global_variables_initializer()
# Launch the graph in a session.
with tf.Session() as sess:
# Run the Op that initializes global variables.
sess.run(init_op)
# ...you can now run any Op that uses variable values...
as a result you need to use something like:
import tensorflow as tf
W = tf.Variable(10)
print('W: {0}'.format(W))
sess = tf.Session()
with sess.as_default():
sess.run(W.initializer)
print(W.eval())
FYI In TensorFlow, what is the difference between Session.run() and Tensor.eval()?