以下運行環境: Ubuntu 18.04 LTS, tensorflow 1.8, python 3.6.5
tensorflow的tf.Graph是靜態的圖(對比eager execution),它表示模型的骨架,定義圖不需要輸入數據也不會執行運算
圖的創建和使用
# 創建圖 g_1 = tf.Graph() # 在命名空間中構建圖 with g_1.as_default(): pass
一個圖對應一個模型,盡量不要出現子圖。訓練模型時,整理代碼的一種常用方法是使用一個圖訓練模型,然后使用另一個圖對受訓模型進行評估或推理。在通常情況下,推理圖與訓練圖不同。
通過添加tf.Operation
和tf.Tensor來構建tf.Graph
a = tf.constant(42.0, name='const1') b = tf.constant(2.0, name='cosnt2') c = tf.add(a, b, name='add1')
tf.constant(42.0, name='const1')創建名為const1的Operation並將該const1的結果作為返回值返回,其中const1用於生成值為42的scalar Tensor
tf.add(a, b, name='add1')創建名為add1的Operation並返回其結果,其中add1接收2個Tensor作為輸入
TensorFlow 使用tf.Session
類來表示客戶端程序(通常為 Python 程序,但也提供了其他語言的類似接口)與 C++ 運行時之間的連接。
通過session執行圖
with tf.Session(graph=g_1) as sess: x = tf.placeholder(tf.float32, shape=[3]) y = tf.square(x) fetch = [y] feed_dict = { x: [1.0, 2.0, 3.0] } print(sess.run(fetch, feed_dict)) # => "[1.0, 4.0, 9.0]"
使用tensorboard顯示圖
with tf.Session() as sess: writer = tf.summary.FileWriter("/tmp/log/...", sess.graph) # Perform your computation... for i in range(1000): sess.run(train_op) # ... writer.close()
在終端中輸入tensorboard --logdir='path'以啟動tensorboard
使用多個圖進行編程
g_1 = tf.Graph() with g_1.as_default(): # Operations created in this scope will be added to `g_1`. c = tf.constant("Node in g_1") # Sessions created in this scope will run operations from `g_1`. sess_1 = tf.Session() g_2 = tf.Graph() with g_2.as_default(): # Operations created in this scope will be added to `g_2`. d = tf.constant("Node in g_2") # Alternatively, you can pass a graph when constructing a session # `sess_2` will run operations from `g_2`. sess_2 = tf.Session(graph=g_2) # Get the default graph. g = tf.get_default_graph()