(1)tf.Session()
计算图构造完成后, 才能启动图. 启动图的第一步是创建一个 Session 对象。
示例程序:
#coding:utf-8
import tensorflow as tf
#构造图
a = tf.constant(4)
b = tf.constant(5)
c = a+b
#启动图
with tf.Session() as sess:
print(sess.run(c))
(2)tf.InteractivesSession()
为了便于使用诸如 IPython之类的 Python 交互环境, 可以使用InteractiveSession 代替 Session 类, 使用 Tensor.eval()和 Operation.run()方法代替Session.run(). 这样可以避免使用一个变量来持有会话。
# coding:utf-8
import tensorflow as tf
a = tf.constant(4)
b = tf.constant(5)
c = a + b
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
print(c.eval() )
sess.close()
(3)tf.train.Supervisor().managed_session()
与上面两种启动图相比较来说,Supervisor() 帮助我们处理一些事情:
(a) 自动去 checkpoint 加载数据或者初始化数据
(b) 自动有一个 Saver ,可以用来保存 checkpoint
eg: sv.saver.save(sess, save_path)
(c) 有一个 summary_computed 用来保存 Summary
因此我们可以省略了以下内容:
(a)手动初始化或者从 checkpoint 中加载数据
(b)不需要创建 Saver 类, 使用 sv 内部的就可以
(c)不需要创建 Summary_Writer()
# coding:utf-8
import tensorflow as tf
a = tf.constant(4)
b = tf.constant(5)
c = a + b
sup_sess = tf.train.Supervisor(logdir=None, init_op=tf.global_variables_initializer())
with sup_sess.managed_session() as sess:
print(sess.run(c))