tensorflow-会话(session)

        Tensorflow中的会话是来执行定义好的运算的。会话拥有并管理Tensorflow程序运行时的所有资源。当计算完成之后需要关闭会话来帮助系统回收资源,否则可能出现资源泄露的问题。 Tensorflow中使用会话的模式一般有两种,第一种模式需要明确调用会话生成函数和关闭会话函数,流程如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import tensorflow as tf

matrix1 = tf.constant([[3,3]])
matrix2 = tf.constant([[2],
[2]])

product = tf.matmul(matrix1, matrix2)

# method 1
sess = tf.Session()
result = sess.run(product)
print(result)
sess.close()
# 输出:[[12]]

        使用这种模式时,所有计算完成后,需要明确调用Session.close()函数关闭会话并释放资源。然而当程序因为异常而退出时,关闭会话的函数可能就不会被执行而导致资源泄露。为了解决异常退出导致资源泄露的问题,Tensorflow可以通过Python的上下文管理器来使用会话。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import tensorflow as tf

matrix1 = tf.constant([[3,3]])
matrix2 = tf.constant([[2],
[2]])

product = tf.matmul(matrix1, matrix2)

# method2,sess会自动关闭
with tf.Session() as sess:
result2 = sess.run(product)
print(result)

##

        通过Python的上下文管理器的机制,只要所有的计算放在with的内部就可以。当上下文管理器退出时会自动释放所有资源。

上下文管理器

        在使用Python编程中,可以会经常碰到这种情况:有一个特殊的语句块,在执行这个语句块之前需要先执行一些准备动作;当语句块执行完成后,需要继续执行一些收尾动作。

例如:当需要操作文件或数据库的时候,首先需要获取文件句柄或者数据库连接对象,当执行完相应的操作后,需要执行释放文件句柄或者关闭数据库连接的动作。

又如,当多线程程序需要访问临界资源的时候,线程首先需要获取互斥锁,当执行完成并准备退出临界区的时候,需要释放互斥锁。

​ 对于这些情况,Python中提供了上下文管理器(Context Manager)的概念,可以通过上下文管理器来定义/控制代码块执行前的准备动作,以及执行后的收尾动作。

上下文管理协议

        那么在Python中怎么实现一个上下文管理器呢?这里,又要提到两个”魔术方法”__enter__和__exit__,下面就是关于这两个方法的具体介绍。

  • enter(self) Defines what the context manager should do at the beginning of the block created by the with statement. Note that the return value of enter is bound to the target of the with statement, or the name after the as.

  • exit(self, exception_type, exception_value, traceback) Defines what the context manager should do after its block has been executed (or terminates). It can be used to handle exceptions, perform cleanup, or do something always done immediately after the action in the block. If the block executes successfully, exception_type, exception_value, and traceback will be None. Otherwise, you can choose to handle the exception or let the user handle it; if you want to handle it, make sure exit returns True after all is said and done. If you don’t want the exception to be handled by the context manager, just let it happen.

            也就是说,当我们需要创建一个上下文管理器类型的时候,就需要实现enterexit方法,这对方法就称为上下文管理协议(Context Manager Protocol),定义了一种运行时上下文环境。

with语句

        在Python中,可以通过with语句来方便的使用上下文管理器,with语句可以在代码块运行前进入一个运行时上下文(执行__enter__方法),并在代码块结束后退出该上下文(执行__exit__方法)。

with语句的语法如下:

1
2
with context_expr [as var]:
with_suite
  • context_expr是支持上下文管理协议的对象,也就是上下文管理器对象,负责维护上下文环境
  • as var是一个可选部分,通过变量方式保存上下文管理器对象
  • with_suite就是需要放在上下文环境中执行的语句块

        在Python的内置类型中,很多类型都是支持上下文管理协议的,例如file,thread.LockType,threading.Lock等等。这里我们就以file类型为例,看看with语句的使用。

with语句简化文件操作

        当需要写一个文件的时候,一般都会通过下面的方式。代码中使用了try-finally语句块,即使出现异常,也能保证关闭文件句柄。

1
2
3
4
5
6
7
8
logger = open("log.txt", "w")
try:
logger.write('Hello ')
logger.write('World')
finally:
logger.close()

print logger.closed

        其实,Python的内置file类型是支持上下文管理协议的,可以直接通过内建函数dir()来查看file支持的方法和属性:

1
2
3
4
5
6
7
8
>>> print dir(file)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '
__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclass
hook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', '
mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines',
'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']
>>>

        所以,可以通过with语句来简化上面的代码,代码的效果是一样的,但是使用with语句的代码更加的简洁:

1
2
3
4
5
with open("log.txt", "w") as logger:
logger.write('Hello ')
logger.write('World')

print logger.closed

参考:

https://www.cnblogs.com/wilber2013/p/4638967.html

https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/

本文标题:tensorflow-会话(session)

文章作者:goingcoder

发布时间:2018年04月04日 - 16:04

最后更新:2018年04月04日 - 17:04

原始链接:https://goingcoder.github.io/2018/04/04/tf2/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------本文结束感谢您的阅读-------------