欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

卷积神经网络(一) Lenet Pytorch实现

程序员文章站 2022-03-17 14:28:33
...

Lenet 这个网络是最基础的卷积神经网络,学过一段时间的pytorch看着结构图应该就可以搭建出来了

1. lenet 网络结构图

卷积神经网络(一) Lenet Pytorch实现

2. lenet模型 代码实现

import torch.nn as nn
import torch.nn.functional as F
class LeNet(nn.Module):
    #定义conv pool  fc
    def __init__(self):
        super(LeNet, self).__init__()
        self.conv1 = nn.Conv2d(3, 16, 5)
        self.pool1 = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(16, 32, 5)
        self.pool2 = nn.MaxPool2d(2, 2)
        self.fc1 = nn.Linear(32*5*5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)
    #前向传播
    def forward(self, x):
        x = F.relu(self.conv1(x))
        #(32-5)/1+1=28
        # input(3, 32, 32) output(16, 28, 28)
        x = self.pool1(x)
        # output(16, 14, 14)
        x = F.relu(self.conv2(x))
        #(14-5)+1=10
        # output(32, 10, 10)
        x = self.pool2(x)
        # output(32, 5, 5)
        x = x.view(-1, 32*5*5)
        # output(32*5*5)
        x = F.relu(self.fc1(x))
        # output(120)
        x = F.relu(self.fc2(x))
        # output(84)
        x = self.fc3(x)
        # output(10)
        return x

3.查看模型输出:

这两行代码比较通用的,查看模型结构的时候直接写这两行代码接可以了

model=LeNet()
print(model)

4. 模型输出:

"""
LeNet(
  (conv1): Conv2d(3, 16, kernel_size=(5, 5), stride=(1, 1))
  (pool1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (conv2): Conv2d(16, 32, kernel_size=(5, 5), stride=(1, 1))
  (pool2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (fc1): Linear(in_features=800, out_features=120, bias=True)
  (fc2): Linear(in_features=120, out_features=84, bias=True)
  (fc3): Linear(in_features=84, out_features=10, bias=True)
)
"""

参考:
pytorh官方demo
论文地址:http://www.dengfanxin.cn/wp-content/uploads/2016/03/1998Lecun.pdf

相关标签: 卷积神经网络