1. 程式人生 > >TensorFlow學習筆記(6) TensorFlow最佳實踐樣例程式

TensorFlow學習筆記(6) TensorFlow最佳實踐樣例程式

在第三篇中編寫了一個程式來解決MNIST問題,這是一個沒有持久化訓練好的模型。當程式退出時,訓練好的模型就再也無法使用了,這導致得到的模型無法被重用。結合變數管理機制及模型持久化機制,對該程式進行進一步的優化重構。

優化重構之後的程式分為三個:第一個是mnist_inference.py,定義前向傳播的過程及引數;第二個是mnist_train.py,定義神經網路的訓練過程;第三個是mnist_eval.py,定義神經網路的測試過程。

mnist_inference.py

import tensorflow as tf

#定義神經網路結構相關的引數
INPUT_NODE = 784
OUTPUT_NODE = 10
LAYER1_NODE = 500

#定義函式建立或者載入變數,並生成正則化損失加入損失集合
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

#定義神經網路的前向傳播過程
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.1))
        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.1))
        layer2 = tf.matmul(layer1, weights) + biases

    return layer2
無論在訓練時還是測試時,都可以直接呼叫inference這個函式,而不用關心具體的神經網路結構。


mnist_train.py

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
REGULARIZATION_RATE = 0.0001 #描述模型複雜度的正則化項在損失函式中的係數
TRAINING_STEPS = 30000
MOVING_AVERAGE_DECAY = 0.99 #滑動平均衰減率

#模型儲存的路徑和檔名
MODEL_SAVE_PATH = '/mnist_model/'
MODEL_SAVE_NAME = 'mnist_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)

    #直接使用mnist_inference.py中定義的前向傳播結果
    y = mnist_inference.inference(x, regularizer)
    global_step = tf.Variable(0, trainable=False)

    # 生成一個滑動平均的類,並在所有變數上使用滑動平均
    variables_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
    variables_averages_op = variables_averages.apply(tf.trainable_variables())

    # 計算交叉熵及當前barch中的所有樣例的交叉熵平均值,並求出損失函式
    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)
    train_op = tf.group(train_step, variables_averages_op)  # 打包
    with tf.control_dependencies([train_step, variables_averages_op]):
        train_op = tf.no_op(name='train')

    #初始化TF持久化類
    saver = tf.train.Saver()

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        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('After %d training steps, loss on training batch is %g'% (step, loss_value))
                saver.save(sess, os.path.join(MODEL_SAVE_PATH, MODEL_SAVE_NAME), global_step=global_step)

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

if __name__ =='__main__':
    tf.app.run()
在訓練過程中,每1000輪輸出一次在當前訓練batch上損失函式的大小來估計訓練的效果。並且每1000輪儲存一次訓練好的模型,這樣通過一個單獨的測試程式,更加方便地在滑動平均模型上做測試。


mnist_eval.py

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

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)

        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))  # 判斷兩張量的每一維是否相等,相等返回True,不等返回False
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))  # cast將布林值轉化為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)

        #每隔10s呼叫一次計算正確率的過程以檢測訓練過程中正確率的變化
        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:
                    #ckpt.model_checkpoint_path:表示模型儲存的位置,不需要提供模型的名字,它會去檢視checkpoint檔案,看看最新的是誰,叫做什麼。
                    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("MNIST_data", one_hot=True)
    evaluate(mnist)

if __name__ == '__main__':
    tf.app.run()
測試程式每隔10s執行一次,每次執行都是讀取最新儲存地模型,並驗證其正確率。



源自:Tensorflow 實戰Google深度學習框架_鄭澤宇