使用“with tf.Session()"的目的? [英] Purpose of using "with tf.Session()"?

查看:11
本文介绍了使用“with tf.Session()"的目的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在练习名为 concatenate 的 keras 方法.

I am practicing the keras method called concatenate.

在这个例子中使用 with 语句让我想到了这个语句的目的

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

示例代码如下:

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

然后我检查文档:tensorflow并说:

Then I check document from: tensorflow and says that:

会话可能拥有资源,例如 tf.Variable、tf.QueueBase 和 tf.ReaderBase.当不再需要这些资源时,释放这些资源很重要.为此,请在会话上调用 tf.Session.close 方法,或将会话用作上下文管理器.

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!

推荐答案

tf.Session() 启动一个 TensorFlow Graph 对象,其中张量通过操作(或 ops)进行处理.with 块在操作完成后立即终止会话.因此,不需要调用 Session.close.此外,会话包含变量、全局变量、占位符和操作.这些必须在创建会话后启动.因此我们调用 tf.global_variables_initializer().run()

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

这篇关于使用“with tf.Session()"的目的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