Purpose of using “with tf.Session()”?

删除回忆录丶 提交于 2020-12-29 12:23:53

问题


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!


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/53885356/purpose-of-using-with-tf-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!