机器学习/深度学习入门:LeNet模型实现

LeNet:最早用于数字识别的CNN

输入层:32*32===》C1===》S2(平均池化)===》C3===》S4===》F5===》F6===》F7(输出层)

TensorFlow实现

数据集准备:

首先是网络结构如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/10/22 14:15
# @Author  : HJH
# @File    : LeNet.py
# @Software: PyCharm
"""
# code is far away from bugs with the god animal protecting
    I love animals. They taste delicious.
              ┏┓      ┏┓
            ┏┛┻━━━┛┻┓
            ┃      ☃      ┃
            ┃  ┳┛  ┗┳  ┃
            ┃      ┻      ┃
            ┗━┓      ┏━┛
                ┃      ┗━━━┓
                ┃  神兽保佑    ┣┓
                ┃ 永无BUG!   ┏┛
                ┗┓┓┏━┳┓┏┛
                  ┃┫┫  ┃┫┫
                  ┗┻┛  ┗┻┛
"""

import tensorflow as tf


class LeNet(object):
    def __init__(self, x, num_class, keep_drop, regulation_rate):
        self.x = x
        self.num_class = num_class
        self.keep_drop = keep_drop
        self.regulation_rate = regulation_rate
        self.__create__()

    def __create__(self):
        # 网上大多数博客的实现方式
        # conv1 = conv(self.x, 5, 5, 32, 1, 1, name='conv1', padding='SAME')
        # pool1 = pool(conv1, 2, 2, 2, 2, name='pool1', padding='SAME')
        #
        # conv2 = conv(pool1, 5, 5, 64, 1, 1, name='conv2', padding='SAME')
        # pool2 = pool(conv2, 2, 2, 2, 2, name='pool2', padding='SAME')
        #
        # pool2_shape = pool2.get_shape().as_list()
        # pool2_len = pool2_shape[1] * pool2_shape[2] * pool2_shape[3]
        # reshaped = tf.reshape(pool2, [pool2_shape[0], pool2_len])
        # fc3 = fc(reshaped, pool2_len, 512, self.regulation_rate, name='fc3')
        # drop3 = dropout(fc3, self.keep_drop)
        #
        # self.fc4 = fc(drop3, 512, self.num_class, self.regulation_rate, name='fc4', relu=False)

        # 论文中的实现方式
        conv1 = conv(self.x, 5, 5, 6, 1, 1, name='conv1', padding='SAME')
        pool1 = pool(conv1, 2, 2, 2, 2, name='pool1', padding='SAME')

        conv2 = conv(pool1, 5, 5, 16, 1, 1, name='conv2', padding='SAME')
        pool2 = pool(conv2, 2, 2, 2, 2, name='pool2', padding='SAME')

        conv3 = conv(pool2, 5, 5, 120, 1, 1, name='conv3', padding='SAME')

        conv3_shape = conv3.get_shape().as_list()
        conv3_len = conv3_shape[1] * conv3_shape[2] * conv3_shape[3]
        reshaped = tf.reshape(conv3, [conv3_shape[0], conv3_len])
        fc4 = fc(reshaped, conv3_len, 84, self.regulation_rate, name='fc3')

        self.fc5 = fc(fc4, 84, self.num_class, self.regulation_rate, name='fc4', relu=False)


def conv(x, filter_height, filter_width, num_filter, stride_y, stride_x, name, padding='SAME'):
    input_channels = int(x.get_shape()[-1])
    with tf.variable_scope(name) as scope:
        weights = tf.get_variable("weights", shape=[filter_height, filter_width, input_channels, num_filter],
                                  initializer=tf.truncated_normal_initializer(stddev=0.1))
        biases = tf.get_variable("biases", shape=[num_filter], initializer=tf.constant_initializer(0.0))

    conv = tf.nn.conv2d(x, weights, padding=padding, strides=[1, stride_y, stride_x, 1])
    bias = tf.reshape(tf.nn.bias_add(conv, biases), tf.shape(conv))
    relu = tf.nn.relu(bias, name=scope.name)
    return relu


def pool(x, filter_height, filter_width, stride_y, stride_x, name, padding='SAME'):
    return tf.nn.max_pool(x, ksize=[1, filter_height, filter_width, 1], strides=[1, stride_y, stride_x, 1],
                          padding=padding, name=name)


