MNIST數字識別TensorFlow最佳實現樣例

1. 內容提要

本文給出一個完整的TensorFlow訓練的神經網絡模型程序來解決MNIST問題。並引入TensorFlow模型持久化機制,而且,將整個模型分爲訓練和測試部分,實現模塊化

此外,此神經網絡運用了多種優化機制:正則化、衰減學習率、滑動平均

涉及到知識點:

  • 正則化
  • 衰減學習率
  • 滑動平均
  • TensorFlow神經網絡模型持久化
  • 前向傳播
  • 梯度下降(反向傳播)

整個代碼分爲3個程序:

  • mnist_inference.py:定義了前向傳播過程以及網絡參數
  • mnist_train.py : 定義了神經網絡的訓練過程
  • mnist_eval.py : 定義了測試過程

下面分別介紹三個程序:

2. mnist_inference.py前向傳播

import tensorflow as tf

# 定義相關參數
INPUT_NODE = 784
OUTPUT_NODE = 10
LAYEER1_NODE = 500

# 通過tf.get_variable函數來獲取變量
def get_weight_variable(shape,regularizer):
    weights = tf.get_variable(
        "weights",shape,
        initializer=tf.truncated_normal_initializer(stddev=0.1)
    )
    if regularizer!=None:
        # 當加入正則化時,將當前變量的正則化損失加入名字爲losses的集合。
        # 這裏使用了add_to_collection函數將一個張量加入一個集合,
        # 這個集合的名稱爲Losses,這是自定義的集合,不在TensorFlow自動管理的集合列表中
        tf.add_to_collection("losses",regularizer(weights))
    return weights

# 定義前向傳播過程
def inference(input_tensor,regularizer):

    with tf.variable_scope('layer1'):
        weights = get_weight_variable(
            [INPUT_NODE,LAYEER1_NODE],regularizer
        )
        biases = tf.get_variable(
            "biases",[LAYEER1_NODE],
            initializer=tf.constant_initializer(0.0)
        )
        layer1 = tf.nn.relu(tf.matmul(input_tensor, weights) + biases)

    with tf.variable_scope('layer2'):
        weights = get_weight_variable(
            [LAYEER1_NODE,OUTPUT_NODE],regularizer
        )
        biases = tf.get_variable(
            "biases",[OUTPUT_NODE],
            initializer=tf.constant_initializer(0.0)
        )
        layer2 = tf.matmul(layer1, weights) + biases
    return layer2

前向傳播,定義了兩層神經網絡,很簡單。

3. mnist_train.py訓練過程

import os
import tensorflow as tf
# 加載定義好的前向傳播模塊
import mnist_inference

# 加載數據集
from tensorflow.examples.tutorials.mnist import input_data

# 配置網絡參數
BATCH_SIZE = 100
LEARNING_RATE_BASE = 0.8
LEARNING_RATE_DECAY = 0.99
REGULARAZTION_RATE = 0.001
TRAINING_STEPS = 20000
MOVING_AVERAGE_DECAY = 0.99
# 模型保存的路徑和文件名
MODEL_SAVE_PATH = "E:/pycharm2016_3_2/pycharmWorkplace/tensorflow_test/model"
MODEL_NAME = 'model.ckpt'

def train(mnist):
    x = tf.placeholder(
        tf.float32,[None,mnist_inference.INPUT_NODE],name='x-input'
    )
    y_ = tf.placeholder(
        tf.float32,[None,mnist_inference.OUTPUT_NODE],name='y-input'
    )
    # 正則化
    regularizer = tf.contrib.layers.l2_regularizer(REGULARAZTION_RATE)
    # 直接使用前向傳播算法
    y = mnist_inference.inference(x,regularizer)
    # 記錄迭代的步數
    global_step = tf.Variable(0,trainable=False)
    # 滑動平均操作
    variable_averages = tf.train.ExponentialMovingAverage(
        MOVING_AVERAGE_DECAY,global_step
    )
    variable_averages_op = variable_averages.apply(tf.trainable_variables())
    # 損失
    cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=tf.argmax(y_,1),logits=y)
    # 平均損失
    cross_entropy_mean = tf.reduce_mean(cross_entropy)
    # 加上正則化的損失(見前向傳播tf.add_to_collection("losses",regularizer(weights)))-->最終損失
    loss = cross_entropy_mean + 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
    )
    # 訓練,梯度下降
    train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss,global_step=global_step)
    with tf.control_dependencies([train_step,variable_averages_op]):
        train_op = tf.no_op(name='train')

    # 初始化tensorflow持久化類
    saver = tf.train.Saver()
    with tf.Session() as sess:
        # 初始化話參數
        tf.global_variables_initializer().run()
        # 訓練
        for i in range(TRAINING_STEPS):
            # 加載一個批次數據
            xs,ys = mnist.train.next_batch(BATCH_SIZE)
            # run
            _,loss_value,step = sess.run([train_op,loss,global_step],feed_dict={x:xs,y_:ys})
            # 每隔1000步統計一下損失率
            if i% 1000 == 0:
                # %g 浮點數字(根據值的大小採用%e或%f),%e科學計數法,%f浮點數
                print('after %d training steps, loss on training batch is %g.' % (step,loss_value))
                # 每隔1000步保存一次模型
                saver.save(
                    sess,os.path.join(MODEL_SAVE_PATH,MODEL_NAME),global_step=global_step
                )

