1. 程式人生 > >深度學習筆記——TensorFlow學習筆記(三)使用TensorFlow實現的神經網路進行MNIST手寫體數字識別

深度學習筆記——TensorFlow學習筆記(三)使用TensorFlow實現的神經網路進行MNIST手寫體數字識別

本文是TensorFlow學習的第三部分,參考的是《TensorFlow實戰Google深度學習框架》一書,這部分講述的是使用TensorFlow實現的神經網路進行MNIST手寫體數字識別一個例項。

這個例項將第二部分講述的啟用函式、損失函式、優化演算法、正則化等都運用上了。同時,使用TensorFlow中利用變數名稱來建立/獲取變數的機制將前向傳播的過程抽象出來,使得訓練和測試時不需要關心神經網路的結構或是引數;還使用了TensorFlow儲存模型的方法將模型持久化(儲存),以及載入模型進行預測。

總結來說,將神經網路的訓練、測試和使用拆分成了不同的程式,並且將神經網路的前向傳播過程抽象成了一個獨立的庫函式,通過這種方式可以將訓練過程和測試。使用過程解耦合,從而使得整個過程更加靈活。

具體程式碼如下:

神經網路前向傳播過程程式碼(mnist_inference.py):

#coding: utf-8
import tensorflow as tf

#define the variables of nerual network
INPUT_NODE = 784
OUTPUT_NODE = 10
LAYER1_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:
        tf.add_to_collection('losses', regularizer(weights))

    return weights

#define the forward network
def inference(input_tensor, regularizer):
    with tf.variable_scope('layer1'):#宣告第一層神經網路的變數並完成前向傳播過程
        weights = get_weight_variable([INPUT_NODE, LAYER1_NODE], regularizer)
        biases = tf.get_variable("biases", [LAYER1_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([LAYER1_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

訓練過程的程式碼(minist_train.py):
#coding: utf-8
import os

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

import mnist_inference

BATCH_SIZE = 100
LEARNING_RATE_BASE = 0.8
LEARNING_RATE_DECAY = 0.99
REGULARAZTION_RATE = 0.0001
TRAINING_STEPS = 30000
MOVING_AVERAGE_DECAY = 0.99
MODEL_SAVE_PATH = "/home/mpk/TensorFlow_learning/MNIST_MLP/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)
    #直接使用mnist_inference.py中定義的前向傳播過程
    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(logits=y, labels=tf.argmax(y_, 1))
    cross_entropy_mean = tf.reduce_mean(cross_entropy)
    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.initialize_all_variables().run()
#訓練過程
        for i in range(TRAINING_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})
    #每1000輪儲存一次模型
            if i % 1000 == 0:
                print("After %d training step(s), loss on training batch is %g." % (step, loss_value))
                print os.path.join(MODEL_SAVE_PATH, MODEL_NAME)
                saver.save(sess, os.path.join(MODEL_SAVE_PATH, MODEL_NAME), global_step=global_step)

def main(argv=None):
    mnist = input_data.read_data_sets("/tmp/data", one_hot=True)
    train(mnist)

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

訓練結果如下圖所示:



測試過程(mnist_eval.py):
#coding: utf-8
import time
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

import mnist_inference
import minist_train

#every 10 sec load the newest model
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}
#直接呼叫封裝好的函式來計算前向傳播的結果
        y = mnist_inference.inference(x, None)
#計算正確率
        correcgt_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
        accuracy = tf.reduce_mean(tf.cast(correcgt_prediction, tf.float32))
#通過變數重新命名的方式載入模型
        variable_averages = tf.train.ExponentialMovingAverage(minist_train.MOVING_AVERAGE_DECAY)
        variable_to_restore = variable_averages.variables_to_restore()
        saver = tf.train.Saver(variable_to_restore)
#每隔10秒呼叫一次計算正確率的過程以檢測訓練過程中正確率的變化
        while True:
            with tf.Session() as sess:
                ckpt = tf.train.get_checkpoint_state(minist_train.MODEL_SAVE_PATH)
                if ckpt and ckpt.model_checkpoint_path:
                    #load the model
                    saver.restore(sess, 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 steps, validation accuracy = %g" % (global_step, accuracy_score))

                else:
                    print('No checkpoint file found')
                    return
            time.sleep(EVAL_INTERVAL_SECS)

def main(argv=None):
    mnist = input_data.read_data_sets("/tmp/data", one_hot=True)
    evaluate(mnist)

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


測試結果如下圖:


程式碼也可以在我的GitHub獲取:點選開啟連結

相關推薦

no