基於TensorFlow的mnist手寫數字圖片識別

在學習了BP算法後在mnist數據集上做了練習,特在此總結。
- mnist
包含7萬張手寫黑白數字圖片,每張圖片是28*28像素,純黑像素值0,純白1,數據集標籤長度是10的一維數組,包含對應數字出現的概率。通過input_data函數加載數據集,是4個壓縮包,包含訓練集50000張,驗證集5000張和測試集10000張,One-hot=True採用獨熱碼的形式加載。

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('./data/',one_hot=True)
Extracting ./data/train-images-idx3-ubyte.gz
Extracting ./data/train-labels-idx1-ubyte.gz
Extracting ./data/t10k-images-idx3-ubyte.gz
Extracting ./data/t10k-labels-idx1-ubyte.gz
mnist.train.num_examples
55000
mnist.validation.num_examples
5000
mnist.test.num_examples
10000
mnist.train.images[0].shape
(784,)
mnist.train.labels[0]
array([0., 0., 0., 0., 0., 0., 0., 1., 0., 0.])
batch_size = 200
xs,ys = mnist.train.next_batch(batch_size)
print(xs.shape)
print(ys.shape)
(200, 784)
(200, 10)

通過next_batch函數從訓練集中隨機抽取batch_size個樣本喂入神經網絡,並將樣本像素值和標籤傳給xs,ys。
- 模塊化搭建網絡
TensorFlow框架方便我們模塊化搭建神經網絡,思考:我們想通過BP算法實現手寫數字圖片識別,需要三個步驟:前向傳播,反向傳播,測試。爲了提高模型的泛化性能,加入優化方法。
- forward
前向傳播中,我們需要完成定義輸入、獲得參數、獲得輸出:

import tensorflow as tf
INPUT_NODE = 784
OUTPUT_NODE = 10
LAYER1_NODE = 500

我們構建了2層NN,隱藏層有500個神經元,輸入層有784個神經元,代表輸入的每張圖片的784個像素,輸出層有10個神經元,代表數據集的標籤。

def get_weight(shape, regularizer):
    w = tf.Variable(tf.truncated_normal(shape,stddev=0.1))#除去較大離散點的正態分佈
    if regularizer != None: tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(regularizer)(w))
    return w

定義get_weight()函數用來對權重w進行設定,傳入參數是w的size和正則化係數,初始化權重後將L2正則化損失加入到總損失中。

def get_bias(shape):  
    b = tf.Variable(tf.zeros(shape))  
    return b
def forward(x, regularizer):
    w1 = get_weight([INPUT_NODE, LAYER1_NODE], regularizer)
    b1 = get_bias([LAYER1_NODE])
    y1 = tf.nn.relu(tf.matmul(x, w1) + b1)#激活函數使用relu:y=max(x,0)

    w2 = get_weight([LAYER1_NODE, OUTPUT_NODE], regularizer)
    b2 = get_bias([OUTPUT_NODE])
    y = tf.matmul(y1, w2) + b2
    return y

參數偏執設定和前向傳播過程,傳入參數x爲輸入,返回預測結果y。
- Backward
反向傳播完成訓練,參數優化。

