TensorFlow哲學
separates definition of computations from their execution
對定義計算,計算的執行,做了分離。
人工智能,目前尤其火熱,那麼深度學習無疑是最火熱的,包括,圖像處理,自然語言處理,那麼最好的框架是誰?
Tensorflow 已經是目前最好的深度學習框架,甚至沒有之一。如何入門,請看本文。
01
—
Tensor是什麼?
Tensor是一個 n 維數組:
- 0-d tensor: scalar (標量)
- 1-d tensor: vector (向量)
- 2-d tensor: matrix(矩陣)
- 等等
02
—
數據流圖
以上就是數據流圖。
下面從最簡單的圖開始:
import tensorflow as tf
a = tf.add(3, 5)
通過TensorBoard進行可視化:
為什麼是 x, y ?
TF 自動地命名節點,當我們沒有顯示地指定節點名稱時,
x = 3
y = 5
接下來,我們打印 a,看看發生什麼:
print (a)
Tensor("Add:0", shape=(), dtype=int32)
圖graph只是定義了操作operations , 如何得到a的值?
03
—
執行環境:Session
創建一個Session,並在這個Session中執行上面的圖,抓取到 a 的值。
創建sess,並在當前的sess中執行圖:
with tf.Session() as sess:
print(sess.run(a))
Session對象,封裝了TF的執行環境。大家如果開發過多線程,分佈式軟件的話,對於Session的理解可能更容易些,Session尤其對於高併發環境,並行計算顯得更重要。
記住
圖graph只是定義了操作operations,但是操作operations只能在session裡面執行,但是graph和session是獨立創建的。
04
—
Tensorboard入門
以windows下的使用Tensorboard為例,如果在Linux系統下,請在個別地方做出修改。
首先,必須在終端啟動tensorboard,如果採用anaconda安裝地話,在目錄Anaconda3\\Scripts下有個啟動項: tensorboard.exe,這就是tensorboard的服務端。在cmd窗口,cd 到這個目錄。
然後,編寫tensorboard,代碼:
import tensorflow as tf
with tf.name_scope('input1'):
input1 = tf.constant(3.0,name='input1')
with tf.name_scope('input2'):
input2 = tf.constant(5.0,name='input2')
output = tf.add(input1,input2,name='add')
with tf.Session() as sess:
output = sess.run(output)
graph = tf.get_default_graph()
#將日誌文件寫入到目錄../log/下
writer = tf.summary.FileWriter('log',graph)
writer.close()
這樣在log文件夾下,增加了一個event文件,
再在終端,輸入 tensorboard.exe --logdir = 剛在生成的log文件夾的絕對路徑,回車,這樣服務端就啟動了,
接下來,啟動客戶端,即瀏覽器,輸入localhost:6006,端口是6006,選中graphs,得到如下的可視化圖:
閱讀更多 Python與算法社區 的文章