def fc(x, num_in, num_out, regulation_rate, name, relu=True):
    with tf.variable_scope(name) as scope:
        weights = tf.get_variable("weights", shape=[num_in, num_out],
                                  initializer=tf.truncated_normal_initializer(stddev=0.1))
        biases = tf.get_variable("biases", shape=[num_out], initializer=tf.constant_initializer(0.1))
        tf.add_to_collection("losses", tf.contrib.layers.l2_regularizer(regulation_rate)(weights))
    if relu is True:
        act = tf.nn.xw_plus_b(x, weights, biases)
        relu = tf.nn.relu(act, name=scope.name)
        return relu
    else:
        act = tf.nn.xw_plus_b(x, weights, biases, name=scope.name)
        return act


def dropout(x, keep_drop):
    return tf.nn.dropout(x, keep_prob=keep_drop)

训练过程如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/10/24 11:04
# @Author  : HJH
# @File    : train.py
# @Software: PyCharm
"""
# code is far away from bugs with the god animal protecting
    I love animals. They taste delicious.
              ┏┓      ┏┓
            ┏┛┻━━━┛┻┓
            ┃      ☃      ┃
            ┃  ┳┛  ┗┳  ┃
            ┃      ┻      ┃
            ┗━┓      ┏━┛
                ┃      ┗━━━┓
                ┃  神兽保佑    ┣┓
                ┃ 永无BUG!   ┏┛
                ┗┓┓┏━┳┓┏┛
                  ┃┫┫  ┃┫┫
                  ┗┻┛  ┗┻┛
"""

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import LeNet
import numpy as np
import os

batch_size = 100
'''网上一些代码的准确率总是在10%左右徘徊,这是因为学习率设置的太高(如果没记错的话,这些代码的学习率为0.8)'''
learning_rate_base = 0.01
learning_rate_decay = 0.99
epochs = 30000
moving_average_decay = 0.99
regulation_rate = 0.0001
num_classes = 10
droup_rate = 0.5

model_save_path = './model/tensorboard/'
model_name = 'lenet.ckpt'
summary_save_path = './model/checkpoints/'


def train(data):
    # 数据集占位符
    x = tf.placeholder(tf.float32, shape=[batch_size, 28, 28, 1])
    y = tf.placeholder(tf.float32, shape=[None, num_classes])
    keep_prob = tf.placeholder(tf.float32)
    # 网络模型设计
    model = LeNet.LeNet(x, num_classes, keep_prob, regulation_rate)
    global_step = tf.Variable(0, trainable=False)
    score = model.fc5
    # 损失函数定义
    variable_average = tf.train.ExponentialMovingAverage(moving_average_decay, global_step)
    variable_average_op = variable_average.apply(tf.trainable_variables())
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=score, labels=y)
    cross_entropy_mean = tf.reduce_mean(cross_entropy)
    with tf.name_scope('loss'):
        loss = cross_entropy_mean + tf.add_n(tf.get_collection('losses'))
    # 学习率
    with tf.name_scope('learning_rate'):
        learning_rate = tf.train.exponential_decay(learning_rate_base, global_step,
                                                   data.train.num_examples / batch_size, learning_rate_decay)
    # 梯度下降
    with tf.name_scope('train'):
        train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
        with tf.control_dependencies([train_step, variable_average_op]):
            train_op = tf.no_op(name='train')

    # 训练准确率
    with tf.name_scope('train_accuracy'):
        correct_pred = tf.equal(tf.argmax(score, 1), tf.argmax(y, 1))
        accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

    # 添加到tensorboard
    tf.summary.scalar('loss', loss)
    tf.summary.scalar('learning_rate', learning_rate)
    tf.summary.scalar('accuracy', accuracy)
    merged_summary = tf.summary.merge_all()

    saver = tf.train.Saver()
    with tf.Session() as sess:
        tf.global_variables_initializer().run()
        writer = tf.summary.FileWriter(summary_save_path, sess.graph)
        for i in range(epochs):
            xs, ys = data.train.next_batch(batch_size)
            xs = np.reshape(xs, [batch_size, 28, 28, 1])
            _, loss_value, step, accuracy_value = sess.run([train_op, loss, global_step, accuracy],
                                                           feed_dict={x: xs, y: ys, keep_prob: droup_rate})
            print("After %d training steps,loss is %g,accuracy is %g" % (step, loss_value, accuracy_value))
            if i % 1000 == 0:
                summary_value = sess.run(merged_summary, feed_dict={x: xs, y: ys, keep_prob: 1.})
                writer.add_summary(summary_value, step)
                saver.save(sess, os.path.join(model_save_path, model_name), global_step)


