參考文獻 強烈推薦Tensorflow實戰Google深度學習框架 實驗平臺: Tensorflow1.4.0 python3.5.0 MNIST數據集將四個文件下載後放到當前目錄下的MNIST_data文件夾下python
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import tqdm # #### 1. 生成變量監控信息並定義生成監控信息日誌的操做。 SUMMARY_DIR = "log_1" BATCH_SIZE = 100 TRAIN_STEPS = 3000 # var給出了須要記錄的張量,name給出了在可視化結果中顯示的圖表名稱,這個名稱通常和變量名一致 def variable_summaries(var, name): # 將生成監控信息的操做放在同一個命名空間下 with tf.name_scope('summaries'): # 經過tf.histogram_summary函數記錄張量中元素的取值分佈 # tf.summary.histogram函數會生成一個Summary protocol buffer. # 將Summary 寫入TensorBoard 門志文件後,在HISTOGRAMS 欄,和 # DISTRIBUTION 欄下都會出現對應名稱的圖表。和TensorFlow 中其餘操做相似, # tf.summary.histogram 函數不會馬上被執行,只有當sess.run 函數明確調用這個操做時, TensorFlow # 纔會具正生成並輸出Summary protocol buffer. tf.summary.histogram(name, var) # 計算變量的平均值,並定義生成平均值信息日誌的操做,記錄變量平均值信息的日誌標籤名 # 爲'mean/'+name,其中mean爲命名空間,/是命名空間的分隔符 # 在相同命名空間中的監控指標會被整合到同一欄中,name則給出了當前監控指標屬於哪個變量 mean = tf.reduce_mean(var) tf.summary.scalar('mean/' + name, mean) # 計算變量的標準差,並定義生成其日誌文件的操做 stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean))) tf.summary.scalar('stddev/' + name, stddev) # #### 2. 生成一層全連接的神經網絡。 def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu): # 將同一層神經網絡放在一個統一的命名空間下 with tf.name_scope(layer_name): # 聲明神經網絡邊上的權值,並調用權重監控信息日誌的函數 with tf.name_scope('weights'): weights = tf.Variable(tf.truncated_normal([input_dim, output_dim], stddev=0.1)) variable_summaries(weights, layer_name + '/weights') # 聲明神經網絡邊上的偏置,並調用偏置監控信息日誌的函數 with tf.name_scope('biases'): biases = tf.Variable(tf.constant(0.0, shape=[output_dim])) variable_summaries(biases, layer_name + '/biases') with tf.name_scope('Wx_plus_b'): preactivate = tf.matmul(input_tensor, weights) + biases # 記錄神經網絡節點輸出在通過激活函數以前的分佈 tf.summary.histogram(layer_name + '/pre_activations', preactivate) activations = act(preactivate, name='activation') # 記錄神經網絡節點輸出在通過激活函數以後的分佈。 """ 對於layerl ,由於使用了ReLU函數做爲激活函數,因此全部小於0的值部被設爲了0。因而在激活後 的layerl/activations 圖上全部的值都是大於0的。而對於layer2 ,由於沒有使用激活函數, 因此layer2/activations 和layer2/pre_activations 同樣。 """ tf.summary.histogram(layer_name + '/activations', activations) return activations def main(): mnist = input_data.read_data_sets("./datasets/MNIST_data", one_hot=True) with tf.name_scope('input'): x = tf.placeholder(tf.float32, [None, 784], name='x-input') y_ = tf.placeholder(tf.float32, [None, 10], name='y-input') with tf.name_scope('input_reshape'): image_shaped_input = tf.reshape(x, [-1, 28, 28, 1]) tf.summary.image('input', image_shaped_input, 10) # 將輸入變量還原成圖片的像素矩陣,並經過tf.iamge_summary函數定義將當前的圖片信息寫入日誌的操做 hidden1 = nn_layer(x, 784, 500, 'layer1') y = nn_layer(hidden1, 500, 10, 'layer2', act=tf.identity) # 計算交叉熵並定義生成交叉熵監控日誌的操做。 with tf.name_scope('cross_entropy'): cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y, labels=y_)) tf.summary.scalar('cross_entropy', cross_entropy) with tf.name_scope('train'): train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy) """ 計算模型在當前給定數據上的正確率,並定義生成正確率監控日誌的操做。若是在sess.run() 時給定的數據是訓練batch,那麼獲得的正確率就是在這個訓練batch上的正確率;若是 給定的數據爲驗證或者測試數據,那麼獲得的正確率就是在當前模型在驗證或者測試數據上 的正確率。 """ with tf.name_scope('accuracy'): with tf.name_scope('correct_prediction'): correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) with tf.name_scope('accuracy'): accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) tf.summary.scalar('accuracy', accuracy) # tf.scalar_summary,tf.histogram_summary,tf.image_summary函數都不會當即執行,須要經過sess.run來調用這些函數 # 由於程序重定義的寫日誌的操做很是多,一一調用很是麻煩,因此Tensorflow提供了tf.merge_all_summaries函數來整理全部的日誌生成操做。 # 在Tensorflow程序執行的過程當中只須要運行這個操做就能夠將代碼中定義的全部日誌生成操做所有執行一次,從而將全部日誌文件寫入文件。 merged = tf.summary.merge_all() with tf.Session() as sess: # 初始化寫日誌的writer,並將當前的Tensorflow計算圖寫入日誌 summary_writer = tf.summary.FileWriter(SUMMARY_DIR, sess.graph) tf.global_variables_initializer().run() for i in tqdm.tqdm(range(TRAIN_STEPS)): xs, ys = mnist.train.next_batch(BATCH_SIZE) # 運行訓練步驟以及全部的日誌生成操做,獲得此次運行的日誌。 summary, _ = sess.run([merged, train_step], feed_dict={x: xs, y_: ys}) # 將獲得的全部日誌寫入日誌文件,這樣TensorBoard程序就能夠拿到此次運行所對應的 # 運行信息。 summary_writer.add_summary(summary, i) summary_writer.close() if __name__ == '__main__': main()