Tensorflow可視化MNIST手寫數字訓練


【簡述】

  我們在學習編程語言時,往往第一個程序就是打印“Hello World”,那么對於人工智能學習系統平台來說,他的“Hello World”小程序就是MNIST手寫數字訓練了。MNIST是一個手寫數字的數據集,官網是Yann LeCun's website。數據集總共包含了60000行的訓練數據集(mnist.train)和10000行的測試數據集(mnist.test),每一個數字的大小為28*28像素。通過利用Tensorflow人工智能平台,我們可以學習到人工智能學習平台是如何通過數據進行學習的。

【數據准備】

  下載mnist數據集,和mnist_10k_sprite.png圖片,分別放在MNIST_data文件夾和projector/data文件夾下。

 

【代碼】

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.contrib.tensorboard.plugins import projector

#載入數據集
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
#運行次數
max_steps = 1001
#圖片數量
image_num = 3000
#文件路徑
DIR = "E:/Github/TensorFlow/trunk/Test/"

#定義會話
sess = tf.Session()

#載入圖片
embedding = tf.Variable(tf.stack(mnist.test.images[:image_num]), trainable=False, name='embedding')

#參數概要
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'):
    #這里的none表示第一個維度可以是任意的長度
    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)

with tf.name_scope('layer'):
    #創建一個簡單神經網絡
    with tf.name_scope('weights'):
        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('wx_plus_b'):
        wx_plus_b = tf.matmul(x,W) + b
    with tf.name_scope('softmax'):    
        prediction = tf.nn.softmax(wx_plus_b)

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.5).minimize(loss)

#初始化變量
sess.run(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))#argmax返回一維張量中最大的值所在的位置
    with tf.name_scope('accuracy'):
        #求准確率
        accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))#把correct_prediction變為float32類型
        tf.summary.scalar('accuracy',accuracy)

#產生metadata文件
if tf.gfile.Exists(DIR + 'projector/projector/metadata.tsv'):
    tf.gfile.DeleteRecursively(DIR + 'projector/projector/metadata.tsv')
with open(DIR + 'projector/projector/metadata.tsv', 'w') as f:
    labels = sess.run(tf.argmax(mnist.test.labels[:],1))
    for i in range(image_num):   
        f.write(str(labels[i]) + '\n')        
        
#合並所有的summary
merged = tf.summary.merge_all()   


projector_writer = tf.summary.FileWriter(DIR + 'projector/projector',sess.graph)
saver = tf.train.Saver()
config = projector.ProjectorConfig()
embed = config.embeddings.add()
embed.tensor_name = embedding.name
embed.metadata_path = DIR + 'projector/projector/metadata.tsv'
embed.sprite.image_path = DIR + 'projector/data/mnist_10k_sprite.png'
embed.sprite.single_image_dim.extend([28,28])
projector.visualize_embeddings(projector_writer,config)

for i in range(max_steps):
    #每個批次100個樣本
    batch_xs,batch_ys = mnist.train.next_batch(100)
    run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
    run_metadata = tf.RunMetadata()
    sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys},options=run_options,run_metadata=run_metadata)
    summary = sess.run(merged,feed_dict={x:batch_xs,y:batch_ys},options=run_options,run_metadata=run_metadata)
    projector_writer.add_run_metadata(run_metadata, 'step%03d' % i)
    projector_writer.add_summary(summary, i)
    
    if i%100 == 0:
        acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
        print ("Iter " + str(i) + ", Testing Accuracy= " + str(acc))

saver.save(sess, DIR + 'projector/projector/a_model.ckpt', global_step=max_steps)
projector_writer.close()
sess.close()
View Code

 【運行】

  直接運行代碼

【可視化界面】

  1、在cmd命令行輸入tensorboard --logdir=progector文件夾路徑;

  2、在瀏覽器打開http://localhost:6006路徑即可查看可視化效果。

 

源碼獲取方式,關注公總號RaoRao1994,查看往期精彩-所有文章,即可獲取資源下載鏈接

更多資源獲取,請關注公總號RaoRao1994


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM