TensorFlow 中三种启动图 用法

来源:互联网 发布:王家卫句式知乎 编辑:程序博客网 时间:2024/06/10 23:29

介绍 TensorFlow 中启动图:  tf.Session(),tf.InteractivesSession(),tf.train.Supervisor().managed_session()  用法的区别:


(1)tf.Session()

         构造阶段完成后, 才能启动图. 启动图的第一步是创建一个 Session 对象, 如果无任何创建参数, 会话构造器将启动默认图.

具体代码:

[python] view plain copy
print?
  1. #coding:utf-8  
  2.   
  3. import tensorflow as tf  
  4.   
  5. matrix1 = tf.constant([[3.3.]])  
  6. matrix2 = tf.constant([[2.], [2.]])  
  7.   
  8. preduct = tf.matmul(matrix1, matrix2)  
  9. # 使用 "with" 代码块来自动完成关闭动作.  
  10. with tf.Session() as sess:  
  11.     sess.run(tf.global_variables_initializer())  
  12.     print sess.run(preduct)  

(2)tf.InteractivesSession()

         为了便于使用诸如 IPython之类的 Python 交互环境, 可以使用InteractiveSession 代替 Session 类, 使用 Tensor.eval() Operation.run()方法代替Session.run(). 这样可以避免使用一个变量来持有会话。

具体代码:

[python] view plain copy
print?
  1. #coding:utf-8  
  2.   
  3. import tensorflow as tf  
  4.   
  5. matrix1 = tf.constant([[3.3.]])  
  6. matrix2 = tf.constant([[2.], [2.]])  
  7.   
  8. preduct = tf.matmul(matrix1, matrix2)  
  9.   
  10. sess_ = tf.InteractiveSession()  
  11.   
  12. tf.global_variables_initializer().run()  
  13. print preduct.eval()  
  14.   
  15. 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()


具体代码:

[python] view plain copy
print?
  1. import tensorflow as tf  
  2.   
  3. matrix1 = tf.constant([[3.3.]])  
  4. matrix2 = tf.constant([[2.], [2.]])  
  5.   
  6. preduct = tf.matmul(matrix1, matrix2)  
  7.   
  8. sv = tf.train.Supervisor(logdir=None, init_op=tf.global_variables_initializer())  
  9.   
  10. with sv.managed_session() as sess:  
  11.     print sess.run(preduct)  

另外一个栗子:

[python] view plain copy
print?
  1. #coding:utf-8  
  2.   
  3. import tensorflow as tf  
  4.   
  5. a = tf.Variable(1)  
  6. b = tf.Variable(2)  
  7. c = tf.add(a, b)  
  8.   
  9. update = tf.assign(a, c)  
  10.   
  11. init = tf.global_variables_initializer()  
  12.   
  13. sv = tf.train.Supervisor(logdir="./tmp/", init_op=init)  
  14. saver = sv.saver  
  15. with sv.managed_session() as sess:  
  16.     for i in range(1000):  
  17.         update_ = sess.run(update)  
  18.         #print("11111", update)  
  19.   
  20.         if i % 100 == 0:  
  21.             sv.saver.save(sess, "./tmp/", global_step=i)  


如何使用 Supervisor() 来启动图和保存训练参数