Learn Tensorflow by Examples Series - Part 2

Tensorflow Sessions


You need to create a session in order to compute a graph. A session provides a kind of environment for holding variable values and intermediate results, and computing graph nodes. Computation resources are only allocated within a session.
There are couple of ways of creating a session.

Using tf.Session()

# Create session
sess = tf.Session()

# Initialize variables
sess.run(x.initializer)
sess.run(y.initializer)

# Evaluate result
result = sess.run(f)
print(result)
Full code

Using a 'with' operator

with tf.Session() as sess:
    x.initializer.run()
    y.initializer.run()
    result = f.eval()

print(result)
Full code

Using interactive session

'''
Tensorflow can also be run in interactive mode,
which sets the default global session.
'''

sess = tf.InteractiveSession()

init.run()
result = f.eval()
print(result)

# Note that you're required to close the session in interactive mode
sess.close()
Full code
Interactive sessions are less common and are generally used for quick experiments.