1.什么是Tensorboard?
PPT設計原則中有這樣一條,叫“文不如表,表不如圖”,可見圖表在表達中更為直觀、明確。程序設計中也是一樣,我們經常用圖表來描述程序的結構和流程,本文所述的Tensorboard就是Tensorflow提供的一款強大的可視化工具,可以借助圖表更方便地進行Tensorflow程序的理解、調試和優化。
左面的數據流圖cool嗎?它是Tensorflow官網上給出的demo,下面,本文就結合一個具體的例子,介紹下Tensorboard的基本使用。
2. 如何使用Tensorboard?
Tensorboard的使用可大體歸結為如下幾步:
1) 在構建graph的過程中,記錄你想要追蹤的Tensor
2) Session會話運行上一步驟中的記錄
3) 查看可視化效果
那么如何具體操作呢?先走一波示例代碼,一個用三層神經網絡實現回歸問題的小例子
1 import tensorflow as tf 2 import numpy as np 3 import matplotlib.pyplot as plt 4 5 def add_layer(inputs, in_size, out_size, n_layer, activation_function = None): 6 # add one more layer and return the output of this layer 7 layer_name = 'layer%s' % n_layer 8 with tf.name_scope('layer'): 9 with tf.name_scope('weights'): 10 Weights = tf.Variable(tf.random_normal([in_size, out_size]), name = 'W') 11 tf.summary.histogram(layer_name + '/weights', Weights) 12 with tf.name_scope('biases'): 13 biases = tf.Variable(tf.zeros([1,out_size]) + 0.1, name = 'b') 14 tf.summary.histogram(layer_name + '/biases', biases) 15 with tf.name_scope('Wx_plus_b'): 16 Wx_plus_b = tf.add(tf.matmul(inputs, Weights), biases, name = 'Wpb') 17 if activation_function is None: 18 outputs = Wx_plus_b 19 else: 20 outputs = activation_function(Wx_plus_b) 21 tf.summary.histogram(layer_name + '/outputs', outputs) 22 return outputs 23 24 #define placeholder for inputs 25 with tf.name_scope('inputs'): 26 xs = tf.placeholder(tf.float32, [None, 1], name = 'x_input') 27 ys = tf.placeholder(tf.float32, [None, 1], name = 'y_input') 28 29 # make up some real data 30 x_data = np.linspace(-1.0, 1.0, 300, dtype = np.float32)[:,np.newaxis] 31 noise = np.random.normal(0.0, 0.05, x_data.shape) 32 y_data = np.square(x_data) + 0.5 + noise 33 34 # add hidden layer and output layer 35 l1 = add_layer(xs, 1, 10, n_layer = 1, activation_function = tf.nn.relu) 36 prediction = add_layer(l1, 10, 1, n_layer = 2, activation_function = None) 37 38 # the error between prediction and real data 39 with tf.name_scope('loss'): 40 loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices = [1]), name = 'L') 41 tf.summary.scalar('loss', loss) 42 with tf.name_scope('train'): 43 train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) 44 45 init = tf.initialize_all_variables() 46 with tf.Session() as sess: 47 sess.run(init) 48 fig = plt.figure() 49 ax = fig.add_subplot(1,1,1) 50 ax.scatter(x_data, y_data) 51 plt.show(block = False) 52 merged =tf.summary.merge_all() 53 writer = tf.summary.FileWriter('/tmp/tensorlogs/ex5', sess.graph) 54 for i in range(1000): 55 sess.run(train_step, feed_dict = {xs : x_data, ys : y_data}) 56 if i % 50 == 0: 57 # print(i, sess.run(loss, feed_dict = {xs : x_data, ys : y_data})) 58 try: 59 ax.lines.remove(lines[0]) 60 except Exception: 61 pass 62 result, prediction_value = sess.run([merged, prediction], feed_dict = {xs : x_data, ys : y_data}) 63 lines = ax.plot(x_data, prediction_value, 'r-', lw = 5) 64 plt.pause(0.1) 65 writer.add_summary(result, i)
下面具體分解上述的3個步驟
1) 在上述示例中用了tf.summary.histogram()和tf.summary.scalar()記錄要追蹤的Tensor,前者可匯總和記錄標量數據,如41行的loss;后者可匯總和記錄變量為直方圖,如11行的Weights。此外,tf.summary還可匯總記錄圖片(images),音頻(Audio)等內容。
2) 在Session中運行之前,要將上述所有匯總記錄做一個合並,以便統一運行,如52行的merged所示,還要指定運行后存放數據記錄的日志文件的位置,如53行的writer所示。接下來,就可以通過運行獲取數據記錄了,如62行的result所示,這里為了簡潔,將result和prediction_value放在了一起運行,也可以拆成兩行執行。程序要進行多次訓練,如54行的for所示,每隔50次記錄下追蹤數據,如56行if所示,每次記錄通過writer.add_summary()添加到日志文件中。
3) 程序運行結束后,打開終端,輸入tensorboard --logdir='path',其中的path為指定的日志文件存放路徑,如53行'/tmp/tensorlogs/ex5',運行后會看到下圖所示
在瀏覽器的地址欄中輸入上圖中所示的地址http://David:6006,就會看到如下圖所示的tensorboard圖表:
graph: 程序圖的結構
scalars: 損失函數的值隨着訓練次數的增加逐步下降
distributions: 隱藏層和輸出層參數的分布圖
histograms: 隱藏層和輸出層參數的直方圖
3. 總結
tensorboard的使用對於程序的理解、分析和優化都很有幫助,本文結合一個小的程序例子介紹了tensorboard的基本使用,更多內容可參看官方文檔中關於Mnist數據集的代碼實例。本文的實驗環境為ubuntu16.04+tensorflow1.1。