[ MOOC课程学习 ] 人工智能实践:Tensorflow笔记_CH7_2 Lenet-5代码讲解

Lenet-5代码讲解

Lenet 神经网络是 Yann LeCun 等人在 1998 年提出的,该神经网络充分考虑图像的相关性。

1. Lenet 神经网络结构为:

1.输入为 32*32*1 的图片大小,为单通道的输入;
2.进行卷积,卷积核大小为 5*5*1,个数为 6,步长为 1,非全零填充模式;
3.将卷积结果通过非线性激活函数;
4.进行池化,池化大小为 2*2,步长为 1,全零填充模式;
5.进行卷积,卷积核大小为 5*5*6,个数为 16,步长为 1,非全零填充模式;
6.将卷积结果通过非线性激活函数;
7.进行池化,池化大小为 2*2,步长为 1,全零填充模式;
8.全连接层进行 10 分类。

2. Lenet 神经网络的结构图及特征提取过程如下所示:

[ MOOC课程学习 ] 人工智能实践:Tensorflow笔记_CH7_2 Lenet-5代码讲解_第1张图片

3. 根据 Lenet 神经网络的结构可得,Lenet 神经网络具有如下特点:

1.卷积(Conv)、非线性激活函数(sigmoid)、池化(ave-pooling)相互交替;
2.层与层之间稀疏连接,减少计算复杂度。

4. 对 Lenet 神经网络进行微调,使其适应 Mnist 数据集:

由于 Mnist 数据集中图片大小为 28*28*1 的灰度图片,而 Lenet 神经网络的输入为 32*32*1,故需要对 Lenet 神经网络进行微调。
1.输入为 28*28*1 的图片大小,为单通道的输入;
2.进行卷积,卷积核大小为 5*5*1,个数为 32,步长为 1,全零填充模式;
3.将卷积结果通过非线性激活函数;
4.进行池化,池化大小为 2*2,步长为 2,全零填充模式;
5.进行卷积,卷积核大小为 5*5*32,个数为 64,步长为 1,全零填充模式;
6.将卷积结果通过非线性激活函数;
7.进行池化,池化大小为 2*2,步长为 2,全零填充模式;
8.全连接层,进行 10 分类。

5. Lenet 进行微调后的结构如下所示:

[ MOOC课程学习 ] 人工智能实践:Tensorflow笔记_CH7_2 Lenet-5代码讲解_第2张图片

6. Lenet 神经网络在 Mnist 数据集上的实现:

主要分为三个部分:
前向传播过程(mnist_lenet5_forward.py)、
反向传播过程(mnist_lenet5_backword.py)、
测试过程(mnist_lenet5_test.py)。

1.前向传播过程(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')

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))
    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.5)

    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

(1) 图片大小即每张图片分辨率为 28*28,故 IMAGE_SIZE 取值为 28;
Mnist 数据集为灰度图,故输入图片通道数NUM_CHANNELS 取值为 1;
第一层卷积核大小为 5,卷积核个数为 32,故 CONV1_SIZE 取值为5,CONV1_KERNEL_NUM 取值为 32;
第二层卷积核大小为 5,卷积核个数为 64,故 CONV2_SIZE 取值为 5, CONV2_KERNEL_NUM为 64;
全连接层第一层为 512 个神经元,全连接层第二层为 10 个神经元,故FC_SIZE 取值为512,OUTPUT_NODE 取值为 10,实现 10 分类输出。
(2) tf.nn.relu()用来实现非线性激活,相比 sigmoid 和 tanh 函数,relu 函数可以实现快速的收敛。
(3) pool_shape = pool2.get_shape().as_list(): 根据 get_shape()函数得到 pool2 输出矩阵的维度,并存入 list 中。其中,pool_shape[0]为一个 batch 值。
nodes = pool_shape[1] * pool_shape[2] * pool_shape[3]从 list 中依次取出矩阵的长宽及深度,并求三者的乘积,得到矩阵被拉长后的长度。
reshaped = tf.reshape(pool2, [pool_shape[0], nodes])将 pool2 转换为一个 batch 的向量再传入后续的全连接。get_shape() 函数用于获取一个张量的维度,并且输出张量每个维度上面的值。
例如:

A = tf.random_normal(shape=[3,4])
print(A.get_shape())
# 输出结果为: (3, 4)

(4) if train: fc1 = tf.nn.dropout(fc1, 0.5)
如果是训练阶段,则对该层输出使用 dropout,也就是随机的将该层输出中的一半神经元置为无效,是为了避免过拟合而设置的,一般只在全连接层中使用。
2.反向传播过程(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
REGULARIZER = 0.0001
TRAIN = True
LR = 0.005
LR_DECAY_RATE = 0.99
EMA_DECAY = 0.99

MODEL_SAVE_PATH = './model/'
MODEL_NAME = 'mnist_model'
STEPS = 50000

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, TRAIN, REGULARIZER)

    global_step = tf.Variable(0, trainable=False)

    ce = tf.nn.sparse_softmax_cross_entropy_with_logits(
        labels=tf.argmax(y_, 1),
        logits=y
    )
    cem = tf.reduce_mean(ce)
    loss = cem + tf.add_n(tf.get_collection('losses'))

    lr = tf.train.exponential_decay(
        learning_rate=LR,
        global_step=global_step,
        decay_steps=mnist.train.num_examples / BATCH_SIZE,
        decay_rate=LR_DECAY_RATE,
        staircase=True
    )
    train_step = tf.train.GradientDescentOptimizer(lr).minimize(loss, global_step)

    ema = tf.train.ExponentialMovingAverage(decay=EMA_DECAY, num_updates=global_step)
    ema_op = ema.apply(tf.trainable_variables())

    with tf.control_dependencies([train_step, ema_op]):
        train_op = tf.no_op('train')

    saver = tf.train.Saver()

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        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)
            xs_reshaped = np.reshape(xs,(
                BATCH_SIZE,
                mnist_lenet5_forward.IMAGE_SIZE,
                mnist_lenet5_forward.IMAGE_SIZE,
                mnist_lenet5_forward.NUM_CHANNELS
            ))
            _, loss_v, step = sess.run([train_op, loss, global_step], feed_dict={x: xs_reshaped, y_: ys})
            if i % 100 == 0:
                print('After {} training steps, loss on training batch is {}'.format(step, loss_v))
                saver.save(sess, os.path.join(MODEL_SAVE_PATH, MODEL_NAME), global_step)


def main():
    mnist = input_data.read_data_sets('./data/', one_hot=True)
    backward(mnist)

if __name__ == '__main__':
    main()

3.测试过程(mnist_lenet5_test.py),对 Mnist 数据集中的测试数据进行预测,测试模型准确率。具体代码如下所示:

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

TEST_INTERVAL_SECS = 5

REGULARIZER = None
TRAIN = False



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, TRAIN, REGULARIZER)

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

        correct_num = tf.equal(tf.argmax(y_, 1), tf.argmax(y, 1)) #
        acc = tf.reduce_mean(tf.cast(correct_num, 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] #
                    xs = mnist.test.images
                    ys = mnist.test.labels
                    xs_reshaped = np.reshape(xs,(
                        mnist.test.num_examples,
                        mnist_lenet5_forward.IMAGE_SIZE,
                        mnist_lenet5_forward.IMAGE_SIZE,
                        mnist_lenet5_forward.NUM_CHANNELS
                    ))
                    acc_val = sess.run(acc, feed_dict={x: xs_reshaped, y_: ys})
                    print('After {} training steps, acc on test if {}.'.format(global_step, acc_val))
                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()

你可能感兴趣的:(tensorflow)