TensorFlow學習筆記(一)--Session會話控制
阿新 • • 發佈:2019-02-20
在構造階段完成以後,我們需要啟動圖,啟動圖的第一步是創建一個Session
物件,如果建立的時候沒有任何物件的話,Session構造器將會啟動預設圖,即函式中沒有傳入引數,表明該程式碼將
會依附於(如果還沒有建立會話,則會建立新的會話)預設的本地會話。
import tensorflow as tf # 建立一個常量 op, 產生一個 1x2 矩陣. 這個 op 被作為一個節點 # 加到預設圖中. # # 構造器的返回值代表該常量 op 的返回值. matrix1 = tf.constant([[3., 3.]]) # 建立另外一個常量 op, 產生一個 2x1 矩陣. matrix2 = tf.constant([[2.],[2.]]) # 建立一個矩陣乘法 matmul op , 把 'matrix1' 和 'matrix2' 作為輸入. # 返回值 'product' 代表矩陣乘法的結果. product = tf.matmul(matrix1, matrix2) # 啟動預設圖. sess = tf.Session() # 呼叫 sess 的 'run()' 方法來執行矩陣乘法 op, 傳入 'product' 作為該方法的引數. # 上面提到, 'product' 代表了矩陣乘法 op 的輸出, 傳入它是向方法表明, 我們希望取回 # 矩陣乘法 op 的輸出. # # 整個執行過程是自動化的, 會話負責傳遞 op 所需的全部輸入. op 通常是併發執行的. # # 函式呼叫 'run(product)' 觸發了圖中三個 op (兩個常量 op 和一個矩陣乘法 op) 的執行. # # 返回值 'result' 是一個 numpy `ndarray` 物件. result = sess.run(product)print(result) #==> [[ 12.]] #任務完成, 關閉會話. sess.close()
Session物件在使用完後需要關閉以釋放資源。除了顯式呼叫close外,也可以使用"with"程式碼塊來自完成關閉操作。
with tf.Session() as sess:
result = sess.run([product])
print(result)
示例中使用一個會話Session來啟動圖,並呼叫Session.run()方法執行操作。
run():
在一個執行的圖中執行某種操作的行為。要求圖必須執行在會話中。在 Python的API中,它是Session類的一個方
法,可以通過Tensors來訂閱或獲取run()操作。
為了取回操作的輸出內容, 可以在使用Session物件的run()呼叫執行圖時, 傳入一些 tensor,這些tensor會幫助
取回結果.。我們可以取回單個節點,也可以取回多個tensor:
input1 = tf.constant(3.0) input2 = tf.constant(2.0) input3 = tf.constant(5.0) intermed = tf.add(input2, input3) mul = tf.multiply(input1, intermed) with tf.Session(): result = sess.run([mul, intermed]) print(result) # 輸出: # [array([ 21.], dtype=float32), array([ 7.], dtype=float32)]
因此我們不需要去逐個獲取tensor,而是從一次執行中可以一次獲得。