Purpose of using "with tf.Session()"?

Pro_gram_mer picture Pro_gram_mer · Dec 21, 2018 · Viewed 19.6k times · Source

I am practicing the keras method called concatenate.

And use of with statement in this example kind of got me thinking the purpose of this statement

The example code looks like:

import numpy as np 
import keras.backend as K
import tensorflow as tf

t1 = K.variable(np.array([ [[1, 2], [2, 3]], [[4, 4], [5, 3]]]))
t2 = K.variable(np.array([[[7, 4], [8, 4]], [[2, 10], [15, 11]]]))

d0 = K.concatenate([t1 , t2] , axis=-2)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    print(sess.run(d0))

Then I check document from: tensorflow and says that:

A session may own resources, such as tf.Variable, tf.QueueBase, and tf.ReaderBase. It is important to release these resources when they are no longer required. To do this, either invoke the tf.Session.close method on the session, or use the session as a context manager.

Which I believe has already explained all of it,but can somebody give me more intuitive explanation.

Thanks in advance and have a nice day!

Answer

user9477964 picture user9477964 · Dec 21, 2018

tf.Session() initiates a TensorFlow Graph object in which tensors are processed through operations (or ops). The with block terminates the session as soon as the operations are completed. Hence, there is no need for calling Session.close. Also, a session contains variables, global variables, placeholders, and ops. These have to be initiated once the session is created. Hence we call tf.global_variables_initializer().run()

A graph contains tensors and operations. To initiate a graph, a session is created which runs the graph. In other words, graph provides a schema whereas a session processes a graph to compute values( tensors ).