1.LeNet模型

LeNet是一个早期用来识别手写数字的卷积神经网络,这个名字来源于LeNet论文的第一作者Yann LeCun。LeNet展示了通过梯度下降训练卷积神经网络可以达到手写数字识别在当时最先进的成果,这个尊基性的工作第一次将卷积神经网络推上舞台

上图就是LeNet模型,下面将对每层参数进行说明

1.1 input输入层

假设输入层数据shape=(32,32)

1.2 C1卷积层

  • 卷积核大小: kernel_size=(5,5)
  • 步幅:stride = 1
  • 输出通道为6
  • 可训练参数为: (5 * 5 + 1) * 6
  • 激活函数:采用relu

    输入层数据经过C1卷积层后将得到feature maps形状(6 * 28 * 28),注:28 = 32 -5 + 1

1.3 S2池化层

池化层(Max Pooling)窗口形状均为2*2,步幅度为2,输出feature maps为(6 *14 * 14),6为feature map的数量

1.4 C3卷积层

  • 卷积核大小: kernel_size=(5,5)
  • 步幅:stride = 1
  • 输出通道为16
  • 激活函数:采用relu得到feature maps为(16 * 10 * 10),(10*10)为每个feature map形状,16为feature map数量

1.5 S4池化层

池化层(Max Pooling)窗口形状依然均为2*2,步幅度为2,输出feature maps为(16 *5 * 5),16为feature map的数量

1.6 C5全链接层

  • 输出120个神经元
  • 激活函数:relu

1.7 F6全连接层

  • 输出84个神经元
  • 激活函数:relu

1.8 output

  • 输出10个神经元
  • 激活函数:无

2.用Mxnet实现LeNet模型

import mxnet as mx
from mxnet import autograd,init,nd
from mxnet.gluon import nn,Trainer
from mxnet.gluon import data as gdata
from mxnet.gluon import loss as gloss
import time class LeNet_mxnet:
def __init__(self):
self.net = nn.Sequential()
self.net.add(nn.Conv2D(channels=6,kernel_size=5,activation='relu'),
nn.MaxPool2D(pool_size =(2,2),strides=(2,2)),
nn.Conv2D(channels=16,kernel_size=(5,5),strides=(1,1),padding=(0,0),activation='relu'),
nn.MaxPool2D(pool_size =(2,2),strides=(2,2)),
nn.Dense(units=120,activation='relu'),
nn.Dense(units=84,activation='relu'),
nn.Dense(units=10) #最后一个全连接层激活函数取决于损失函数
) def train(self,train_iter,test_iter,n_epochs,ctx):
print('training on',ctx)
self.net.initialize(force_reinit=True,ctx=ctx,init=init.Xavier())
trainer_op = Trainer(self.net.collect_params(),'adam',{'learning_rate':0.01})
loss = gloss.SoftmaxCrossEntropyLoss() accuracy_val = 0
for epoch in range(n_epochs): train_loss_sum,train_acc_sum,n,start = 0.0,0.0,0,time.time() for x_batch,y_batch in train_iter:
x_batch,y_batch = x_batch.as_in_context(ctx),y_batch.as_in_context(ctx)
with autograd.record():
y_hat = self.net(x_batch)
loss_val = loss(y_hat,y_batch).sum()
loss_val.backward()
trainer_op.step(n_batches)
y_batch = y_batch.astype('float32')
train_loss_sum += loss_val.asscalar()
train_acc_sum += (y_hat.argmax(axis=1) == y_batch).sum().asscalar()
n += y_batch.size
test_acc = self.accuracy_score(test_iter,ctx)
accuracy_val += self.accuracy_score(test_iter,ctx)
print('epoch:%d,train_loss:%.4f,train_acc:%.3f,test_acc:%.3f,time:%.1f sec'
%(epoch+1, train_loss_sum / n, train_acc_sum/ n,test_acc,time.time() - start)) def accuracy_score(self,data_iter,ctx):
acc_sum,n = nd.array([0],ctx=ctx),0
for x,y in data_iter:
x,y = x.as_in_context(ctx),y.as_in_context(ctx)
y = y.astype('float32')
acc_sum += (self.net(x).argmax(axis=1) == y).sum()
n += y.size
return acc_sum.asscalar() / n def __call__(self,x):
return self.net(x) def predict(self,x,ctx):
x = x.as_in_context(ctx)
return self.net(x).argmax(axis=1) def print_info(self):
print(self.net[4].params)

