1. 程式人生 > >TensorFlow筆記之一:MNIST手寫數字識別

TensorFlow筆記之一:MNIST手寫數字識別

     本人剛剛開始接觸深度學習不久,對於tensorflow的瞭解也有限,想通過tensorflow這個框架來學習深度學習及其優化與識別。現在直接進入主題。

    1.手寫識別的介紹:

           MNIST手寫識別在機器學習中就像c語言中Hello World一樣,MNIST資料集是一個機器視覺的資料集,它由幾萬張28X28畫素點構成的手寫數字,我們的任務就是向神經網路輸入由這些畫素點構成的圖片,然後神經網路輸出圖片對應的標籤。

2.用TensorFlow實現手寫識別

        (1)首先匯入手寫資料集MNIST:

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)

       這段程式碼看不懂沒事,它就是TensorFlow內部封裝的一個模組,它會自動從網上下載MNIST資料集。 

然後檢視mnist這個資料集的情況:

print(mnist.train.images.shape, mnist.train.labels.shape)
print(mnist.test.images.shape, mnist.test.labels.shape)
print(mnist.validation.images.shape, mnist.validation.labels.shape)

     其中mnist.train.images返回訓練集的圖片資訊,minist.test返回測試集的圖片資訊,mnist.validation.images返回測試集的圖片資訊。而labels就是圖片標籤:0-9shape就是矩陣資料的維度,比如  [[2,3],[3,5],[1,5]]通過shape運算就返回(3,2)。

以上執行結果為:

      

       說明了訓練集有55000張圖片,每張圖片由28*28個畫素點資料構成。同樣測試集有10000張圖片構成,驗證集由5000個圖片構成。我們在訓練集上訓練資料,在驗證集上檢驗效果並決定何時完成訓練,最後在測試機上檢驗模型的效果。這裡我們要注意標籤label是一個10維向量,這是一種one_hot格式,標籤為0-9之間的數字,如果標籤為5,對應label:[0,0,0,0,0,1,0,0,0,0],就是說標籤為幾就將十位向量的哪一維為位1,其餘都置為0.

       (2) 接下來載入Tensorflow庫  ,並定義x,y兩個Placeholder,所謂Placehoder,初學者可以理解為一種容器,後面我們將會把上面的訓練集資料mnist.train.images及minst.train.labels輸入到x,y中

import tensorflow as tf

#定義兩個placeholder
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])


       (3)然後建立一層簡單的神經網路: 

 W = tf.Variable(tf.zeros([784,10]))
 b = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x,W)+b)
       這裡的引數x將會是輸入的圖片資料即為[None,784],None就是圖片的數量,因為我們訓練的時候並不是一張一張圖片輸入的,因為一張一張輸入的效率低,而且會因為一張噪音圖片的對整個網路造成巨大影響,正確的訓練方法應該是將100張圖片組成的資料集[100,784]輸入神經網路進行訓練(當然,這裡的100也可以是其他數值)。然後得到神經網路的輸出prediction,這裡的prediction就是標籤y的預測值,也是一個10維的向量,例如[0.12,0.22,0.21,0.86,0.33,0.01,0.81,0.15,0.54,0.13]

       (4)定義二次損失函式和梯度優化模型,我們的目的就是通過更新神經網路引數W,b來讓loss的最小,而更新W,b的操作就是train_step.

#二次代價函式
loss = tf.reduce_mean(tf.square(y-prediction))
#使用梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)


       (5)計算準確率:

       這裡的tf.argmax(y,1),tf.argmax(prediction,1)就是計算10維向量y及prediction中元素的最大值,也就是說預測的標籤和實際標籤相等時tf.equal返回真,否則返回假。最終預測正確的資訊被儲存到correct_prediction布林型列表中,在通過tf.cast轉化為float型,然後通過tf.reduce_mean求平均求出準確率。

#結果存放在一個布林型列表中
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#argmax返回一維張量中最大的值所在的位置
#求準確率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))


     
         (6)接著就進入正式訓練了:

     首先通過init初始化變數,接著for迴圈訓練40個回合。batch_size為每個批次的大小,

n_batch為批次數。在每次訓練一個回合後計算出測試集的準確率acc,並輸出。



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

with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    for epoch in range(40):
        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))


 


        以上是程式的執行的結果,可以看到最終準確率為91.94%,這並不是很高的準確率,但卻是一個入門的經典例子,後面我們將會講到如何提高準確率.

        全部程式碼為:

# coding: utf-8

# 載入資料集
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)


print(mnist.train.images.shape, mnist.train.labels.shape)
print(mnist.test.images.shape, mnist.test.labels.shape)
print(mnist.validation.images.shape, mnist.validation.labels.shape)

import tensorflow as tf

# 定義兩個placeholder
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])

# 建立一個簡單的神經網路
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x, W) + b)

# 二次代價函式
loss = tf.reduce_mean(tf.square(y - prediction))
# 使用梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)

#結果存放在一個布林型列表中
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#argmax返回一維張量中最大的值所在的位置
#求準確率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
# 每個批次的大小
batch_size = 100
# 計算一共有多少個批次
n_batch = mnist.train.num_examples // batch_size

with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    for epoch in range(40):
        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))