def backward(mnist):
    #輸入佔位
    x = tf.placeholder(tf.float32, [None, mnist_forward.INPUT_NODE])
    y_ = tf.placeholder(tf.float32, [None, mnist_forward.OUTPUT_NODE])
    #預測值由前向傳播得到
    y = mnist_forward.forward(x, REGULARIZER)
    global_step = tf.Variable(0, trainable=False)

    #交叉熵+softmax,考慮正則化係數
    ce = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.argmax(y_, 1))
    cem = tf.reduce_mean(ce)
    loss = cem + tf.add_n(tf.get_collection('losses'))

    #指數衰減學習率
    learning_rate = tf.train.exponential_decay(
        LEARNING_RATE_BASE,
        global_step,
        mnist.train.num_examples / BATCH_SIZE, 
        LEARNING_RATE_DECAY,
        staircase=True)

    #梯度下降學習方法
    train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)

    #滑動平均,實現和訓練過程同步
    ema = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
    ema_op = ema.apply(tf.trainable_variables())
    with tf.control_dependencies([train_step, ema_op]):
        train_op = tf.no_op(name='train')

    #實例化模型對象,用於後續保存
    saver = tf.train.Saver()

    #with結構初始化所有參賽
    with tf.Session() as sess:
        init_op = tf.global_variables_initializer()
        sess.run(init_op)

        for i in range(STEPS):
            xs, ys = mnist.train.next_batch(BATCH_SIZE)
            _, loss_value, step = sess.run([train_op, loss, global_step], feed_dict={x: xs, y_: ys})

            #反向傳播過程中每隔一定輪數保存模型,併產生3個文件(圖結構.mata,當前參數名.index,當前參數.data
             if i % 1000 == 0:
                print("After %d training step(s), loss on training batch is %g." % (step, loss_value))
                saver.save(sess, os.path.join(MODEL_SAVE_PATH, MODEL_NAME), global_step=global_step)#將訓練模型和訓練輪數保存到指定路徑

在反向傳播中,先對輸入x和實際標籤y_佔位,前向傳播得到預測值,優化參數,實例化模型用於保存,開啓會話先對參數進行初始化,訓練模型更新參數和損失函數,一定輪數打印和保存模型。
其中,參數優化用來提高模型的泛化能力,包括交叉熵+softmax,指數衰減學習率,滑動平均,正則化。
指數衰減學習率使學習率隨着訓練輪數動態變化,需要提前賦值學習率基數和學習衰減率。
滑動平均用來得到在一定時間內所有參數,w,b的平均值,提前賦值平均衰減率。
學習方法是梯度下降,每次喂入batch_size個訓練樣本最小化損失函數。
此時,我們的神經網絡模型已經搭建好了,若想用於測試,需要定義測試函數用來加載模型。
- Test

def test(mnist):
    #將當前圖設置爲默認圖並保存,與with使用,用於將已定義好的NN復現
    with tf.Graph().as_default() as g:
        x = tf.placeholder(tf.float32, [None, mnist_forward.INPUT_NODE])
        y_ = tf.placeholder(tf.float32, [None, mnist_forward.OUTPUT_NODE])#標籤真實值
        y = mnist_forward.forward(x, None)
        #加載已保存的滑動平均值
        ema = tf.train.ExponentialMovingAverage(mnist_backward.MOVING_AVERAGE_DECAY)
        ema_restore = ema.variables_to_restore()
        saver = tf.train.Saver(ema_restore)
        #準確率評估
        #y是batch_size個數據的預測結果,大小[batch_size,10],argmax()返回最大值元素對應索引值
        #通過tf.equal()函數與實際標籤張量對比,相等返回true,不等返回false,再通過cast函數將布爾型轉爲實數
        #通過reduce_mean()求平均值,得到本組數據在NN上的準確率
        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

        while True:
            with tf.Session() as sess:
                #加載NN模型
                ckpt = tf.train.get_checkpoint_state(mnist_backward.MODEL_SAVE_PATH)
                #若模型和指定路徑存在,則將模型加載到會話中
                if ckpt and ckpt.model_checkpoint_path:
                    saver.restore(sess, ckpt.model_checkpoint_path)
                    global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]#恢復保存時運行的輪數
                    accuracy_score = sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})
                    print("After %s training step(s), test accuracy = %g" % (global_step, accuracy_score))
                else:
                    print('No checkpoint file found')
                    return
            time.sleep(TEST_INTERVAL_SECS)

其中,TensorFlow是基於計算圖的操作,我們在圖中添加operation作爲節點,就是對張量的計算,在所有節點添加完成後,開啓session,完成對指定節點的計算。在test函數中,將當前圖設置爲默認圖,在默認圖中添加張量輸入值、標籤、預測值、加載參數和輸出模型準確率,with session開啓會話完成對當前圖的計算:加載保存模型,計算準確率。
截圖運行backward和test程序結果:
這裏寫圖片描述
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章