0. Tensorflow libraries
- TF Learn (tf.conrtib.learn): simplified interface that transits tf to scikit-learn
- TF Slim (tf.contrib.slim): lightweight library for defining, training and evaluating complex models
- High level API: Keras, TFLearn
1. Graph and session
TF將模型定義過程和計算過程分開了
所以使用過程可以分爲如下兩步
1. 整合Graph(模型定義)
2. 使用session執行Graph中的操作
1.1 Tensor是什麼
n維矩陣(n-d matrix)
0-d : number
1-d : vector
2-d : matrix
1.2 Graph
import tensorflow as tf
a=tf.add(3,5)
這段代碼會構建一個如下的Graph,graph即對應了計算過程。但是不會執行計算3+5。
在計算圖中,
節點是 operators, variables, and constants
邊代表 tennsors
1.3 Session
必須實例化一個Session,才能讓graph執行計算。
Session負責讀取數據送入到graph。
import tensorflow as tf
a = tf.add(3, 5)
sess = tf.Session()
print(sess.run(a))
sess.close()
//or
with tf.Session() as sess:
print(sess.run(a))
Session只會計算graph中,指定的計算節點需要的部分。
解釋如下,在下圖的graph中,Session只會執行紅色部分。在Session.run()語句執行之前graph已經建好。
sess.run([pow_op, useless]) 會執行全部graph
1.4 Subgraphs
使用多個GPU的實例代碼如下
# To put part of a graph on a specific CPU or GPU:
# Creates a graph.
with tf.device('/gpu:2'):
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name='b')
c = tf.multiply(a, b)
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
# Runs the op.
print(sess.run(c))
1.5 MultiGraph
假設同一個任務有多個模型graph需要同時訓練。