tensorFlow 三種啟動圖的用法
阿新 • • 發佈:2018-12-05
tf.Session(),tf.InteractivesSession(),tf.train.Supervisor().managed_session() 用法的區別:
- tf.Session()
構造階段完成後, 才能啟動圖. 啟動圖的第一步是建立一個 Session
物件, 如果無任何建立引數, 會話構造器將啟動預設圖.
import tensorflow as tf matrix1 = tf.constant([[3., 3.]]) matrix2= tf.constant([[2.],[2.]]) preduct = tf.matmul(matrix1, matrix2)
#使用 "with" 程式碼塊來自動完成關閉動作 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print sess.run(preduct)
- 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()
- tf.train.Supervisor().managed_session()
(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 matrix1 = tf.constant([[3., 3.]]) matrix2 = tf.constant([[2.], [2.]]) preduct = tf.matmul(matrix1, matrix2) sv = tf.train.Supervisor(logdir=None, init_op=tf.global_variables_initializer()) with sv.managed_session() as sess: print sess.run(preduct)
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)