1. 程式人生 > >深度學習框架TensorFlow學習與應用(五)——TensorBoard結構與視覺化

深度學習框架TensorFlow學習與應用(五)——TensorBoard結構與視覺化

一、TensorBoard網路結構

舉例:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#載入資料集
mnist=input_data.read_data_sets("D:\BaiDu\MNIST_data",one_hot=True)
#每個批次的大小
batch_size=100
#計算一共有多少個批次
n_batch=mnist.train.num_examples//batch_size

#名稱空間
with tf.name_scope('input'):
    #定義兩個placeholder
x=tf.placeholder(tf.float32,[None,784],name='x-input') y=tf.placeholder(tf.float32,[None,10],name='y-input') with tf.name_scope('layer'): #建立一個簡單的神經網路 with tf.name_scope('wights'): W=tf.Variable(tf.zeros([784,10])) with tf.name_scope('biases'): b=tf.Variable(tf.zeros([10
])) with tf.name_scope('xw_plus_b'): wx_plus_b=tf.matmul(x,W)+b with tf.name_scope('sofemax'): prediction=tf.nn.softmax(tf.matmul(x,W)+b) #二次代價函式 #loss=tf.reduce_mean(tf.square(y-prediction)) loss=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction)) #使用梯度下降法
train_step=tf.train.GradientDescentOptimizer(0.2).minimize(loss) #初始化變數 init=tf.global_variables_initializer() #結果存放在一個布林型列表中 correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#比較兩個引數大小,相同為true。argmax返回一維張量中最大的值所在的位置 #求準確率 accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))#將布林型轉化為32位浮點型,再求一個平均值。true變為1.0,false變為0。 with tf.Session() as sess: sess.run(init) write=tf.summary.FileWriter('logs/',sess.graph)#在當前檔案中寫檔案,存的就是圖的結構 for epoch in range(1): for batch in range(n_batch): batch_xs,batch_ys=mnist.train.next_batch(batch_size) sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys}) acc=sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}) print("Iter "+str(epoch)+",Testing Accuracy "+str(acc))

執行後開啟cmd(TensorFlow環境下):

tensorboard --logdir=C:\Users\JLUTiger\logs #檔案的路徑

得到如下的資訊:

TensorBoard 0.4.0rc2 at http://DESKTOP-UEGK0FV:6006 (Press CTRL+C to quit)

複製連結在瀏覽器中開啟,便進入TensorBoard,如下所示:

這裡寫圖片描述

從TensorBoard中可以看出資料是怎麼流動的等資訊。

二、TensorBoard網路執行

將上面的程式碼改寫為:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#載入資料集
tf.reset_default_graph()
mnist=input_data.read_data_sets("D:\BaiDu\MNIST_data",one_hot=True)



#每個批次的大小
batch_size=100
#計算一共有多少個批次
n_batch=mnist.train.num_examples//batch_size

#引數概要
def variable_summaries(var):
    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)#直方圖

#名稱空間
with tf.name_scope('input'):
    #定義兩個placeholder
    x=tf.placeholder(tf.float32,[None,784],name='x-input')
    y=tf.placeholder(tf.float32,[None,10],name='y-input')

with tf.name_scope('layer'):
    #建立一個簡單的神經網路
    with tf.name_scope('wights'):
        W=tf.Variable(tf.zeros([784,10]),name='W')
        variable_summaries(W)
    with tf.name_scope('biases'):
        b=tf.Variable(tf.zeros([10]),name='b')
        variable_summaries(b)
    with tf.name_scope('xw_plus_b'):
        wx_plus_b=tf.matmul(x,W)+b
    with tf.name_scope('softmax'):
        prediction=tf.nn.softmax(wx_plus_b)

#二次代價函式
#loss=tf.reduce_mean(tf.square(y-prediction))
with tf.name_scope('loss'):
    loss=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
    tf.summary.scalar('loss',loss)
#使用梯度下降法
with tf.name_scope('train'):
    train_step=tf.train.GradientDescentOptimizer(0.2).minimize(loss)

#初始化變數
init=tf.global_variables_initializer()
with tf.name_scope('accuracy'):
    with tf.name_scope('correct_prediction'):
        #結果存放在一個布林型列表中
        correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#比較兩個引數大小,相同為true。argmax返回一維張量中最大的值所在的位置
    with tf.name_scope('accuracy'):
        #求準確率
        accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))#將布林型轉化為32位浮點型,再求一個平均值。true變為1.0,false變為0。
        tf.summary.scalar('accuracy',accuracy)

#合併所有的summary
merged=tf.summary.merge_all()

#以下的與結構沒什麼關係
with tf.Session() as sess:
    sess.run(init)
    writer=tf.summary.FileWriter('logs/',sess.graph)#在當前檔案中寫檔案,存的就是圖的結構
    for epoch in range(51):
        for batch in range(n_batch):
            batch_xs,batch_ys=mnist.train.next_batch(batch_size)
            summary,_=sess.run([merged,train_step],feed_dict={x:batch_xs,y:batch_ys})#每訓練一次都統計一次

        writer.add_summary(summary,epoch)

        acc=sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
        print("Iter "+str(epoch)+",Testing Accuracy "+str(acc))

注意:
起初執行時會報錯:InvalidArgumentError: You must feed a value for placeholder tensor ‘inputs/x_input’ 。
引用別人的方法: if you’re using IPython or Jupyter, it’ll cause that problem after running repeatedly.there are two main ways that you could fix that:
A.
tf.reset_default_graph()
call firstly, before your tf operations code
B.
using
with tf.Graph().as_default() as g:
your tf operations code
如果有別的錯誤也可以參考這篇博文:

網路結構:

這裡寫圖片描述

準確率:

這裡寫圖片描述

偏置值分佈圖:

這裡寫圖片描述

權值分佈圖:

這裡寫圖片描述

權值直方圖:

這裡寫圖片描述

如果感覺圖中的點比較少,可以改用下列類似程式碼:

for i in range(2001):
    #m每個批次100個樣本
    batch_xs,batch_xs=mnist.train.next_batch(100)
    summary,_=sess.run([merged,train_step],feed_dict={x:batch_xs,y:batch_xs})
    writer.add_summary(summary,i)
    if i%500==0:
        print(sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}))

通過檢視TensorBoard中各個影象,可以分析出程式是否存在問題,從而便於進一步的優化改進。