TensorFlow 中三種啓動圖 用法

介紹 TensorFlow 中啓動圖:  tf.Session(),tf.InteractivesSession(),tf.train.Supervisor().managed_session()  用法的區別:


(1)tf.Session()

         構造階段完成後, 才能啓動圖. 啓動圖的第一步是創建一個 Session 對象, 如果無任何創建參數, 會話構造器將啓動默認圖.

具體代碼:

#coding:utf-8

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)

(2)tf.InteractivesSession()

         爲了便於使用諸如 IPython之類的 Python 交互環境, 可以使用InteractiveSession 代替 Session 類, 使用 Tensor.eval() Operation.run()方法代替Session.run(). 這樣可以避免使用一個變量來持有會話。

具體代碼:

#coding:utf-8

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

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)

另外一個栗子:

#coding:utf-8

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)


如何使用 Supervisor() 來啓動圖和保存訓練參數




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章