3.使用mnist手写数字数据集进行测试

from tensorflow.keras.datasets import mnist

(x_train,y_train),(x_test,y_test) = mnist.load_data()
print(x_train.shape,y_train.shape)
print(x_test.shape,y_test.shape)
x_train = x_train.reshape(60000,1,28,28).astype('float32')
x_test = x_test.reshape(10000,1,28,28).astype('float32')
(60000, 28, 28) (60000,)
(10000, 28, 28) (10000,)
lenet_mxnet = LeNet_mxnet()
epochs = 10
n_batches = 500
train_iter = gdata.DataLoader(gdata.ArrayDataset(x_train,y_train),batch_size=n_batches)
test_iter = gdata.DataLoader(gdata.ArrayDataset(x_test,y_test),batch_size=n_batches)
lenet_mxnet.train(train_iter,test_iter,epochs,ctx=mx.gpu())
training on gpu(0)
epoch:1,train_loss:1.8267,train_acc:0.571,test_acc:0.896,time:3.0 sec
epoch:2,train_loss:0.2449,train_acc:0.924,test_acc:0.948,time:2.6 sec
epoch:3,train_loss:0.1563,train_acc:0.952,test_acc:0.954,time:2.6 sec
epoch:4,train_loss:0.1302,train_acc:0.961,test_acc:0.962,time:2.5 sec
epoch:5,train_loss:0.1169,train_acc:0.964,test_acc:0.958,time:2.5 sec
epoch:6,train_loss:0.1017,train_acc:0.969,test_acc:0.967,time:2.5 sec
epoch:7,train_loss:0.0855,train_acc:0.973,test_acc:0.964,time:3.3 sec
epoch:8,train_loss:0.0848,train_acc:0.973,test_acc:0.964,time:3.6 sec
epoch:9,train_loss:0.0767,train_acc:0.976,test_acc:0.963,time:3.5 sec
epoch:10,train_loss:0.0771,train_acc:0.977,test_acc:0.970,time:3.5 sec
# 将预测结果可视化
import matplotlib.pyplot as plt def plt_image(image):
n = 20
plt.figure(figsize=(20,4))
for i in range(n):
ax = plt.subplot(2,10,i+1)
plt.imshow(x_test[i].reshape(28,28))
plt.gray()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show() plt_image(x_test)
print('predict result:',lenet_mxnet.predict(nd.array(x_test[0:20]),ctx=mx.gpu()))

predict result:
[7. 2. 1. 0. 4. 1. 4. 9. 5. 9. 0. 6. 9. 0. 1. 5. 9. 7. 3. 4.]
<NDArray 20 @gpu(0)>

4. 附:需要注意的知识点

  • (1) 注意SoftmaxCrossEntropyLoss的使用,hybrid_forward源码说明,若from_logits为False时(默认为Flase),会先通过log_softmax计算各分类的概率,再计算loss,同样SigmoidBinaryCrossEntropyLoss也提供了from_sigmoid参数决定是否在hybrid_forward函数中要计算sigmoid函数,所以在创建模型最后一层的时候要特别注意是否要给激活函数

  • (2) 注意权重初始化选择

  • (3) 注意(y_hat.argmax(axis=1) == y_batch)操作时y_batch数据类型转换

  • (4) 上面的模型没有对数据集进行归一化处理,可以添加该步骤

