简体   繁体   English

目的是使用“ with tf.Session()”?

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

I am practicing the keras method called concatenate. 我正在练习称为串联的keras方法。

And use of with statement in this example kind of got me thinking the purpose of this statement 在此示例中使用with语句让我思考了该语句的目的

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: 然后我检查来自tensorflow的文档,并说:

A session may own resources, such as tf.Variable, tf.QueueBase, and tf.ReaderBase. 会话可能拥有资源,例如tf.Variable,tf.QueueBase和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. 为此,请在会话上调用tf.Session.close方法,或将该会话用作上下文管理器。

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! 在此先感谢您,祝您愉快!

tf.Session() initiates a TensorFlow Graph object in which tensors are processed through operations (or ops). tf.Session()启动一个TensorFlow Graph对象,在其中通过操作(或操作)处理张量。 The with block terminates the session as soon as the operations are completed. 操作完成后, with块将终止会话。 Hence, there is no need for calling Session.close . 因此,无需调用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() 因此,我们将其称为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 ). 换句话说,图提供了一个模式,而会话则处理一个图以计算值(张量)。

The tensorflow documentation is very specific about this. tensorflow 文档对此非常具体。

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. 由于tf.Session拥有物理资源(例如GPU和网络连接),因此通常用作上下文管理器(在with块中),当您退出该块时,它将自动关闭会话。

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. 也可以在不使用with块的情况下创建会话,但是完成会话后应显式调用tf.Session.close以释放资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM