Tensorflow之MNIST的最佳實踐思路總結


Tensorflow之MNIST的最佳實踐思路總結

  在上兩篇文章中已經總結出了深層神經網絡常用方法和Tensorflow的最佳實踐所需要的知識點,如果對這些基礎不熟悉,可以返回去看一下。在《Tensorflow:實戰Google深度學習框架》這本書在第五章中給出了MNIST的例子代碼,源碼可以去代碼庫中查看https://github.com/caicloud/tensorflow-tutorial,在這里寫一下對這個例子的思路總結(最佳實踐):
  為了擴展性變得更好,這里將整個程序分為三個文件,分別如下:
  注意:在編寫該程序時,可以看幾遍代碼熟悉一下,再只看思路不要去看代碼,編寫自己理解的MNIST

  • 前向傳播過程以及神經網絡的參數封裝在一個文件中,在這里是mnist_inference.py。

1、定義神經網絡的前向傳播過程,也就是一個方法。
2、在方法中分別聲明第一層與第二層神經網絡的變量(權重和偏置項)並完成前向傳播過程(舉證的乘法),由於正則化需要傳入邊上的權重,所以需要注意是使用tf.add_to_collection去添加正則損失。
3、根據所需,定義相關參數(用到了再定義)。
4、返回結果值。

代碼如下:

import tensorflow as tf
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))
    # 當給出了正則化生成函數時,將當前變量的正則化損失加入名字為losses的集合。
    # 在這里使用了add_to_collection函數將一個張量加入一個集合,而這個集合的名稱為losses。
    # 這是自定義的集合,不在Tensorflow自動管理的集合列表中。
    if regularizer != None:
        tf.add_to_collection('losses', regularizer(weights))
    return weights
# 定義神經網絡的前向傳播過程。
def inference(input_tensor, regularizer):
    # 聲明第一層神經網絡的變量並完成前向傳播過程
    with tf.variable_scope('layer1'):
        # 這里使用tf.get_variable或tf.Variable沒有本質區別,因為在訓練或是測試中沒有在同一個程序中多次調用這個函數。
        # 如果在同一個程序中多次調用,在第一次調用之后需要將reuse參數置為True。
        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
  • 訓練程序,mnist_train.py

1、定義訓練方法,輸入的x、y_、損失類
2、調用inference的前向傳播。
3、按順序定義滑動平均、損失函數、設置學習率的梯度下降
4、使用tf.control_dependencies來一次性完成每過一遍數據需要通過反向傳播來更新神經網絡參數以及更新每一個參數的滑動平均值這兩個操作。
5、初始化、跑測試並保存1000次的模型
6、定義主類得到mnist並調用train方法。

代碼如下:

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 = "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(REGULARIZATION_RATE)
    y = mnist_inference.inference(x, regularizer)
    global_step = tf.Variable(0, trainable=False)
    
    # 定義損失函數、學習率、滑動平均操作以及訓練過程。
    variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
    variables_averages_op = variable_averages.apply(tf.trainable_variables())
    cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(y, 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,
        staircase=True)
    train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
    with tf.control_dependencies([train_step, variables_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)
            _, loss_value, step = sess.run([train_op, loss, global_step], feed_dict={x: xs, y_: ys})
            if i % 1000 == 0:
                print(step,loss_value)
                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("dataset/", one_hot=True)
    train(mnist)
if __name__ == '__main__':
    tf.app.run()
  • 測試程序,mnist_eval.py

1、定義訓練方法,輸入的x、y_、損失類
2、調用inference的前向傳播。
3、獲取正確率
4、加載模型
5、獲得最新保存的模型並測試
6、定義主類得到mnist並調用train方法。

代碼如下:

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

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}
        # 直接通過調用封裝好的函數來計算前向傳播的結果。
        # 因為測試時不關注正則損失的值,所以這里用於計算正則化損失的函數被設置為None。
        y = mnist_inference.inference(x, None)

        # 使用前向傳播的結果計算正確率。
        # 如果需要對未知的樣例進行分類,那么使用tf.argmax(y, 1)就可以得到輸入樣例的預測類別了。
        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

        # 通過變量重命名的方式來加載模型,這樣在前向傳播的過程中就不需要調用求滑動平均的函數來獲取平局值了。
        # 這樣就可以完全共用mnist_inference.py中定義的前向傳播過程,
		# 加載模型的時候將影子變量直接映射到變量的本身
        variable_averages = tf.train.ExponentialMovingAverage(mnist_train.MOVING_AVERAGE_DECAY)
        variable_to_restore = variable_averages.variables_to_restore()
        saver = tf.train.Saver(variable_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)
                    # 通過文件名得到模型保存時迭代的輪數
                    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 = %f" % (global_step, accuracy_score))
                else:
                    print("No checkpoint file found")
                    return
        	#每隔EVAL_INTERVAL_SECS秒調用一次計算正確率的過程以檢測訓練過程中正確率的變化
            time.sleep(EVAL_INTERVAL_SECS)
def main(argv=None):
    mnist = input_data.read_data_sets("dataset/", one_hot=True)
    evaluate(mnist)
if __name__ == '__main__':
    tf.app.run()


免責聲明!

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



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