在TensorFlow上使用LeNet-5模型识别MNIST数据

完整代码可在https://github.com/TimeIvyace/MNIST-TensorFlow.git中下载。文件夹为train_improved3,文件夹中一共三个py程序,mnist_inference.py定义前向传播的过程以及神经网络中的参数,mnist_train.py用于训练和mnist_eval.py用于测试。
注意:使用代码需要修改MNIST数据集存储位置以及卷积网络存储位置。

此代码中的LeNet-5网络为改进版,依然为7层结构,但是使用的第一个卷积层过滤器尺寸为5*5*32,第二个卷积层过滤器尺寸为5*5*64。
注意:训练网络的学习率不宜太高,容易结果发散。

mnist_inference.py : 定义前向传播的过程以及神经网络中的参数

# -*- coding:utf-8 -*-

#定义前向传播的过程以及神经网络中的参数

import tensorflow as tf

INPUT_NODE = 784  #输入层的节点数,图片为28*28,为图片的像素
OUTPUT_NODE = 10   #输出层的节点数,等于类别的数目,需要区分0-9,所以为10类

IMAGE_SIZE = 28
NUM_CHANNELS = 1 #处理的图像深度
NUM_LABELS = 10

# 第一层卷积层的尺寸和深度
CONV1_DEEP = 32
CONV1_SIZE = 5
# 第二层卷积层的尺寸和深度
CONV2_DEEP = 64
CONV2_SIZE = 5
# 全连接层的节点个数
FC_SIZE = 512


