卷积神经网络之-Lenet

更多内容请关注『机器视觉CV』公众号
原文地址

前言

Lenet 是一系列网络的合称,包括 Lenet1 - Lenet5,由 Yann LeCun 等人在1990 年《Handwritten Digit Recognition with a Back-Propagation Network》中提出,是卷积神经网络的 HelloWorld。

Lenet5

Lenet 的最终版本是 Lenet5,是一个 7 层的神经网络,包含3个卷积层,2个池化层,1个全连接层。其中所有卷积层的所有卷积核都为5x5,步长 strid=1,池化方法都为全局pooling,激活函数为 Sigmoid,网络结构如下:

代码复现

Lenet 网络的参数量,以及每层的输出特征图大小如下:

  • 卷积的卷积核都为 5×5 步长 stride=1
  • 输入是 32×32
  • -> 6@28*28(卷积C1) 参数:5×5×6+6 =156
  • -> 6@14*14(池化S2) 参数:偏移量参数 2×6
  • -> 16@10*10(卷积C3) 参数:5×5×6×16+16 = 2416 # 这里与原始的 LeNet 网络有区别
  • -> 16@5*5(池化S4) 参数:偏移量参数 2×16
  • -> 120@1*1(卷积C5)当然,这里也可以认为是全连接层(因为上一层得到的特征图是5x5,卷积核也为5x5) 参数:5×5×16×120+120 = 48120
  • -> 84(全连接F6) 这个 84 的选取有个背景:与 ASCII 码表示的 7×12 的位图大小相等 参数:120×84
  • -> 10(输出类别数) 参数:84×10

下面我们用 Pytorh 框架实现一些 Lenet5,实际代码会与上面的说明有些差别,并模拟一个输入进行测试。

import torch
import torch.nn as nn
import torch.nn.functional as F

class LeNet5(nn.Module):
    def __init__(self, num_classes, grayscale=False): 
        """
        num_classes: 分类的数量
        grayscale:是否为灰度图
        """
        super(LeNet5, self).__init__()
        
        self.grayscale = grayscale
        self.num_classes = num_classes
        
        if self.grayscale: # 可以适用单通道和三通道的图像
            in_channels = 1
        else:
            in_channels = 3
        
        # 卷积神经网络
        self.features = nn.Sequential(
            nn.Conv2d(in_channels, 6, kernel_size=5),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(6, 16, kernel_size=5),
            nn.MaxPool2d(kernel_size=2)   # 原始的模型使用的是 平均池化
        )
        # 分类器
        self.classifier = nn.Sequential(
            nn.Linear(16*5*5, 120),  # 这里把第三个卷积当作是全连接层了
            nn.Linear(120, 84), 
            nn.Linear(84, num_classes)
        )
    
    def forward(self, x):
        x = self.features(x) # 输出 16*5*5 特征图
        x = torch.flatten(x, 1) # 展平 (1, 16*5*5)
        logits = self.classifier(x) # 输出 10
        probas = F.softmax(logits, dim=1)
        return logits, probas
        
        
    
num_classes = 10  # 分类数目
grayscale = True  # 是否为灰度图
data = torch.rand((1, 1, 32, 32))
print("input data:\n", data, "\n")
model = LeNet5(num_classes, grayscale)
logits, probas = model(data)
print("logits:\n",logits)
print("probas:\n",probas)

最后模拟了一个输入,输出一个分类器运算后的结果和 10 个 softmax 概率值

image.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

机器视觉CV

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值