1. 程式人生 > >Tensorflow學習教程------tensorboard網路執行和視覺化

Tensorflow學習教程------tensorboard網路執行和視覺化

tensorboard可以將訓練過程中的一些引數視覺化,比如我們最關注的loss值和accuracy值,簡單來說就是把這些值的變化記錄在日誌裡,然後將日誌裡的這些資料視覺化。

首先執行訓練程式碼

複製程式碼
#coding:utf-8
import  tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

#載入資料集
mnist = input_data.read_data_sets("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') #輸入標籤
#建立一個簡單的神經網路 784個畫素點對應784個數  因此輸入層是784個神經元 輸出層是10個神經元 不含隱層 
#最後準確率在92%左右
with tf.name_scope('layer'):
    with tf.name_scope('wights'):
        W = tf.Variable(tf.zeros([784,10]),name = 'W') #生成784行 10列的全0矩陣
        variable_summaries(W)
    with tf.name_scope('biases'):
        b = tf.Variable(tf.zeros([1,10]),name='b') 
        variable_summaries(b)
    with tf.name_scope('softmax'):
        prediction = tf.nn.softmax(tf.matmul(x,W)+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)
#使用梯度下降法
#train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
train_step = tf.train.AdamOptimizer(1e-3).minimize(loss) #學習率一般設定比較小 收斂速度快

#初始化變數
init = tf.global_variables_initializer()

#結果存放在布林型列表中
#argmax能給出某個tensor物件在某一維上的其資料最大值所在的索引值
with tf.name_scope('accuracy'):
    with tf.name_scope('correct_prediction'):
        correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(prediction,1))
    with tf.name_scope('accuracy'):
        accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
        tf.summary.scalar('accuracy',accuracy)
#合併所有的summary
merged = tf.summary.merge_all()
with tf.Session() as sess:
    sess.run(init)
    writer = tf.summary.FileWriter('/home/xxx/logs/',sess.graph) #定義記錄日誌的位置
    for epoch in range(50): 
        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) #將summary epoch 寫入到writer
        acc = sess.run(accuracy,feed_dict={x:mnist.test.images, y:mnist.test.labels}) 
        print ("Iter " + str(epoch) + ",Testing Accuracy " + str(acc)) 
複製程式碼

注意我將訓練日誌儲存在 /home/xxx/logs/ 路徑下,開啟終端,輸入以下命令 tensorboard --logdir=/home/xxx/logs/ 如下圖所示

在瀏覽器中輸入127.0.0.1:6006,可以看到視覺化效果,如loss和accuracy的變化折線圖