TensorFlow 中三種啟動圖用法
阿新 • • 發佈:2018-12-06
轉自https://blog.csdn.net/lyc_yongcai/article/details/73467480
TensorFlow 中有三種啟動圖的方法:tf.Session(),tf.InteractivesSession(),tf.train.Supervisor().managed_session()
它們各自的用法如下:
(1)tf.Session():構造階段完成後, 才能啟動圖。啟動圖的第一步是建立一個 Session
物件, 如果無任何建立引數, 會話構造器將啟動預設圖。
(2)tf.InteractivesSession():為了便於使用諸如 IPython之類的 Python 互動環境, 可以使用InteractiveSession 代替 Session 類, 使用 Tensor.eval()和 Operation.run()方法代替Session.run(). 這樣可以避免使用一個變數來持有會話。
import tensorflow as tf
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.], [2.]])
preduct = tf.matmul(matrix1, matrix2)
sess_ = tf.InteractiveSession()
tf.global_variables_initializer().run()
print preduct.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()
import tensorflow as tf a = tf.Variable(1) b = tf.Variable(2) c = tf.add(a, b) update = tf.assign(a, c) init = tf.global_variables_initializer() sv = tf.train.Supervisor(logdir="./tmp/", init_op=init) saver = sv.saver with sv.managed_session() as sess: for i in range(1000): update_ = sess.run(update) #print("11111", update) if i % 100 == 0: sv.saver.save(sess, "./tmp/", global_step=i)