【TensorFlow-windows】TensorBoard可视化
前言
緊接上一篇博客,學(xué)習(xí)tensorboard可視化訓(xùn)練過(guò)程。
國(guó)際慣例,參考博客:
MNIST機(jī)器學(xué)習(xí)入門(mén)
Tensorboard 詳解(上篇)
Tensorboard 可視化好幫手 2
tf-dev-summit-tensorboard-tutorial
tensorflow官方mnist_with_summaries
預(yù)備知識(shí)
根據(jù)之前學(xué)的知識(shí),創(chuàng)建一個(gè)卷積結(jié)構(gòu)進(jìn)行手寫(xiě)數(shù)字分類(lèi)
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data#讀取手寫(xiě)數(shù)字 mnist = input_data.read_data_sets('./dataset/',one_hot=True)#定義卷積操作 def conv_layer(input,size_in,size_out,name='conv'):with tf.name_scope(name):w=tf.Variable(tf.truncated_normal([5,5,size_in,size_out],stddev=0.1),name='W')b=tf.Variable(tf.constant(0.1,shape=[size_out]),name='B')conv = tf.nn.conv2d(input,w,strides=[1,1,1,1],padding='SAME')act = tf.nn.relu(conv+b)return tf.nn.max_pool(act,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')#全連接層 def fc_layer(input,size_in,size_out,name='fc'):with tf.name_scope(name):w=tf.Variable(tf.truncated_normal([size_in,size_out],stddev=0.1),name='W')b=tf.Variable(tf.constant(0.1,shape=[size_out]),name='B')act=tf.matmul(input,w)+breturn act#創(chuàng)建模型 def create_model(input_x):#卷積input_img = tf.reshape(input_x,[-1,28,28,1])conv1=conv_layer(input_img,1,32,'conv1')conv2=conv_layer(conv1,32,64,'conv2')#全連接flattened=tf.reshape(conv2,[-1,7*7*64])fc1=fc_layer(flattened,7*7*64, 1024,'fc1')act1=tf.nn.relu(fc1)out=fc_layer(act1,1024,10,'fc2')return out#定義網(wǎng)絡(luò)輸入,輸出 X=tf.placeholder(tf.float32,shape=[None,28*28],name='x') Y=tf.placeholder(tf.float32,shape=[None,10],name='y')logits = create_model(X) #創(chuàng)建模型 prediction=tf.nn.softmax(logits=logits,name='prediction') #預(yù)測(cè)# 損失函數(shù) loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits,labels=Y)) optimize = tf.train.AdamOptimizer(learning_rate=0.01) train_op = optimize.minimize(loss_op)#評(píng)估函數(shù) correct_pred = tf.equal(tf.argmax(prediction,1),tf.argmax(Y,1)) accuracy = tf.reduce_mean(tf.cast(correct_pred,tf.float32))with tf.Session() as sess:sess.run(tf.global_variables_initializer())for step in range(20000):batch_xs,batch_ys=mnist.train.next_batch(50)sess.run(train_op,feed_dict={X:batch_xs,Y:batch_ys})if(step%10==0 or step==1):loss,acc = sess.run([loss_op,accuracy],feed_dict={X: mnist.test.images,Y: mnist.test.labels})print('Step:{0},loss:{1},acc:{2}'.format(step,loss,acc))依舊是那幾個(gè)流程:讀數(shù)據(jù)→初始化相關(guān)參數(shù)→定義接收數(shù)據(jù)的接口以便測(cè)試使用→初始化權(quán)重和偏置→定義基本模塊(編碼和解碼)→構(gòu)建模型(先編碼再解碼)→定義預(yù)測(cè)函數(shù)、損失函數(shù)、優(yōu)化器→訓(xùn)練
加入TensorBoard
從tensorflow的官方文檔來(lái)看,支持可視化操作函數(shù)有:scalar、image、audio、text、histogram
這里我們只需要使用scalar可視化loss值的變動(dòng),image可視化部分輸入數(shù)據(jù)、histogram可視化權(quán)重與偏置的分布。
很簡(jiǎn)單,調(diào)用方法統(tǒng)一是tf.summary。
可視化卷積層的權(quán)重和偏置
#定義卷積操作 def conv_layer(input,size_in,size_out,name='conv'):with tf.name_scope(name):w=tf.Variable(tf.truncated_normal([5,5,size_in,size_out],stddev=0.1),name='W') b=tf.Variable(tf.constant(0.1,shape=[size_out]),name='B') conv = tf.nn.conv2d(input,w,strides=[1,1,1,1],padding='SAME')act = tf.nn.relu(conv+b)tf.summary.histogram(name+'/weights',w)tf.summary.histogram(name+'/bias',b)return tf.nn.max_pool(act,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')可視化部分訓(xùn)練數(shù)據(jù):
#創(chuàng)建模型 def create_model(input_x):#卷積input_img = tf.reshape(input_x,[-1,28,28,1])tf.summary.image('input',input_img,3)conv1=conv_layer(input_img,1,32,'conv1')conv2=conv_layer(conv1,32,64,'conv2')#全連接flattened=tf.reshape(conv2,[-1,7*7*64])fc1=fc_layer(flattened,7*7*64, 1024,'fc1')act1=tf.nn.relu(fc1)out=fc_layer(act1,1024,10,'fc2')return out可視化損失函數(shù)變動(dòng):
# 損失函數(shù) loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits,labels=Y)) tf.summary.scalar('loss',loss_op)最終要把所有需要可視化的操作合并到一起:
merged=tf.summary.merge_all()而tensorflow中的操作一般需要由session執(zhí)行,也就是說(shuō)如果我們想寫(xiě)入日志,就需要在session中執(zhí)行merged操作,并使用add_summary將每次訓(xùn)練的記錄寫(xiě)入到日志文件。
with tf.Session() as sess:writer=tf.summary.FileWriter('logs/',sess.graph)sess.run(tf.global_variables_initializer())for step in range(20000):batch_xs,batch_ys=mnist.train.next_batch(50)sess.run(train_op,feed_dict={X:batch_xs,Y:batch_ys})if(step%10==0 or step==1):loss,acc,s = sess.run([loss_op,accuracy,merged],feed_dict={X: mnist.test.images[:100],Y: mnist.test.labels[:100]})print('Step:{0},loss:{1},acc:{2}'.format(step,loss,acc))writer.add_summary(s,step)然后運(yùn)行訓(xùn)練腳本,開(kāi)始訓(xùn)練以后,打開(kāi)終端,啟動(dòng)tensorboard
tensorboard --logdir 'logs'其中最后一個(gè)參數(shù)logs代表日志存儲(chǔ)的地方,根據(jù)自己的情況定義
運(yùn)行以后會(huì)彈出一個(gè)網(wǎng)址:
/home/xx/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.from ._conv import register_converters as _register_converters TensorBoard 1.12.2 at http://xx-XPS-8700:6006 (Press CTRL+C to quit)瀏覽器中打開(kāi)此網(wǎng)址,能夠看到tensorboard顯示的你想可視化的內(nèi)容。
【注】可能參數(shù)不會(huì)實(shí)施更新,在右上角的齒輪那里可以調(diào)整刷新間隔,默認(rèn)30s
后續(xù)
可視化對(duì)訓(xùn)練過(guò)程是十分重要的,有時(shí)候模型不起作用,loss不降或者炸了,可以通過(guò)權(quán)重來(lái)判斷是否參數(shù)更新是否出現(xiàn)了問(wèn)題,而且如果是生成對(duì)抗網(wǎng)絡(luò),可以把訓(xùn)練過(guò)程中的重建圖像打印出來(lái),也可以看到模型是否有效。
本博文源碼:https://download.csdn.net/download/zb1165048017/11536994
總結(jié)
以上是生活随笔為你收集整理的【TensorFlow-windows】TensorBoard可视化的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 小小军团英雄装备搭配与心得
- 下一篇: 【TensorFlow-windows】