使用mxnet实现卷积神经网络LeNet的更多相关文章

  1. MXNET:卷积神经网络

    介绍过去几年中数个在 ImageNet 竞赛(一个著名的计算机视觉竞赛)取得优异成绩的深度卷积神经网络. LeNet LeNet 证明了通过梯度下降训练卷积神经网络可以达到手写数字识别的最先进的结果. ...

  2. TensorFlow+实战Google深度学习框架学习笔记(12)------Mnist识别和卷积神经网络LeNet

    一.卷积神经网络的简述 卷积神经网络将一个图像变窄变长.原本[长和宽较大,高较小]变成[长和宽较小,高增加] 卷积过程需要用到卷积核[二维的滑动窗口][过滤器],每个卷积核由n*m(长*宽)个小格组成 ...

  3. MXNET:卷积神经网络基础

    卷积神经网络(convolutional neural network).它是近年来深度学习能在计算机视觉中取得巨大成果的基石,它也逐渐在被其他诸如自然语言处理.推荐系统和语音识别等领域广泛使用. 目 ...

  4. 卷积神经网络LeNet Convolutional Neural Networks (LeNet)

    Note This section assumes the reader has already read through Classifying MNIST digits using Logisti ...

  5. 卷积神经网络之LeNet

    开局一张图,内容全靠编. 上图引用自 [卷积神经网络-进化史]从LeNet到AlexNet. 目前常用的卷积神经网络 深度学习现在是百花齐放,各种网络结构层出不穷,计划梳理下各个常用的卷积神经网络结构 ...

  6. 卷积神经网络详细讲解 及 Tensorflow实现

    [附上个人git完整代码地址:https://github.com/Liuyubao/Tensorflow-CNN] [如有疑问,更进一步交流请留言或联系微信:523331232] Reference ...

  7. 经典卷积神经网络(LeNet、AlexNet、VGG、GoogleNet、ResNet)的实现(MXNet版本)

    卷积神经网络(Convolutional Neural Network, CNN)是一种前馈神经网络,它的人工神经元可以响应一部分覆盖范围内的周围单元,对于大型图像处理有出色表现. 其中 文章 详解卷 ...

  8. 卷积神经网络的一些经典网络(Lenet,AlexNet,VGG16,ResNet)

    LeNet – 5网络 网络结构为: 输入图像是:32x32x1的灰度图像 卷积核:5x5,stride=1 得到Conv1:28x28x6 池化层:2x2,stride=2 (池化之后再经过激活函数 ...

  9. 从LeNet到SENet——卷积神经网络回顾

    从LeNet到SENet——卷积神经网络回顾 从 1998 年经典的 LeNet,到 2012 年历史性的 AlexNet,之后深度学习进入了蓬勃发展阶段,百花齐放,大放异彩,出现了各式各样的不同网络 ...

随机推荐

  1. Eureka与Zookeeper的区别

    ACID与ACP的介绍

  2. MongoDB学习笔记(六)

    初识 MongoDB 中的索引 索引就像图书的目录一样,可以让我们快速定位到需要的内容,关系型数据库中有索引,NoSQL 中当然也有,本文我们就先来简单介绍下 MongoDB 中的索引. 索引创建 默 ...

  3. 百度前端技术学院-task1.4源代码

    任务描述 实现如 示例图(点击打开) 的效果 灰色元素水平垂直居中,有两个四分之一圆位于其左上角和右下角. 任务注意事项 思考不同情况下(如灰色高度是根据内容动态变化的)水平垂直居中的解决方案. 动手 ...

  4. 补习系列(12)-springboot 与邮件发送【华为云技术分享】

    目录 一.邮件协议 关于数据传输 二.SpringBoot 与邮件 A. 添加依赖 B. 配置文件 C. 发送文本邮件 D.发送附件 E. 发送Html邮件 三.CID与图片 参考文档 一.邮件协议 ...

  5. 【08】Kubernets:Service

    写在前面的话 在 K8S 第一节的时候我们简单提到过 Service 的工作模式有三种:userspace / iptables / ipvs.并且已经知道在目前新版本中默认是 ipvs,前提是在按照 ...

  6. Storm 系列(九)—— Storm 集成 Kafka

    一.整合说明 Storm 官方对 Kafka 的整合分为两个版本,官方说明文档分别如下: Storm Kafka Integration : 主要是针对 0.8.x 版本的 Kafka 提供整合支持: ...

  7. Jackson 序列化/反序列化时忽略某属性

    https://www.iteye.com/blog/wwwcomy-2397340 博客分类: Spring jacksonread_onlyjsonignore  基于Spring MVC的RES ...

  8. DSAPI CMD命令行进程代理

    DSAPI.文件.CMD命令行进程代理,是用来和CMD.exe或指定exe进行输出重定向的简化使用工具,可隐藏或显式地启动一个cmd.exe,并将输出流.输入流和错误流重定向至代理,通过事件触发方式与 ...

  9. .net 中访问config的一些方式

    人所缺乏的不是才干而是志向,不是成功的能力而是勤劳的意志. 哎!好久没有写博客了,今天就分享一些比较常用的对config文件的访问一些方式. 首先 引用 using System.Configurat ...

  10. 基于.NET平台常用的框架整理 转自 http://www.cnblogs.com/zhuyongblogs/p/5353751.html

    常用的一些开源组件整理: 导出Excel报表的插件:NOPI.dll(基于微软OpenXml实现)开源的作业调度和自动任务框架:Quartz.NET用于大数据搜索引擎的全文检索框架:Lucene.ne ...