Understand TensorFlow Session: A Beginner Introduction

By | April 18, 2020

TensorFlow session is an important feature in tensorflow 1.x. What is it and how to use it correctly? In this tutorial, we will discuss these questions for tensorflow beginners.

understand tensorflow session

What is tensorflow session?

You can regard tensorflow session as a runtime environment. In tensorflow session, we should run operations (initialize variables, calculate mathematical expressions) that are defined in tensorflow graph.

For example, We may define some variables and operations in a tensorflow graph.

graph = tf.Graph()
with graph.as_default():
    w1 = tf.Variable(np.array([1,2], dtype = np.float32))
    w2 = tf.Variable(np.array([2,2], dtype = np.float32))
  
    w = tf.multiply(w1, w2)
  
    initialize = tf.global_variables_initializer()

However, these variables and operations have not been assigned any memory resources. If you plan to make variables can store values and calculate operations, you should run tensorflow graph in a session.

How to run a graph in a tensorflow session?

We can use tf.Session() class to create a session. Look at its initialized method:

__init__(
    target='',
    graph=None,
    config=None
)

We can find that if you plan to create a session to run a graph, you should make this graph as a parameter.

Here is an example:

with tf.Session(graph=graph) as sess:
    sess.run(initialize)
    print(sess.run([w]))

In this session sess, we can run graph created above. Run this code, we will get this result:

[array([2., 4.], dtype=float32)]

Meanwhile, different tensorflow session can run the same graph.

For example, we will create two different sessions to run a same graph.

with tf.Session(graph=graph) as sess_1:
    sess_1.run(initialize)
    print(sess_1.run([w]))
    
with tf.Session(graph=graph) as sess_2:
    sess_2.run(initialize)
    print(sess_2.run([w]))

In this python code, we have created two sessions sess_1 and sess_2. They will run a same graph in their environment, however, they are independent.

The results are the same:

[array([2., 4.], dtype=float32)]
[array([2., 4.], dtype=float32)]

If you have created some sessions in a tensorflow application, how about their relation? To understand it, you can read:

Understand The Relations of Multiple Tensorflow Sessions: A Beginner Guide

Leave a Reply