MOOC笔记——Lenet5神经网络

MOOC笔记——Lenet5神经网络

Lenet5神经网络的介绍:

Lenet5神经网络是 Yann LeCun 等人在1998年提出的,该神经网络充分考虑图像的相关性。虽然Lenet5神经网络虽然规模不大,但是“麻雀虽小五脏俱全”,该网络涵盖了卷积层、池化层、全连接层。这在当时,已经是一个很不错的网络架构。


写在前面:

建议在读这篇博文前,先了解一下卷积神经网络,因为我写博客没什么经验,做图也不擅长,所以先把主要的内容放上来了,希望大家不要介意。


Lennet5神经网络的结构:

1.输入为32*32*1的图片大小,输入的是灰度图(后续操作都采用的是非全零填充方式)。
2.对输入的图片进行卷积,卷积核大小为5*5*1,个数为6,步长为1。
3.对卷积后的结果进行池化操作,池化大小为2*2,池话步长为2。
4.对池化后的结果继续进行卷积操作,卷积核大小为5*5*6,个属为16,步长为1。
5.对卷积后的结果进行池化操作,池化大小为2*2,步长为2。
6.将池化后的结果拉直,使其成为[1,5*5*16]的一维向量形式,进入全连接层。
7.输出结果。


手写数字识别

  • 一些修改

    • 由于手写数字的图片尺寸是28*28*1,因此我们对输入层进行稍微调整。
    • 在进行卷积操作的时,我们稍加修改了卷积核的个数,使得模型表达效果更好。
    • 在池化或者是卷积操作进行时,我们都选取了全零填充的方式。
  • 流程图:
    MOOC笔记——Lenet5神经网络_第1张图片


程序介绍:

一点说明:该博文的程序都是参考自中国大学MOOC上曹健老师的 “人工智能实践”课程代码,本人在上面进行了细微修改以及添加部分注释,方便读者阅读

程序模块介绍

  • mnist_lennet5_forward.py
    用于前向传播以及各种操作的定义
  • mnist_lennet5_backward.py
    用于反向传播调整参数值(并保存训练好的模型)
  • mnist_lennet5_test.py
    测试模型(提取训练好的模型,测试效果)

程序:

  • mnist_lenet5_forward.py
#coding:utf-8
import tensorflow as tf
IMAGE_SIZE = 28 # 图片尺寸
NUM_CHANNELS = 1 # 信道数
CONV1_SIZE = 5 # 一个卷积核尺寸
CONV1_KERNEL_NUM = 32 # 第一个卷积核个数
CONV2_SIZE = 5  # 第二个卷积核尺寸
CONV2_KERNEL_NUM = 64 # 第二个卷积核个数
FC_SIZE = 512   # 全连接层尺寸
OUTPUT_NODE = 10 # 输出结点个数

# 用于获得权重矩阵,并定义了正则化选项
def get_weight(shape, regularizer):
    w = tf.Variable(tf.truncated_normal(shape,stddev=0.1))
    if regularizer != None: tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(regularizer)(w)) 
    return w

# 用于获得偏差
def get_bias(shape): 
    b = tf.Variable(tf.zeros(shape))  
    return b

# 进行卷积操作
def conv2d(x,w):  
    return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')

# 进行2*2最大池化操作
def max_pool_2x2(x):  
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') 

# 前向传播
def forward(x, train, regularizer):
    conv1_w = get_weight([CONV1_SIZE, CONV1_SIZE, NUM_CHANNELS, CONV1_KERNEL_NUM], regularizer) 
    conv1_b = get_bias([CONV1_KERNEL_NUM]) 
    conv1 = conv2d(x, conv1_w) 
    relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1_b))  # RELU激活函数
    pool1 = max_pool_2x2(relu1) 

    conv2_w = get_weight([CONV2_SIZE, CONV2_SIZE, CONV1_KERNEL_NUM, CONV2_KERNEL_NUM],regularizer) 
    conv2_b = get_bias([CONV2_KERNEL_NUM])
    conv2 = conv2d(pool1, conv2_w) 
    relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_b))
    pool2 = max_pool_2x2(relu2)

    pool_shape = pool2.get_shape().as_list() 
    nodes = pool_shape[1] * pool_shape[2] * pool_shape[3] 
    reshaped = tf.reshape(pool2, [pool_shape[0], nodes]) 

    fc1_w = get_weight([nodes, FC_SIZE], regularizer) 
    fc1_b = get_bias([FC_SIZE]) 
    fc1 = tf.nn.relu(tf.matmul(reshaped, fc1_w) + fc1_b) 
    if train: fc1 = tf.nn.dropout(fc1, 0.6)     # 如果是训练阶段,加入dropout选项,减小模型的过拟合程度

    fc2_w = get_weight([FC_SIZE, OUTPUT_NODE], regularizer)
    fc2_b = get_bias([OUTPUT_NODE])
    y = tf.matmul(fc1, fc2_w) + fc2_b
    return y 

  • mnist_lenet5_backward.py
