- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊 | 接辅导、项目定制
- 🚀 文章来源:K同学的学习圈子
学习记录
在学习YOLOv5之前,必定要对v3和v4进行简要了解,上一周直接上手的v5,感觉有一些力不从心。这次从头来过,理清思路。
首先,要清楚YOLO系列算法主要是运用于目标检测领域。YOLO的全称是You Only Look Once,它们的结构都由输入层、卷积层、残差块、批量归一化层、激活函数层和输出层组成。其中,YOLOv3引入了一种新的结构单元——空间金字塔池化模块(Spatial Pyramid Pooling module, SPP),以提高模型的准确性。YOLOv4引入了更多改进,包括采用残差通道 attention 机制(Residual Channel Attention Mechanism, RCAM)、使用 Mish 激活函数以及更精细的训练策略等。YOLOv5在YOLOv4的基础上进一步改进了网络结构,并增加了模型的轻量化。
YOLO系列的最大亮点在于其实时性和高准确性的目标检测能力。与其他传统的两步目标检测方法相比,YOLO采取了一步到位的方法,它直接从一张图像中预测出所有的边界框和相应的类别概率。这使得YOLO可以在短时间内完成目标检测任务,大大提高了实时性。
YOLOv5的Backbone模块是一个骨干网络,用于提取图像的特征。在YOLOv5中,有两种类型的骨干网络可供选择:CSPDarknet53和Focus。
1.CSPDarknet53:这是一个基于Darknet-53的网络结构,通过添加残差连接(shortcut
connections)来提高训练速度和性能。Darknet-53由多个残差块组成,每个残差块包含两个卷积层和一个跳跃连接。此外,为了减少计算量,YOLOv5还对Darknet-53进行了一些优化,例如使用CSP(Cross Stage Partial)策略将卷积分组在一起进行计算。
2.Focus:这是一个轻量级的骨干网络,主要用于移动设备和嵌入式系统。Focus网络由多个卷积层组成,每个卷积层后面都跟着一个批归一化层和激活函数。与CSPDarknet53相比,Focus网络的结构更简单,参数更少,但性能略低。
空间金字塔池化模块(Spatial Pyramid Pooling module, SPP)是一种用于提取图像特征的池化技术,它是由何凯明等人在2016年提出的。它的主要目的是克服传统池化技术的局限性,即池化操作只关注某一特定尺度下的特征,而忽略了其他尺度下的特征。SPP模块通过将特征图分割成多个尺寸的子区域,并对每个子区域进行池化操作,将不同尺度的特征图融合在一起。这种方法可以提取到更多的上下文信息,有助于提高模型的准确性和鲁棒性。SPP模块已被广泛应用于各种计算机视觉任务中,如目标检测、语义分割和全景拼接等。
一、前期准备
1.设置GPU
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision
from torchvision import transforms, datasets
import os,PIL,pathlib,warnings
warnings.filterwarnings("ignore") #忽略警告信息
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device
device(type=‘cuda’)
2.导入数据
import os,PIL,random,pathlib
data_dir = './P3/'
data_dir = pathlib.Path(data_dir)
data_paths = list(data_dir.glob('*'))
classeNames = [str(path).split("\\")[1] for path in data_paths]
classeNames
[‘cloudy’, ‘rain’, ‘shine’, ‘sunrise’]
train_transforms = transforms.Compose([
transforms.Resize([224, 224]),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
test_transform = transforms.Compose([
transforms.Resize([224, 224]),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
total_data = datasets.ImageFolder("./P3/",transform=train_transforms)
total_data
Dataset ImageFolder
Number of datapoints: 1125
Root location: ./P3/
StandardTransform
Transform: Compose(
Resize(size=[224, 224], interpolation=bilinear, max_size=None, antialias=warn)
ToTensor()
Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
)
total_data.class_to_idx
{‘cloudy’: 0, ‘rain’: 1, ‘shine’: 2, ‘sunrise’: 3}
3.划分数据集
train_size = int(0.8 * len(total_data))
test_size = len(total_data) - train_size
train_dataset, test_dataset = torch.utils.data.random_split(total_data, [train_size, test_size])
train_dataset, test_dataset
(<torch.utils.data.dataset.Subset at 0x2c6247fd0a0>,
<torch.utils.data.dataset.Subset at 0x2c6247fd430>)
batch_size = 8
train_dl = torch.utils.data.DataLoader(train_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=1)
test_dl = torch.utils.data.DataLoader(test_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=1)
for X, y in test_dl:
print("Shape of X [N, C, H, W]: ", X.shape)
print("Shape of y: ", y.shape, y.dtype)
break
Shape of X [N, C, H, W]: torch.Size([8, 3, 224, 224])
Shape of y: torch.Size([8]) torch.int64
二、搭建包含Backbone模块的模型
1. 搭建模型
这里我将我对这个模型的理解以注释的方式体现
import torch.nn.functional as F
def autopad(k, p=None): #自动填充函数,根据卷积核大小为输入图像补零
if p is None:
p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
return p
class Conv(nn.Module):
# Standard convolution(定义了一个标准卷积层)
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):
# 卷积层,c1: 输入通道数,c2: 输出通道数, k: 卷积核大小, s: 步长, autopad: 自动填充函数,p: 填充方式,默认是k的一半
super().__init__()
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
self.bn = nn.BatchNorm2d(c2)#归一化处理
self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
#当输入act为True时,使用SiLU激活函数;否则如果act是一个Module,则直接使用act,否则使用Identity函数,也就是不加任何激活函数。
def forward(self, x):
return self.act(self.bn(self.conv(x)))
class Bottleneck(nn.Module):
# Standard bottleneck
def __init__(self, c1, c2, shortcut=True, g=3, e=0.5): # 输入通道数c1、输出通道数c2、是否使用快捷连接shortcut、分组数g和扩展因子e。
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv(c_, c2, 3, 1, g=g)
self.add = shortcut and c1 == c2
def forward(self, x):
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
class C3(nn.Module):
# CSP Bottleneck with 3 convolutions
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.6): # ch_in, ch_out, number, shortcut, groups, expansion
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv(c1, c_, 1, 1)
self.cv3 = Conv(2 * c_, c2, 1) # act=FReLU(c2)
self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
#扩展因子e被设置为1.0,每个残差模块的输出通道数等于输入通道数
def forward(self, x):
return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))
#将张量x传递给卷积层self.cv1。将卷积后结果与x进行拼接,使用torch.cat函数沿着第1个维度(dim=1)进行拼接。
#然后重复,最后将拼接后的结果传递给全连接层self.cv3进行线性变换。返回全连接层的输出结果作为前向传播的最终输出。
class SPPF(nn.Module):
def __init__(self, c1, c2, k=5):
super().__init__()
c_ = c1 // 2 # hidden channels
#创建两个卷积层self.cv1和self.cv2,分别用于处理输入特征图和生成输出特征图。
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv(c_ * 4, c2, 1, 1)
self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
def forward(self, x):
x = self.cv1(x)
with warnings.catch_warnings():
warnings.simplefilter('ignore')
y1 = self.m(x)
y2 = self.m(y1)
return self.cv2(torch.cat([x, y1, y2, self.m(y2)], 1))
class YOLOv5_backbone(nn.Module):#构建YOLOv5模型的骨干网络
def __init__(self):
super(YOLOv5_backbone, self).__init__()
#创建了两个卷积层和四个C3模块,进行一系列操作
self.Conv_1 = Conv(3, 64, 3, 2, 2)
self.Conv_2 = Conv(64, 128, 3, 2)
self.C3_3 = C3(128,128)
self.Conv_4 = Conv(128, 256, 3, 2)
self.C3_5 = C3(256,256)
self.Conv_6 = Conv(256, 512, 3, 2)
self.C3_7 = C3(512,512)
self.Conv_8 = Conv(512, 1024, 3, 2)
self.C3_9 = C3(1024, 1024)
self.SPPF = SPPF(1024, 1024, 5)
self.classifier = nn.Sequential(
nn.Linear(in_features=65536, out_features=100),
nn.ReLU(),
nn.Linear(in_features=100, out_features=4)#定义一个序列模型,包含三个线性层和一个ReLU激活函数。
#第一个线性层将输入特征映射到100个特征,第二个线性层将100个特征映射到4个特征,最后一个ReLU激活函数用于增加非线性。
)
def forward(self, x):
x = self.Conv_1(x)
x = self.Conv_2(x)
x = self.C3_3(x)
x = self.Conv_4(x)
x = self.C3_5(x)
x = self.Conv_6(x)
x = self.C3_7(x)
x = self.Conv_8(x)
x = self.C3_9(x)
x = self.SPPF(x)
x = torch.flatten(x, start_dim=1)
x = self.classifier(x)
return x
device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))
model = YOLOv5_backbone().to(device)
model
Using cuda device
YOLOv5_backbone(
(Conv_1): Conv(
(conv): Conv2d(3, 64, kernel_size=(3, 3), stride=(2, 2), padding=(2, 2), bias=False)
(bn): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(Conv_2): Conv(
(conv): Conv2d(64, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
(bn): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(C3_3): C3(
(cv1): Conv(
(conv): Conv2d(128, 76, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn): BatchNorm2d(76, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(cv2): Conv(
(conv): Conv2d(128, 76, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn): BatchNorm2d(76, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(cv3): Conv(
(conv): Conv2d(152, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(m): Sequential(
(0): Bottleneck(
(cv1): Conv(
(conv): Conv2d(76, 76, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn): BatchNorm2d(76, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(cv2): Conv(
(conv): Conv2d(76, 76, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn): BatchNorm2d(76, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
)
)
)
(Conv_4): Conv(
(conv): Conv2d(128, 256, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
(bn): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(C3_5): C3(
(cv1): Conv(
(conv): Conv2d(256, 153, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn): BatchNorm2d(153, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(cv2): Conv(
(conv): Conv2d(256, 153, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn): BatchNorm2d(153, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(cv3): Conv(
(conv): Conv2d(306, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(m): Sequential(
(0): Bottleneck(
(cv1): Conv(
(conv): Conv2d(153, 153, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn): BatchNorm2d(153, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(cv2): Conv(
(conv): Conv2d(153, 153, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn): BatchNorm2d(153, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
)
)
)
(Conv_6): Conv(
(conv): Conv2d(256, 512, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
(bn): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(C3_7): C3(
(cv1): Conv(
(conv): Conv2d(512, 307, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn): BatchNorm2d(307, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(cv2): Conv(
(conv): Conv2d(512, 307, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn): BatchNorm2d(307, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(cv3): Conv(
(conv): Conv2d(614, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(m): Sequential(
(0): Bottleneck(
(cv1): Conv(
(conv): Conv2d(307, 307, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn): BatchNorm2d(307, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(cv2): Conv(
(conv): Conv2d(307, 307, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn): BatchNorm2d(307, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
)
)
)
(Conv_8): Conv(
(conv): Conv2d(512, 1024, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
(bn): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(C3_9): C3(
(cv1): Conv(
(conv): Conv2d(1024, 614, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn): BatchNorm2d(614, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(cv2): Conv(
(conv): Conv2d(1024, 614, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn): BatchNorm2d(614, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(cv3): Conv(
(conv): Conv2d(1228, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(m): Sequential(
(0): Bottleneck(
(cv1): Conv(
(conv): Conv2d(614, 614, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn): BatchNorm2d(614, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(cv2): Conv(
(conv): Conv2d(614, 614, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn): BatchNorm2d(614, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
)
)
)
(SPPF): SPPF(
(cv1): Conv(
(conv): Conv2d(1024, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(cv2): Conv(
(conv): Conv2d(2048, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(act): SiLU()
)
(m): MaxPool2d(kernel_size=5, stride=1, padding=2, dilation=1, ceil_mode=False)
)
(classifier): Sequential(
(0): Linear(in_features=65536, out_features=100, bias=True)
(1): ReLU()
(2): Linear(in_features=100, out_features=4, bias=True)
)
)
import torchsummary as summary
2. 查看模型详情
import torchsummary as summary
summary.summary(model, (3, 224, 224))
Layer (type) Output Shape Param #
Conv2d-1 [-1, 64, 113, 113] 1,728
BatchNorm2d-2 [-1, 64, 113, 113] 128
SiLU-3 [-1, 64, 113, 113] 0
Conv-4 [-1, 64, 113, 113] 0
Conv2d-5 [-1, 128, 57, 57] 73,728
BatchNorm2d-6 [-1, 128, 57, 57] 256
SiLU-7 [-1, 128, 57, 57] 0
Conv-8 [-1, 128, 57, 57] 0
Conv2d-9 [-1, 76, 57, 57] 9,728
BatchNorm2d-10 [-1, 76, 57, 57] 152
SiLU-11 [-1, 76, 57, 57] 0
Conv-12 [-1, 76, 57, 57] 0
Conv2d-13 [-1, 76, 57, 57] 5,776
BatchNorm2d-14 [-1, 76, 57, 57] 152
SiLU-15 [-1, 76, 57, 57] 0
Conv-16 [-1, 76, 57, 57] 0
Conv2d-17 [-1, 76, 57, 57] 51,984
BatchNorm2d-18 [-1, 76, 57, 57] 152
SiLU-19 [-1, 76, 57, 57] 0
Conv-20 [-1, 76, 57, 57] 0
Bottleneck-21 [-1, 76, 57, 57] 0
Conv2d-22 [-1, 76, 57, 57] 9,728
BatchNorm2d-23 [-1, 76, 57, 57] 152
SiLU-24 [-1, 76, 57, 57] 0
Conv-25 [-1, 76, 57, 57] 0
Conv2d-26 [-1, 128, 57, 57] 19,456
BatchNorm2d-27 [-1, 128, 57, 57] 256
SiLU-28 [-1, 128, 57, 57] 0
Conv-29 [-1, 128, 57, 57] 0
C3-30 [-1, 128, 57, 57] 0
Conv2d-31 [-1, 256, 29, 29] 294,912
BatchNorm2d-32 [-1, 256, 29, 29] 512
SiLU-33 [-1, 256, 29, 29] 0
Conv-34 [-1, 256, 29, 29] 0
Conv2d-35 [-1, 153, 29, 29] 39,168
BatchNorm2d-36 [-1, 153, 29, 29] 306
SiLU-37 [-1, 153, 29, 29] 0
Conv-38 [-1, 153, 29, 29] 0
Conv2d-39 [-1, 153, 29, 29] 23,409
BatchNorm2d-40 [-1, 153, 29, 29] 306
SiLU-41 [-1, 153, 29, 29] 0
Conv-42 [-1, 153, 29, 29] 0
Conv2d-43 [-1, 153, 29, 29] 210,681
BatchNorm2d-44 [-1, 153, 29, 29] 306
SiLU-45 [-1, 153, 29, 29] 0
Conv-46 [-1, 153, 29, 29] 0
Bottleneck-47 [-1, 153, 29, 29] 0
Conv2d-48 [-1, 153, 29, 29] 39,168
BatchNorm2d-49 [-1, 153, 29, 29] 306
SiLU-50 [-1, 153, 29, 29] 0
Conv-51 [-1, 153, 29, 29] 0
Conv2d-52 [-1, 256, 29, 29] 78,336
BatchNorm2d-53 [-1, 256, 29, 29] 512
SiLU-54 [-1, 256, 29, 29] 0
Conv-55 [-1, 256, 29, 29] 0
C3-56 [-1, 256, 29, 29] 0
Conv2d-57 [-1, 512, 15, 15] 1,179,648
BatchNorm2d-58 [-1, 512, 15, 15] 1,024
SiLU-59 [-1, 512, 15, 15] 0
Conv-60 [-1, 512, 15, 15] 0
Conv2d-61 [-1, 307, 15, 15] 157,184
BatchNorm2d-62 [-1, 307, 15, 15] 614
SiLU-63 [-1, 307, 15, 15] 0
Conv-64 [-1, 307, 15, 15] 0
Conv2d-65 [-1, 307, 15, 15] 94,249
BatchNorm2d-66 [-1, 307, 15, 15] 614
SiLU-67 [-1, 307, 15, 15] 0
Conv-68 [-1, 307, 15, 15] 0
Conv2d-69 [-1, 307, 15, 15] 848,241
BatchNorm2d-70 [-1, 307, 15, 15] 614
SiLU-71 [-1, 307, 15, 15] 0
Conv-72 [-1, 307, 15, 15] 0
Bottleneck-73 [-1, 307, 15, 15] 0
Conv2d-74 [-1, 307, 15, 15] 157,184
BatchNorm2d-75 [-1, 307, 15, 15] 614
SiLU-76 [-1, 307, 15, 15] 0
Conv-77 [-1, 307, 15, 15] 0
Conv2d-78 [-1, 512, 15, 15] 314,368
BatchNorm2d-79 [-1, 512, 15, 15] 1,024
SiLU-80 [-1, 512, 15, 15] 0
Conv-81 [-1, 512, 15, 15] 0
C3-82 [-1, 512, 15, 15] 0
Conv2d-83 [-1, 1024, 8, 8] 4,718,592
BatchNorm2d-84 [-1, 1024, 8, 8] 2,048
SiLU-85 [-1, 1024, 8, 8] 0
Conv-86 [-1, 1024, 8, 8] 0
Conv2d-87 [-1, 614, 8, 8] 628,736
BatchNorm2d-88 [-1, 614, 8, 8] 1,228
SiLU-89 [-1, 614, 8, 8] 0
Conv-90 [-1, 614, 8, 8] 0
Conv2d-91 [-1, 614, 8, 8] 376,996
BatchNorm2d-92 [-1, 614, 8, 8] 1,228
SiLU-93 [-1, 614, 8, 8] 0
Conv-94 [-1, 614, 8, 8] 0
Conv2d-95 [-1, 614, 8, 8] 3,392,964
BatchNorm2d-96 [-1, 614, 8, 8] 1,228
SiLU-97 [-1, 614, 8, 8] 0
Conv-98 [-1, 614, 8, 8] 0
Bottleneck-99 [-1, 614, 8, 8] 0
Conv2d-100 [-1, 614, 8, 8] 628,736
BatchNorm2d-101 [-1, 614, 8, 8] 1,228
SiLU-102 [-1, 614, 8, 8] 0
Conv-103 [-1, 614, 8, 8] 0
Conv2d-104 [-1, 1024, 8, 8] 1,257,472
BatchNorm2d-105 [-1, 1024, 8, 8] 2,048
SiLU-106 [-1, 1024, 8, 8] 0
Conv-107 [-1, 1024, 8, 8] 0
C3-108 [-1, 1024, 8, 8] 0
Conv2d-109 [-1, 512, 8, 8] 524,288
BatchNorm2d-110 [-1, 512, 8, 8] 1,024
SiLU-111 [-1, 512, 8, 8] 0
Conv-112 [-1, 512, 8, 8] 0
MaxPool2d-113 [-1, 512, 8, 8] 0
MaxPool2d-114 [-1, 512, 8, 8] 0
MaxPool2d-115 [-1, 512, 8, 8] 0
Conv2d-116 [-1, 1024, 8, 8] 2,097,152
BatchNorm2d-117 [-1, 1024, 8, 8] 2,048
SiLU-118 [-1, 1024, 8, 8] 0
Conv-119 [-1, 1024, 8, 8] 0
SPPF-120 [-1, 1024, 8, 8] 0
Linear-121 [-1, 100] 6,553,700
ReLU-122 [-1, 100] 0
Linear-123 [-1, 4] 404
Total params: 23,807,796 Trainable params: 23,807,796 Non-trainable
params: 0
---------------------------------------------------------------- Input size (MB): 0.57 Forward/backward pass size (MB): 147.71 Params size
(MB): 90.82 Estimated Total Size (MB): 239.10
---------------------------------------------------------------- def train(dataloader, model, loss_fn, optimizer):
三、 训练模型
1. 编写训练函数
def train(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset)
num_batches = len(dataloader)
train_loss, train_acc = 0, 0
for X, y in dataloader:
X, y = X.to(device), y.to(device)
pred = model(X)
loss = loss_fn(pred, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
train_acc += (pred.argmax(1) == y).type(torch.float).sum().item()
train_loss += loss.item()
train_acc /= size
train_loss /= num_batches
return train_acc, train_loss
2.编写测试函数
def test (dataloader, model, loss_fn):
size = len(dataloader.dataset)
num_batches = len(dataloader)
test_loss, test_acc = 0, 0
with torch.no_grad():
for imgs, target in dataloader:
imgs, target = imgs.to(device), target.to(device)
# 计算loss
target_pred = model(imgs)
loss = loss_fn(target_pred, target)
test_loss += loss.item()
test_acc += (target_pred.argmax(1) == target).type(torch.float).sum().item()
test_acc /= size
test_loss /= num_batches
return test_acc, test_loss
3.正式训练
import copy
optimizer = torch.optim.Adam(model.parameters(), lr= 1e-5)
loss_fn = nn.CrossEntropyLoss()
epochs = 20
train_loss = []
train_acc = []
test_loss = []
test_acc = []
best_acc = 0
for epoch in range(epochs):
model.train()
epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, optimizer)
model.eval()
epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)
if epoch_test_acc > best_acc:
best_acc = epoch_test_acc
best_model = copy.deepcopy(model)
train_acc.append(epoch_train_acc)
train_loss.append(epoch_train_loss)
test_acc.append(epoch_test_acc)
test_loss.append(epoch_test_loss)
lr = optimizer.state_dict()['param_groups'][0]['lr']
template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%, Test_loss:{:.3f}, Lr:{:.2E}')
print(template.format(epoch+1, epoch_train_acc*100, epoch_train_loss,
epoch_test_acc*100, epoch_test_loss, lr))
PATH = './best_model.pth'
torch.save(best_model.state_dict(), PATH)
print('Done')
Epoch: 1, Train_acc:59.6%, Train_loss:0.964, Test_acc:72.0%, Test_loss:0.727, Lr:1.00E-05
Epoch: 2, Train_acc:69.8%, Train_loss:0.745, Test_acc:66.2%, Test_loss:0.611, Lr:1.00E-05
Epoch: 3, Train_acc:72.4%, Train_loss:0.625, Test_acc:78.7%, Test_loss:0.492, Lr:1.00E-05
Epoch: 4, Train_acc:80.6%, Train_loss:0.497, Test_acc:85.3%, Test_loss:0.393, Lr:1.00E-05
Epoch: 5, Train_acc:83.9%, Train_loss:0.412, Test_acc:80.9%, Test_loss:0.360, Lr:1.00E-05
Epoch: 6, Train_acc:86.6%, Train_loss:0.364, Test_acc:86.2%, Test_loss:0.298, Lr:1.00E-05
Epoch: 7, Train_acc:89.2%, Train_loss:0.292, Test_acc:93.3%, Test_loss:0.225, Lr:1.00E-05
Epoch: 8, Train_acc:90.1%, Train_loss:0.250, Test_acc:92.4%, Test_loss:0.197, Lr:1.00E-05
Epoch: 9, Train_acc:91.4%, Train_loss:0.248, Test_acc:94.7%, Test_loss:0.269, Lr:1.00E-05
Epoch:10, Train_acc:92.2%, Train_loss:0.202, Test_acc:92.0%, Test_loss:0.263, Lr:1.00E-05
Epoch:11, Train_acc:94.7%, Train_loss:0.171, Test_acc:86.2%, Test_loss:0.445, Lr:1.00E-05
Epoch:12, Train_acc:94.3%, Train_loss:0.175, Test_acc:90.2%, Test_loss:0.244, Lr:1.00E-05
Epoch:13, Train_acc:94.2%, Train_loss:0.155, Test_acc:92.4%, Test_loss:0.238, Lr:1.00E-05
Epoch:14, Train_acc:96.2%, Train_loss:0.118, Test_acc:90.7%, Test_loss:0.330, Lr:1.00E-05
Epoch:15, Train_acc:95.4%, Train_loss:0.124, Test_acc:93.8%, Test_loss:0.158, Lr:1.00E-05
Epoch:16, Train_acc:97.2%, Train_loss:0.093, Test_acc:91.1%, Test_loss:0.270, Lr:1.00E-05
Epoch:17, Train_acc:96.6%, Train_loss:0.104, Test_acc:92.0%, Test_loss:0.248, Lr:1.00E-05
Epoch:18, Train_acc:98.1%, Train_loss:0.071, Test_acc:94.7%, Test_loss:0.219, Lr:1.00E-05
Epoch:19, Train_acc:97.2%, Train_loss:0.072, Test_acc:92.4%, Test_loss:0.207, Lr:1.00E-05
Epoch:20, Train_acc:97.4%, Train_loss:0.082, Test_acc:94.7%, Test_loss:0.216, Lr:1.00E-05
Done
四、 结果可视化
1. Loss与Accuracy图
import matplotlib.pyplot as plt
#隐藏警告
import warnings
warnings.filterwarnings("ignore") #忽略警告信息
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
plt.rcParams['figure.dpi'] = 100 #分辨率
epochs_range = range(epochs)
plt.figure(figsize=(12, 3))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, train_loss, label='Training Loss')
plt.plot(epochs_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
2. 模型评估
best_model.load_state_dict(torch.load(PATH, map_location=device))
epoch_test_acc, epoch_test_loss = test(test_dl, best_model, loss_fn)
epoch_test_acc, epoch_test_loss
(0.9466666666666667, 0.19661984669751134)
epoch_test_acc
0.9466666666666667