Tensorflow的運行機制包括兩部分,一個是tensor, 一個是flow.
- Tensor表明tensorflow所用的數據類型
- flow也就是計算圖,表明tensor之間的關係
所以在構建tensorflow的運行程序的時候,就包括兩個步驟:
- 構建tensoflow計算圖(Graph)
- 執行tensorflow計算圖(Session)
1. 計算圖的使用與注意事項
1.1 計算圖的構建
在tensorflow中定義tensor, tensorflow會自動將定義的tensor轉化爲計算圖的一個節點,比如:
import tensorflow as tf
a = tf.constant([1, 2], name='a')
b = tf.constant([2, 3], name='b')
result = a + b
print(result) # Tensor("add:0", shape=(2,), dtype=int32)
如果直接運行result, 打印出來的是result這個tensor,而不是result中的值,這是因爲上面的code只是在計算圖中定義了節點,而沒有執行。
可以通過tensorboard查看定義的tensor.
1.2 計算圖注意事項
如果沒有顯式定義計算圖,tensorflow會自動維護默認的計算圖
print(a.graph is tf.get_default_graph()) # True
如果不使用tensorflow自動維護的默認計算圖,也可以通過tf.Graph()來進行生成graph. 並且每個graph中的變量是不能進行共享的。
- 從下面的代碼可以看出g1和g2上面都有一個tensor爲a, 但是兩個計算圖不共享變量。
import tensorflow as tf
g1 = tf.Graph()
print(g1) ##<tensorflow.python.framework.ops.Graph object at 0x7f1a8eb73198>
with g1.as_default():
a = tf.get_variable('v', shape=[1,], initializer=tf.zeros_initializer)
print(a.graph) #<tensorflow.python.framework.ops.Graph object at 0x7f1a8eb73198>
g2 = tf.Graph()
with g2.as_default():
a = tf.get_variable('v', shape=[1,], initializer=tf.ones_initializer)
print(a.graph) # <tensorflow.python.framework.ops.Graph object at 0x7f4ebc882208>
with tf.Session(graph=g1) as sess:
init =tf.global_variables_initializer()
sess.run(init)
with tf.variable_scope('', resue=tf.AUTO_REUSE):
sess.run(tf.get_variable('v', shape=[1,])) # 0
with tf.Session(graph=g1) as sess:
init =tf.global_variables_initializer()
sess.run(init)
with tf.variable_scope('', resue=tf.AUTO_REUSE):
sess.run(tf.get_variable('v', shape=[1,])) # 1
3. 集合
tensorflow中的變量很多,所以需要將其變量組織起來,可以通過tf.add_to_collection和tf.get_collection添加和獲取集合中的所有變量。
tensorflow還定義了一些常見的集合
- tf.GraphKeys.VARIABLES : 所有變量, tf.GraphKeys.Global_VARIABLES.
- tf.GraphKeys.TRAINABLE_VARIABLES: 可學習的變量