def main(argv=None):
    # 這個路徑../mnist/data可以隨便寫,沒有數據的話它會自動下載
    mnist = input_data.read_data_sets('../mnist/data',one_hot=True)
    train(mnist)

if __name__ == '__main__':
    tf.app.run()

注意點:

  • windows下,保存模型的路徑必須是絕對路徑,否則報錯。親測是醬紫。保存後的模型如下:
    保存的模型
    這裏是每隔1000步保存一次,tensorflow默認設置是最多保存5個,如果到第6個,則把第一個刪了。因此,最終只會保留最後5個最新的模型數據。

    • 對於 tf.add_n(tf.get_collection('losses')),就是把保存到集合中的losses加起來而已。tf.add_n()的用法參考這篇文章
    • 這段代碼:
    with tf.control_dependencies([train_step,variable_averages_op]):
        train_op = tf.no_op(name='train')

就是將訓練滑動平均兩個操作依賴到一起而已。具體參考這篇文章

4. mnist_eval.py測試過程

import time
import tensorflow as tf

from tensorflow.examples.tutorials.mnist import input_data

# 加載mnist_inference.py和mnist_train.py中定義的常量和函數
import mnist_inference
import mnist_train

# 每10秒加載一次模型
EVAL_INTERVAL_SECS = 10

def evaluate(mnist):
    with tf.Graph().as_default() as g:
        # 定義輸入輸出
        x = tf.placeholder(tf.float32,[None,mnist_inference.INPUT_NODE],name='x-input')
        y_= tf.placeholder(tf.float32,[None,mnist_inference.OUTPUT_NODE],name='y-input')
        # 真正的測試數據
        validate_feed = {
            x:mnist.validation.images,
            y_:mnist.validation.labels
        }
        # 前向傳播,得到預測值[?,10]
        y = mnist_inference.inference(x,None)

        # 預測值,取前15個爲例
        predict = tf.argmax(y,1)[0:15]
        # 真實值
        real = tf.argmax(y_,1)[0:15]
        # 正確率
        correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
        # tf.reduce_mean求平均值
        accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

        # 加載滑動平均操作
        variables_averages = tf.train.ExponentialMovingAverage(mnist_train.MOVING_AVERAGE_DECAY)
        variables_to_restore = variables_averages.variables_to_restore()
        saver = tf.train.Saver(variables_to_restore)# 得到持久化類

        while True:
            with tf.Session() as sess:
                # tf.train.get_checkpoint_state函數會通過checkpoint文件自動
                # 找到目錄中最新模型的文件名
                ckpt = tf.train.get_checkpoint_state(mnist_train.MODEL_SAVE_PATH)
                if ckpt and ckpt.model_checkpoint_path:
                    # 加載模型
                    saver.restore(sess,ckpt.model_checkpoint_path)
                    # 通過文件名得到保存時迭代的輪數
                    print(ckpt.model_checkpoint_path)# 打印一下文件名
                    # 字符串操作,截取到步數
                    global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
                    # 計算準確率
                    accuracy_score = sess.run(accuracy,feed_dict=validate_feed)
                    print('after %s training step(s), validation accuracy = %g '%(global_step,accuracy_score))
                    # 計算預測值,取前15個值作爲示範
                    prediction = sess.run(predict, feed_dict=validate_feed)
                    # 真實值,與預測值對照
                    real_value  = sess.run(real,feed_dict=validate_feed)
                    print('after %s training step(s), validation prediction is '%(global_step),prediction,' real value is',real_value)
                else:
                    print('no checkpoint file found')
                    return

            time.sleep(EVAL_INTERVAL_SECS)

def main(argv=None):
    # 這個路徑../mnist/data可以隨便寫,沒有數據的話它會自動下載
    mnist = input_data.read_data_sets('../mnist/data',one_hot=True)
    evaluate(mnist)

if __name__ == '__main__':
    tf.app.run()

運行結果:
測試過程運行結果
由結果可見,每次加載的模型都是最新的模型,也就是第訓練了19001步得到的模型。因爲我這個程序是訓練文件執行完後才執行的測試文件,所以它每次都加載最後一次保存的模型了。

實際上,這個程序應該是訓練和測試同時運行的。這樣就可以看出每隔10秒種,測試的不同結果了。

參考文章
https://blog.csdn.net/PKU_Jade/article/details/73498753
https://blog.csdn.net/uestc_c2_403/article/details/72808839
《Tensorflow+實戰Google深度學習框架》

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