tensorflow会话-Session(), Session().as_fault() 与InteractiveSession()

在学习tensorflow过程中关于一些会话的语句不是很理解,抽空把三种主要的会话Session(), Session().as_fault(), InteractiveSession()整理下:

1.Session()

对于TF中执行会话中的语句时,需要指定是哪个会话中的函数(可能在一些项目中会生成很多个会话)。通过tf.Session()生成会话。举个简单的例子。

1 import tensorflow as tf
2 a = tf.constant(3, tf.float32)
3 b = tf.constant(4, tf.float32)
4 c = a+b
5 sess1 = tf.Session()
6 print(sess1.run(c))
7 print(a.eval(session = sess1))

在调用函数run,及eval需要指定是会话中的函数。或者也可以控制在sess1的一个内循环中,也可写成如下语句

1 import tensorflow as tf
2 a = tf.constant(3, tf.float32)
3 b = tf.constant(4, tf.float32)
4 c = a+b
5 with tf.Session() as sess1:
6     print(sess1.run(c))
7     print(a.eval())

这种方式eval会默认调用sess1中的函数,(由于run函数是tf.Session()类中的函数,因此这里run前的sess1不可去掉)

2.Session().as_fault()

  •  tf.Session()创建一个会话,当上下文管理器退出时会话关闭和资源释放自动完成。比如:
import tensorflow as tf
a = tf.constant(3, tf.float32)
b = tf.constant(4, tf.float32)
c = a+b
with tf.Session() as sess1:
    print(sess1.run(c))
print(a.eval(session = sess1))

在执行语句print(a.eval(session = sess1))时, 由于上下文管理器已经退出,会话已经关闭,因此会报错。

  •  tf.Session().as_default()创建一个默认会话,当上下文管理器退出时会话没有关闭,还可以通过调用会话进行run()和eval()操作
    import tensorflow as tf
    a = tf.constant(3, tf.float32)
    b = tf.constant(4, tf.float32)
    c = a+b
    with tf.Session().as_default()  as sess1:
        print(sess1.run(c))
    print(a.eval(session = sess1))

 tf.Session().as_default()虽然上下文管理器已经退出,但是会话没有关闭,后面的函数还是可以调用该会话中的函数。

3.IntersectiveSession()

tf.InteractiveSession()是一种交替式的会话方式,它让自己成为了默认的会话,也就是说用户在单一会话的情境下,不需要指明用哪个会话也不需要更改会话运行的情况下,就可以运行起来,这就是默认的好处。这样的话就是run和eval()函数可以不指明session啦

1 import tensorflow as tf
2 a = tf.constant(3, tf.float32)
3 b = tf.constant(4, tf.float32)
4 c = a+b
5 sess = tf.InteractiveSession()
6 print(a.eval())

简单来说InteractiveSession()等价于:

sess=tf.Session()
with sess.as_default():
原文地址:https://www.cnblogs.com/kuangsyx/p/9743477.html