if __name__ == '__main__':
    my_mnist = input_data.read_data_sets('./MNIST/', one_hot=True)
    train(my_mnist)

训练结果如下所示:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 深度学习是一种机器学习技术,可以通过模拟人类大脑的神经网络结构来实现智能决策和预测。Python是一种广泛使用的编程语言,也是深度学习中使用最多的语言之一。 如果你想入门深度学习并使用Python进行实现,可以参考一些经典的教材和资源,例如《Python深度学习》(Francois Chollet著)、《深度学习入门:基于Python的理论与实现》(斋藤康毅著)等。这些教材通常会介绍深度学习的基础理论、Python的基本语法和深度学习框架(如TensorFlow、Keras等)的使用方法,同时也会提供一些实例代码和练习题帮助你快速上手。 此外,你也可以通过在线课程和MOOC平台学习深度学习和Python编程。例如,Coursera、Udacity和edX等平台都提供了相关课程,可以根据自己的需求和兴趣进行选择。 ### 回答2: 深度学习入门:基于Python的理论与实现,是一本介绍深度学习的较为全面的教程。本书主要介绍了人工神经网络,包括基于反向传播算法的多层感知器、卷积神经网络、循环神经网络等基本模型以及它们的实现方法,同时还介绍了一些高级话题,如深度强化学习、生成模型等等。 在本书中,作者通过大量的编程实例来演示深度学习的应用。这些实例包括用深度学习算法进行手写数字识别、图像分类、语音识别和自然语言处理等任务。由于Python是目前流行的机器学习工具之一,因此这本书的实现过程都使用了Python编程语言。 具体来说,本书的主要内容包括人工神经网络基础知识、多层感知器模型、卷积神经网络模型、循环神经网络模型、生成模型、 强化学习、深度学习框架等方面,同时还包括很多深度学习的应用案例。作者采用了基础理论、数学公式、实例程序和实验数据等不同形式的阐释方法,使读者既能够理解深度学习的基本原理,也能够掌握它的实现方法。 此外,本书还提供了大量的参考文献和网上资源,使读者可以进一步深入学习和研究深度学习。在阅读本书的同时,读者可以根据作者提供的代码和数据,通过实际操作来进一步巩固理论知识和应用技能。 总之,深度学习入门:基于Python的理论与实现是一本非常实用的深度学习教材,可以帮助初学者更好地了解深度学习的基本概念和方法,提高实际应用的技能。 ### 回答3: 深度学习是一种人工智能技术,可用于训练计算机识别和理解大量数据。《深度学习入门:基于Python的理论与实现》这本书是入门者学习深度学习的必读之书。以下是本书的内容概述。 本书的第一部分介绍了深度学习的基础概念和理论,包括神经网络、反向传播算法、损失函数等。介绍了基本的深度学习模型,如前馈神经网络、卷积神经网络和循环神经网络。此外,还介绍了优化算法和正则化技术。 在第二部分中,作者使用Python编程语言实现了各种深度学习模型,使用的是许多广泛使用的深度学习框架,如TensorFlow和PyTorch。学习者获得从头开始编写深度学习算法的经验,同时实际应用中必备的PyTorch和TensorFlow经验。 在第三部分中,本书涵盖了几个应用案例,包括图像分类、语音识别和自然语言处理。幸运的是,这些案例通过代码演示展示,确保即使您没有实际应用经验也能操作成功。 总的来说,《深度学习入门:基于Python的理论与实现》是一本适合想要学习深度学习的初学者的绝佳书籍。其提供了深度学习的基本理论和核心技术,同时应用Python编程语言演示了实现技术。由此学习者可以建立深度学习专业的技术栈和能力,在人工智能领域有更广阔的发展空间。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值