2017年8月30日 星期三

(新手指南) 開啟 tensorboard 來視覺化 tensorflow 程式

(一) 環境設定 & 準備事項
1. 小編使用環境: Mac OS
2. Source code:小編使用的是Dandelion Mané演講所demo的Code (https://github.com/decentralion/tf-dev-summit-tensorboard-tutorial)

3. 請先安裝tensorflow, python, virtualenv至你的系統中,請參考官網的安裝步驟 (https://www.tensorflow.org/install/install_mac)


(二) 開始執行tensorboard

請注意,tensorboard主要是讀取tensorflow的event檔案,所以請了解每個source code將event寫在哪裡。
本節分兩個部分:
(2-1)下載別人的Source code時,要如何開啟tensorboard
(2-2)自己撰寫Python code時,要如何開啟tensorboard

正文開始:
(2-1) 執行別人的Python Source Code

1. 首先,先進入git,把整包下載下載:

2. 接著開啟console,並執行程式:
(1)載入tensorflow
source ~/tensorflow/bin/activate
(2) 進入到下載的位置,執行程式
python mnist.py 
3. 在開啟另外一個console,並執行tensorboard
(1)載入tensorflow
source ~/tensorflow/bin/activate
(2) 執行tensorboard
tensorboard --logdir=/tmp/mnist_tutorial

其位址,可參考程式中所寫的位址,如下圖所示:

4. 接著他會跟你說,打開XXX位址去檢視,如下所示:TensorBoard 0.1.5 at http://AllendeMacBook-Pro.local:6006 (Press CTRL+C to quit)

5. 你就可以在瀏覽器輸入這個位址,去檢視tensorboard了!

(2-2) 自行撰寫的python程式
當自己在撰寫Python程式時,透過tensorboard可以迅速了解自己執行到哪個步驟。
1. 首先,進入python環境
(1)載入tensorflow
source ~/tensorflow/bin/activate
(2) 進入python
python

2. 自己撰寫小程式
程式碼:


載入tensorflow API,讓Python能夠存取tensorflow的class, method和symbol
import tensorflow as tf

宣告2常數
node1 = tf.constant(3.0, dtype=tf.float32)
node2 = tf.constant(4.0) # also tf.float32 implicitly
print(node1, node2)

建立一個Session物件,並且執行run這個方法,來去建立Graph以評估node1和node2
sess = tf.Session()
print(sess.run([node1, node2]))

在建立一個node3,並利用add方法,使得 node1+node2 = node3

node3 = tf.add(node1, node2)
print("node3:", node3)
print("sess.run(node3):", sess.run(node3))

重頭戲來了,透過summary方法,將上述的內容輸出到 '/tmp/allen_test'中,(路徑可以自行定義);然後再透過add_graph的方式,將上述node的圖寫到檔案中。

writer = tf.summary.FileWriter('/tmp/allen_test')
writer.add_graph(sess.graph)

3. 請不要將上述console關掉,也不要退出python,請開另外一個console

並執行以下語法

tensorboard --logdir=/tmp/allen_test

接著他會跟你說,打開XXX位址去檢視,如下所示:TensorBoard 0.1.5 at http://AllendeMacBook-Pro.local:6006 (Press CTRL+C to quit)

你就可以透過瀏覽器,看到tensorboard囉,如下圖所示:


記錄2020美國寫下歷史一頁