#coding:utf-8
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import mnist_lenet5_forward
import os
import numpy as np

BATCH_SIZE = 100   # 每一轮迭代的个数
LEARNING_RATE_BASE =  0.005 # 基础学习率
LEARNING_RATE_DECAY = 0.99  # 学习衰减率
REGULARIZER = 0.0001    # 正则化洗漱
STEPS = 50000 # 训练步数
MOVING_AVERAGE_DECAY = 0.99 # 滑动平均衰减率 
MODEL_SAVE_PATH="./model/" 
MODEL_NAME="mnist_model" 

def backward(mnist):
    x = tf.placeholder(tf.float32,[
    BATCH_SIZE,
    mnist_lenet5_forward.IMAGE_SIZE,
    mnist_lenet5_forward.IMAGE_SIZE,
    mnist_lenet5_forward.NUM_CHANNELS])    # 定义占位符
    y_ = tf.placeholder(tf.float32, [None, mnist_lenet5_forward.OUTPUT_NODE])
    y = mnist_lenet5_forward.forward(x,True, REGULARIZER)   # 带正则化的前项传播结果 
    global_step = tf.Variable(0, trainable=False) 

    # 定义总的损失函数
    ce = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.argmax(y_, 1))
    cem = tf.reduce_mean(ce) 
    loss = cem + 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)

    # 实现滑动平均
    ema = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
    ema_op = ema.apply(tf.trainable_variables())
    with tf.control_dependencies([train_step, ema_op]):     # 将train_step和ema_op两个操作绑定到train_op上
        train_op = tf.no_op(name='train')
    # 实例化一个保存和恢复变量的saver,并创建一个会话
    saver = tf.train.Saver() 

    with tf.Session() as sess: 
        init_op = tf.global_variables_initializer() 
        sess.run(init_op) 
        # 通过checkpoint文件定位到最新保存的模型,若文件存在,则加载最新的模型
        ckpt = tf.train.get_checkpoint_state(MODEL_SAVE_PATH) 
        if ckpt and ckpt.model_checkpoint_path:
            saver.restore(sess, ckpt.model_checkpoint_path) 

        for i in range(STEPS):
            xs, ys = mnist.train.next_batch(BATCH_SIZE) 
            reshaped_xs = np.reshape(xs,(  
            BATCH_SIZE,
            mnist_lenet5_forward.IMAGE_SIZE,
            mnist_lenet5_forward.IMAGE_SIZE,
            mnist_lenet5_forward.NUM_CHANNELS))    # 进行resize操作,使得满足输入要求
            _, loss_value, step = sess.run([train_op, loss, global_step], feed_dict={x: reshaped_xs, y_: ys}) 
            if i % 100 == 0: 
                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():
    mnist = input_data.read_data_sets("./data/", one_hot=True) 
    print(mnist)
    backward(mnist)

if __name__ == '__main__':
    main()

  • mnist_lenet5_test.py
#coding:utf-8
import time
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import mnist_lenet5_forward
import mnist_lenet5_backward
import numpy as np

TEST_INTERVAL_SECS = 5

def test(mnist):
    with tf.Graph().as_default() as g: 
        x = tf.placeholder(tf.float32,[
            mnist.test.num_examples,
            mnist_lenet5_forward.IMAGE_SIZE,
            mnist_lenet5_forward.IMAGE_SIZE,
            mnist_lenet5_forward.NUM_CHANNELS]) 
        y_ = tf.placeholder(tf.float32, [None, mnist_lenet5_forward.OUTPUT_NODE])
        y = mnist_lenet5_forward.forward(x,False,None)

        ema = tf.train.ExponentialMovingAverage(mnist_lenet5_backward.MOVING_AVERAGE_DECAY)
        ema_restore = ema.variables_to_restore()
        saver = tf.train.Saver(ema_restore)

        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) 
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))  # 计算准确率 

        while True:
            with tf.Session() as sess:
                ckpt = tf.train.get_checkpoint_state(mnist_lenet5_backward.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] 
                    reshaped_x = np.reshape(mnist.test.images,(
                    mnist.test.num_examples,
                    mnist_lenet5_forward.IMAGE_SIZE,
                    mnist_lenet5_forward.IMAGE_SIZE,
                    mnist_lenet5_forward.NUM_CHANNELS))
                    accuracy_score = sess.run(accuracy, feed_dict={x:reshaped_x,y_:mnist.test.labels}) 
                    print("After %s training step(s), test accuracy = %g" % (global_step, accuracy_score))
                else:
                    print('No checkpoint file found')
                    return
            time.sleep(TEST_INTERVAL_SECS) 

def main():
    mnist = input_data.read_data_sets("./data/", one_hot=True)
    test(mnist)

if __name__ == '__main__':
    main()

你可能感兴趣的:(深度学习/机器学习,Lenet5,神经网络,深度学习,数字识别)