# 定义卷积神经网络的前向传播过程,train用于区分训练过程和测试过程
# 增加了dropout方法,进一步提高模型可靠性防止过拟合,dropout只在训练时使用
def inference(input_tensor, train, regularizer):
    # 声明第一层卷积层的变量并实现前向传播,通过不同的命名空间来隔离不同层的变量
    # 让每一层中的变量命名只需要考虑在当前层的作用,不需要考虑重名
    # 因为卷积层输入为28*28*1,使用全0填充
    with tf.variable_scope('layer1-conv1'):
        conv1_weight = tf.get_variable("weight", [CONV1_SIZE, CONV1_SIZE, NUM_CHANNELS, CONV1_DEEP],
                                       initializer=tf.truncated_normal_initializer(stddev=0.1))
        conv1_biases = tf.get_variable("bias", [CONV1_DEEP], initializer=tf.constant_initializer(0.0))

        # 使用边长为5,深度为32的过滤器,过滤器移动的步长为1,且使用全0填充
        conv1 = tf.nn.conv2d(input_tensor, conv1_weight, [1, 1, 1, 1], padding='SAME')
        relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1_biases))

    # 实现第二层池化层的前向传播过程,选用最大池化,过滤器边长为2,步长2,全0填充
    # 池化层的输入是上层卷积层的输出,也就是28*28*32的矩阵,输出为14*14*32的矩阵
    with tf.name_scope('layer2-pool1'):
        pool1 = tf.nn.max_pool(relu1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

    # 声明第三层卷积层前向传播过程,这一层输入为14*14*32,输出为14*14*64
    with tf.variable_scope('layer3-conv2'):
        conv2_weight = tf.get_variable("weight", [CONV2_SIZE, CONV2_SIZE, CONV1_DEEP, CONV2_DEEP],
                                       initializer=tf.truncated_normal_initializer(stddev=0.1))
        conv2_biases = tf.get_variable("bias", [CONV2_DEEP], initializer=tf.constant_initializer(0.0))

        # 使用边长为5,深度为64的过滤器,步长为1,全0填充
        conv2 = tf.nn.conv2d(pool1, conv2_weight, [1, 1, 1, 1], padding='SAME')
        relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_biases))

    # 实现第四层池化层的前向传播过程,与第二层结构一样,输入为14*14*64,输出为7*7*64
    with tf.name_scope('layer4-pool2'):
        pool2 = tf.nn.max_pool(relu2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

    # 将第四层池化层的输出转化为第五层全连接的输入格式,需要将7*7*64拉成一个向量
    # pool2.get_shape可以得到第四层输出矩阵的维度
    # 每一层神经网络的输入输出都为一个batch的矩阵,所以这里得到的维度也包含了一个batch中数据的个数
    pool_shape = pool2.get_shape().as_list()
    # 计算将矩阵拉直成向量之后的长度,这个长度是矩阵长度以及深度的乘积
    # pool_shape[0]为一个batch中数据的个数,[1][2]分别为长宽,[3]为深度
    nodes = pool_shape[1] * pool_shape[2] * pool_shape[3]

    # 通过tf.reshape函数将第四层的输出变成一个batch的向量
    reshaped = tf.reshape(pool2, [pool_shape[0], nodes])

    # 声明第五层全连接层的前向传播过程。输入为拉直的向量,长度3136,输出512的向量
    # 引入dropout,在训练时会将部分节点的输出改为0,一般只在全连接层使用
    with tf.variable_scope('layer5-fc1'):
        fc1_weight = tf.get_variable("weight", [nodes, FC_SIZE],
                                     initializer=tf.truncated_normal_initializer(stddev=0.1))
        # 只有全连接层的权重需要加入正则化
        if regularizer != None:
            tf.add_to_collection('losses', regularizer(fc1_weight))
        fc1_biases = tf.get_variable("bias", [FC_SIZE], initializer=tf.constant_initializer(0.1))
        fc1 = tf.nn.relu(tf.matmul(reshaped, fc1_weight) + fc1_biases)
        if train:
            fc1 = tf.nn.dropout(fc1, 0.5) # 0.5为每个元素被保存下来的概率

    # 声明第六层全连接层的前向传播过程,这一层的输入为长度是512的向量,输出为10的一维向量
    # 结果需要通过softmax层
    with tf.variable_scope('layer6-fc2'):
        fc2_weight = tf.get_variable("weight", [FC_SIZE, OUTPUT_NODE],
                                     initializer=tf.truncated_normal_initializer(stddev=0.1))
        if regularizer != None:
            tf.add_to_collection('losses', regularizer(fc2_weight))
        fc2_biases = tf.get_variable("bias", [OUTPUT_NODE], initializer=tf.constant_initializer(0.1))
        logit = tf.matmul(fc1, fc2_weight) + fc2_biases

    #返回第六层的输出
    return logit

mnist_train.py : 定义神经网络的训练过程

# -*- coding:utf-8 -*-

#定义神经网络的训练过程

import os  #os模块是对操作系统进行调用的接口
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data

#加载mnist_inference.py中定义的常量和前向传播的函数
import mnist_inference

#配置神经网络的参数
BATCH_SIZE = 100 #一个训练batch中的训练数据个数,数字越小,越接近随机梯度下降,越大越接近梯度下降
LEARNING_RATE_BASE = 0.01 #基础的学习率
LEARNING_RATE_DECAY = 0.99 #学习率的衰减率
REGULARIZATION_RATE = 0.0001 #描述网络复杂度的正则化向在损失函数中的系数
TRAINING_STEPS = 30000 #训练轮数
MOVING_AVERAGE_DECAY = 0.99 #滑动平均衰减率
#模型保存的路径和文件名
MODEL_SAVE_PATH = "/tensorflow_google/mnist"
MODEL_NAME = "mnist.ckpt"

def train(mnist):
    #定义输入输出,卷积神经网络的输入层为一个三维矩阵
    #第一维为一个batch中样例的个数,第二维和第三维表示图片的尺寸,第四维表示图片的深度
    x = tf.placeholder(tf.float32, [BATCH_SIZE, mnist_inference.IMAGE_SIZE,
                                    mnist_inference.IMAGE_SIZE, mnist_inference.NUM_CHANNELS], 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, 1, regularizer)

    global_step = tf.Variable(0, trainable=False)
    # 初始化滑动平均类
    variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
    # 在所有代表神经网络参数的变量上使用滑动平均,需要被训练的参数,variable_averages返回的就是GraphKeys.TRAINABLE_VARIABLES中的元素
    variable_averages_op = variable_averages.apply(tf.trainable_variables())
    # 计算交叉熵,使用了sparse_softmax_cross_entropy_with_logits,当问题只有一个正确答案时,可以使用这个函数来加速交叉熵的计算。
    # 这个函数的第一个参数是神经网络不包括softmax层的前向传播结果,第二个是训练数据的正确答案,argmax返回最大值的位置
    cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.argmax(y_, 1))
    # 计算在当前batch中所有样例的交叉熵平均值
    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)
    # LEARNING_RATE_BASE为基础学习率,global_step为当前迭代的次数
    # mnist.train.num_examples/BATCH_SIZE为完整的过完所有的训练数据需要的迭代次数
    # LEARNING_RATE_DECAY为学习率衰减速度

    # 使用GradientDescentOptimizer优化算法优化损失函数
    train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
    # 在训练神经网络的时候,每过一遍数据都要通过反向传播来更新参数以及其滑动平均值
    # 为了一次完成多个操作,可以通过tf.control_dependencies和tf.group两种机制来实现
    # train_op = tf.group(train_step, variable_averages_op)  #和下面代码功能一样
    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)
            #将输入的训练数据调整为一个四维矩阵
            reshaped_xs = np.reshape(xs, (BATCH_SIZE, mnist_inference.IMAGE_SIZE,
                                          mnist_inference.IMAGE_SIZE, mnist_inference.NUM_CHANNELS))
            _, loss_value, step = sess.run([train_op, loss, global_step],
                                           feed_dict={x: reshaped_xs, y_: ys})
            #每1000轮保存一次模型
            if i%1000==0:
                #输出当前的训练情况,只输出了网络在当前训练batch上的损失函数大小
                print("After %d training step(s), loss on training batch is %g," %(step, loss_value))
                #保存当前的网络,给出了global_step参数,这样可以让每个保存网络的文件名末尾加上训练的轮数
                #例如mnist.ckpt-1000
                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("/tensorflow_google", 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 numpy as np

#加载mnist_inference和mnist_train中定义的常量和函数
import mnist_inference
import mnist_train


def evaluate(mnist):
    with tf.Graph().as_default() as g:  #将默认图设为g
        #定义输入输出的格式
        Validate_SIZE = mnist.validation.num_examples
        x = tf.placeholder(tf.float32, [Validate_SIZE, mnist_inference.IMAGE_SIZE,
                                        mnist_inference.IMAGE_SIZE, mnist_inference.NUM_CHANNELS], name='x-input')
        y_ = tf.placeholder(tf.float32, [None, mnist_inference.OUTPUT_NODE], name='y-input')
        xs = mnist.validation.images
        # 将输入的测试数据调整为一个三维矩阵
        reshaped_xs = np.reshape(xs, (Validate_SIZE, mnist_inference.IMAGE_SIZE,
                                      mnist_inference.IMAGE_SIZE, mnist_inference.NUM_CHANNELS))
        validate_feed = {x: reshaped_xs, y_: mnist.validation.labels}

        #直接通过调用封装好的函数来计算前向传播的结果
        #测试时不关注过拟合问题,所以正则化输入为None
        y = mnist_inference.inference(x, None, None)

        #使用前向传播的结果计算正确率,如果需要对未知的样例进行分类
        #使用tf.argmax(y, 1)就可以得到输入样例的预测类别
        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
        # 首先将一个布尔型的数组转换为实数,然后计算平均值
        # 平均值就是网络在这一组数据上的正确率
        #True为1,False为0
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

        #通过变量重命名的方式来加载模型
        variable_averages = tf.train.ExponentialMovingAverage(mnist_train.MOVING_AVERAGE_DECAY)
        variable_to_restore = variable_averages.variables_to_restore()
        # 所有滑动平均的值组成的字典,处在/ExponentialMovingAverage下的值
        # 为了方便加载时重命名滑动平均量,tf.train.ExponentialMovingAverage类
        # 提供了variables_to_store函数来生成tf.train.Saver类所需要的变量
        saver = tf.train.Saver(variable_to_restore) #这些值要从模型中提取


        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) #使用此模型检验
                #没有初始化滑动平均值,只是调用模型的值,inference只是提供了一个变量的接口,完全没有赋值
                print("After %s training steps, validation accuracy = %g"
                      %(global_step, accuracy_score))
            else:
                print("No checkpoint file found")
                return

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

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

输出为:After 29001 training steps, validation accuracy = 0.991

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值