目标检测——LeNet
demo的流程
- model.py ——定义LeNet网络模型
- train.py ——加载数据集并训练,训练集计算loss,测试集计算accuracy,保存训练好的网络参数
- predict.py——得到训练好的网络参数后,用自己找的图像进行分类测试
目录
1. model.py
先给出代码,模型是基于LeNet做简单修改,层数很浅,容易理解:
# 使用torch.nn包来构建神经网络.
import torch.nn as nn
import torch.nn.functional as F
class LeNet(nn.Module): # 继承于nn.Module这个父类
def __init__(self): # 初始化网络结构
super(LeNet, self).__init__() # 多继承需用到super函数
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)) # input(3, 32, 32) output(16, 28, 28)
x = self.pool1(x) # output(16, 14, 14)
x = F.relu(self.conv2(x)) # 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
需注意:
- pytorch 中 tensor(也就是输入输出层)的 通道排序为:
[batch, channel, height, width]
- pytorch中的卷积、池化、输入输出层中参数的含义与位置,如下图:
1.1 卷积 Conv2d
我们常用的卷积(Conv2d)在pytorch中对应的函数是:
torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros')
一般使用时关注以下几个参数即可:
- in_channels:输入特征矩阵的深度。如输入一张RGB彩色图像,那in_channels=3
- out_channels:输入特征矩阵的深度。也等于卷积核的个数,使用n个卷积核输出的特征矩阵深度就是n
- kernel_size:卷积核的尺寸。可以是int类型,如3 代表卷积核的height=width=3,也可以是 tuple类型如(3, 5)代表卷积核的height=3,width=5
- stride:卷积核的步长。默认为1,和kernel_size一样输入可以是int型,也可以是tuple类型
- padding:补零操作,默认为0。可以为int型如1即补一圈0,如果输入为tuple型如(2, 1) 代表在上下补2行,左右补1列。
附上pytorch官网上的公式:
经卷积后的输出层尺寸计算公式为:
- 输入图片大小 W×W(一般情况下Width=Height)
- Filter大小 F×F
- 步长 S
- padding的像素数 P
若计算结果不为整数呢?pytorch中的卷积操作详解