Pro_gram_mer
Pro_gram_mer

Reputation: 817

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

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!

Upvotes: 18

Views: 39398

Answers (2)

Leander
Leander

Reputation: 568

The tensorflow documentation is very specific about this.

Since a tf.Session owns physical resources (such as GPUs and network connections), it is typically used as a context manager (in a with block) that automatically closes the session when you exit the block.

It is also possible to create a session without using a with block, but you should explicitly call tf.Session.close when you are finished with it to free the resources.

Upvotes: 7

user9477964
user9477964

Reputation:

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 ).

Upvotes: 18

Related Questions