學習筆記TF039:TensorBoard
首先向大家和《TensorFlow實戰》的作者說句不好意思。我現在看的書是《TensorFlow實戰》。但從TF024開始,我在學習筆記的參考資料里一直寫的是《TensorFlow實踐》,我自己粗心搞錯了,希望不至於對大家造成太多誤導。
TensorBoard,TensorFlow官方可視化工具。展示模型訓練過程各種匯總數據。標量(Scalars)、圖片(Images)、音頻(audio)、計算圖(Graphs)、數據分布(Distributions)、直方圖(Histograms)、嵌入向量(Embeddings)。TensorBoard展示數據,執行TensorFlow計算圖過程,各種類型數據匯總並記錄到日誌文件。TensorBoard讀取日誌文件,解析數據,生成數據可視化Web頁,瀏覽器觀察各種匯總數據。
載入TesnsorFlow,設置訓練最大步數1000,學習速率0.001,dropout保留比率0.9。設置MNIST數據下載地址data_dir、匯總數據日誌存放路徑log_dir。日誌路徑log_dir存所有匯總數據。
input_data.read_data_sets下載MNIST數據,創建TensorFlow默認Session。
with tf.name_scope限定命名空間。定義輸入x、y placeholder。輸入一維數據變形28x28圖片儲存到tensor,tf.summary.image匯總圖片數據TensorBoard展示。
定義神經網路模型參數初始化方法,權重用truncated_normal初始化,偏置賦值0.1。
定義Variable變數數據匯總函數,計算Variable mean、stddev、max、min,tf.summary.scalar記錄、匯總。tf.summary.histogram記錄變數var直方圖數據。
設計MLP多層神經網路訓練數據,每一層匯總模型參數數據。定義創建一層神經網路數據匯總函數nn_layer。輸入參數,輸入數據input_tensor、輸入維度input_dim、輸出維度output_dim、層名稱layer_name。激活函數act用ReLU。初始化神經網路權重、偏置,用variable_summaries匯總variable數據。輸入,矩陣乘法,加偏置,未激活結果用tf.summary.histogram統計直方圖。用激活函數後,tf.summary.histogram再統計一次。
nn_layer創建一層神經網路,輸入維度圖片尺寸28x28=784,輸出維度隱藏節點數500。創建Dropout層,用tf.summary.scalar記錄keep_prob。用nn_layer定義神經網路輸出層,輸入維度為上層隱含節點數500,輸出維度類別數10,激活涵數全等映射identity。
tf.nn.softmax_cross_entropy_with_logits()對前面輸出層結果Softmax處理,計算交叉熵損失cross_entropy。計算平均損失,tf.summary.scalar統計匯總。
Adma優化器優化損失。統計預測正確樣本數,計算正確率accury, tf.summary.scalar統計匯總accuracy。
tf.summary.merger_all()獲取所有匯總操作。定義兩個tf.summary.FileWriter(文件記錄器)在不同子目錄,分別存放訓練和測試日誌數據。Session計算圖sess.graph加入訓練過程記錄器,TensorBoard GRAPHS窗口展示整個計算圖可視化效果。tf.global_variables_initializer().run()初始化全部變數。
定義feed_dict損失函數。先判斷訓練標記,True,從mnist.train獲取一個batch樣本,設置dropout值;False,獲取測試數據,設置keep_prob 1,沒有dropout效果。
實際執行具體訓練、測試、日誌記錄操作。tf.train.Saver()創建模型保存器。進入訓練循環,每隔10步執行merged(數據匯總)、accuracy(求測試集預測準確率)操作,test_writer.add_sumamry將匯總結果summary和循環步數i寫入日誌文件。每隔100步,tf.RunOptions定義TensorFlow運行選項,設置trace_lever FULL_TRACE。tf.RunMetadata()定義TensorFlow運行元信息,記錄訓練運算時間和內存佔用等信息。執行merged數據匯總操作,train_step訓練操作,匯總結果summary、訓練元信息run_metadata添加到train_writer。執行merged、train_step操作,添加summary到train_writer。所有訓練全部結束,關閉train_writer、test_writer。
切換Linux命令行,執行TensorBoard程序,--logdir指定TensorFlow日誌路徑,TensorBoard自動生成所有匯總數據可視化結果。
tensorboard --logdir=/tmp/tensorflow/mnist/logs/mnist_with_summaries
複製網址到瀏覽器。
打開標量SCALARS窗口,打開accuracy圖表。調整Smoothing參數,控制曲線平滑處理,數值越小越接近實際值,波動大;數值越大麴線越平緩。圖表下方按鈕放大圖片,右邊按鈕調整坐標軸範圍。
切換圖像IMAGES窗口,可以看到所有tf.summary.image()匯總數據。
計算圖GRAPHS窗口,整個TensorFlow計算圖結構。網路forward inference流程,backward訓練更新參數流程。實線代表數據依賴關係,虛線代表控制條件依賴關係。節點窗口,看屬性、輸入、輸出及tensor尺寸。
"+"按鈕,展示node內部細節。所有同一命名空間節點被摺疊一起。右鍵單擊節點選擇刪除。
切換配色風絡,基於結構,同結構節點同顏色;基於運算硬體,同運算硬體節點同顏色。
Session runs,選擇run_metadata訓練元信息。
切換DISTRIBUTIONS窗口,看各個神經網路層輸出分布,激活函數前後結果。看看有沒有被屏蔽節點(dead neurons)。轉為直方圖。
EMBEDDINGS窗口,降維嵌入向量可視化效果。tf.save.Saver保存整個模型,TensorBoard自動對模型所有二維Variable可視化(只有Variable可以被保存,Tensor不行)。選擇T-SNE或PCA演算法對數據列(特徵)降維,在3D、2D坐標可視化展示。對Word2Vec計算或Language Model非常有用。
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
max_steps=1000
learning_rate=0.001
dropout=0.9
data_dir=/tmp/tensorflow/mnist/input_data
log_dir=/tmp/tensorflow/mnist/logs/mnist_with_summaries
# Import data
mnist = input_data.read_data_sets(data_dir,one_hot=True)
sess = tf.InteractiveSession()
# Create a multilayer model.
# Input placeholders
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)
# We cant initialize these variables to 0 - the network will get stuck.
def weight_variable(shape):
"""Create a weight variable with appropriate initialization."""
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
"""Create a bias variable with appropriate initialization."""
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def variable_summaries(var):
"""Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""
with tf.name_scope(summaries):
mean = tf.reduce_mean(var)
tf.summary.scalar(mean, mean)
with tf.name_scope(stddev):
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
tf.summary.scalar(stddev, stddev)
tf.summary.scalar(max, tf.reduce_max(var))
tf.summary.scalar(min, tf.reduce_min(var))
tf.summary.histogram(histogram, var)
def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu):
"""Reusable code for making a simple neural net layer.
It does a matrix multiply, bias add, and then uses relu to nonlinearize.
It also sets up name scoping so that the resultant graph is easy to read,
and adds a number of summary ops.
"""
# Adding a name scope ensures logical grouping of the layers in the graph.
with tf.name_scope(layer_name):
# This Variable will hold the state of the weights for the layer
with tf.name_scope(weights):
weights = weight_variable([input_dim, output_dim])
variable_summaries(weights)
with tf.name_scope(biases):
biases = bias_variable([output_dim])
variable_summaries(biases)
with tf.name_scope(Wx_plus_b):
preactivate = tf.matmul(input_tensor, weights) + biases
tf.summary.histogram(pre_activations, preactivate)
activations = act(preactivate, name=activation)
tf.summary.histogram(activations, activations)
return activations
hidden1 = nn_layer(x, 784, 500, layer1)
with tf.name_scope(dropout):
keep_prob = tf.placeholder(tf.float32)
tf.summary.scalar(dropout_keep_probability, keep_prob)
dropped = tf.nn.dropout(hidden1, keep_prob)
# Do not apply softmax activation yet, see below.
y = nn_layer(dropped, 500, 10, layer2, act=tf.identity)
with tf.name_scope(cross_entropy):
# The raw formulation of cross-entropy,
#
# tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.softmax(y)),
# reduction_indices=[1]))
#
# can be numerically unstable.
#
# So here we use tf.nn.softmax_cross_entropy_with_logits on the
# raw outputs of the nn_layer above, and then average across
# the batch.
diff = tf.nn.softmax_cross_entropy_with_logits(logits=y, labels=y_)
with tf.name_scope(total):
cross_entropy = tf.reduce_mean(diff)
tf.summary.scalar(cross_entropy, cross_entropy)
with tf.name_scope(train):
train_step = tf.train.AdamOptimizer(learning_rate).minimize(
cross_entropy)
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)
# Merge all the summaries and write them out to /tmp/mnist_logs (by default)
merged = tf.summary.merge_all()
train_writer = tf.summary.FileWriter(log_dir + /train, sess.graph)
test_writer = tf.summary.FileWriter(log_dir + /test)
tf.global_variables_initializer().run()
# Train the model, and also write summaries.
# Every 10th step, measure test-set accuracy, and write test summaries
# All other steps, run train_step on training data, & add training summaries
def feed_dict(train):
"""Make a TensorFlow feed_dict: maps data onto Tensor placeholders."""
if train:
xs, ys = mnist.train.next_batch(100)
k = dropout
else:
xs, ys = mnist.test.images, mnist.test.labels
k = 1.0
return {x: xs, y_: ys, keep_prob: k}
saver = tf.train.Saver()
for i in range(max_steps):
if i % 10 == 0: # Record summaries and test-set accuracy
summary, acc = sess.run([merged, accuracy], feed_dict=feed_dict(False))
test_writer.add_summary(summary, i)
print(Accuracy at step %s: %s % (i, acc))
else: # Record train set summaries, and train
if i % 100 == 99: # Record execution stats
run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
run_metadata = tf.RunMetadata()
summary, _ = sess.run([merged, train_step],
feed_dict=feed_dict(True),
options=run_options,
run_metadata=run_metadata)
train_writer.add_run_metadata(run_metadata, step%03d % i)
train_writer.add_summary(summary, i)
saver.save(sess, log_dir+"/model.ckpt", i)
print(Adding run metadata for, i)
else: # Record a summary
summary, _ = sess.run([merged, train_step], feed_dict=feed_dict(True))
train_writer.add_summary(summary, i)
train_writer.close()
test_writer.close()
參考資料:
《TensorFlow實戰》
歡迎付費諮詢(150元每小時),我的微信:qingxingfengzi
推薦閱讀:
※增強學習(Reinforcement Learning)的幾點迷惑?
※為什麼CNTK知名度和普及率不如Tensorflow、Theano、caffe、Torch?
※哪裡有受限玻爾茲曼機、卷積神經網路 的講解課程?
※從事深度學習等人工智慧研究在未來的職業發展前景如何?
※AlphaGo挑戰《星際爭霸2》會像圍棋之戰一樣橫掃頂級選手嗎?
TAG:TensorFlow | 机器学习 | 深度学习DeepLearning |