前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >持久化的基于 L2 正则化和平均滑动模型的 MNIST 手写数字识别模型

持久化的基于 L2 正则化和平均滑动模型的 MNIST 手写数字识别模型

作者头像
演化计算与人工智能
发布2020-08-14 14:12:30
3600
发布2020-08-14 14:12:30
举报

参考文献Tensorflow 实战 Google 深度学习框架[1]实验平台: Tensorflow1.4.0 python3.5.0MNIST 数据集[2]将四个文件下载后放到当前目录下的 MNIST_data 文件夹下

定义模型框架与前向传播

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))
    # 如果使用正则化方法会将该张量加入一个名为'losses'的集合
    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.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

模型训练与模型框架及参数持久化

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

# 配置神经网络参数
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_NAME = "mnist_model"


def train(mnist):
    # 定义输入输出placeholder
    x = tf.placeholder(tf.float32, [None, mnist_inference.INPUT_NODE], name='x-input')  # 可以直接引用mnist_inference中的超参数
    y_ = tf.placeholder(tf.float32, [None, mnist_inference.OUTPUT_NODE], name='y-input')
    # 定义L2正则化器
    regularizer = tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE)
    # 在前向传播时使用L2正则化
    y = mnist_inference.inference(x, regularizer)
    global_step = tf.Variable(0, trainable=False)
    # 在可训练参数上定义平均滑动模型
    variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
    # tf.trainable_variables()返回的是图上集合GraphKeys.TRAINABLE_VARIABLES中的元素。这个集合中的元素是所有没有指定trainable=False的参数
    variables_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)
    # 在交叉熵函数的基础上增加权值的L2正则化部分
    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')
    # 在反向传播的过程中,不仅更新神经网络中的参数还更新每一个参数的滑动平均值
    train_op = tf.group(train_step, variables_averages_op)
    # 定义Saver模型保存器
    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})
            # 每1000轮保存一次模型
            if i%1000 == 0:
                # 输出当前的训练情况,这里只输出了模型在当前训练batch上的损失函数大小
                # 通过损失函数的大小可以大概了解训练的情况,
                # 在验证数据集上的正确率信息会有一个单独的程序来生成
                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)


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


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

模型恢复与评价测试集上的效果

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)
        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)
        variables_to_restore = variable_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)
                    # 通过文件名得到模型保存是迭代的轮数
                    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))
                else:
                    print('No checkpoint file found')
                    return
            time.sleep(EVAL_INTERVAL_SECS)
            # 每次运行都是读取最新保存的模型,并在MNIST验证数据集上计算模型的正确率
            # 每隔EVAL_INTERVAL_SECS秒来调用一侧计算正确率的过程以检验训练过程中的正确率变化


# ###  主程序
def main(argv=None):
    mnist = input_data.read_data_sets("./MNIST_data", one_hot=True)
    evaluate(mnist)


if __name__ == '__main__':
    main()

# After 29001 training step(s), validation accuracy = 0.9854

参考资料

[1]Tensorflow实战Google深度学习框架: https://github.com/caicloud/tensorflow-tutorial/tree/master/Deep_Learning_with_TensorFlow/1.4.0

[2]MNIST数据集: http://yann.lecun.com/exdb/mnist/

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 DrawSky 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 定义模型框架与前向传播
  • 模型训练与模型框架及参数持久化
  • 模型恢复与评价测试集上的效果
    • 参考资料
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档