365天深度学习训练营-第P8周:YOLOv5-C3模块实现

  • 本文为365天深度学习训练营 中的学习记录博客
  • 参考文章:Pytorch实战 | 第P8天:YOLOv5-C3模块实现(训练营内部成员可读)
  • 原作者:K同学啊|接辅导、项目定制

目录

  • 一、课题背景和开发环境
    • 开发环境
  • 二、前期准备
    • 1.设置GPU
    • 2.导入数据并划分数据集
    • 3.数据可视化
  • 三、搭建包含C3模块的模型
  • 四、训练模型
    • 1.编写训练函数
    • 2.编写测试函数
    • 3.正式训练
  • 五、结果可视化&模型评估
    • 1.训练结果可视化
    • 2.模型评估

一、课题背景和开发环境

第P8周:YOLOv5-C3模块实现

  • 难度:夯实基础⭐⭐
  • 语言:Python3、Pytorch

要求:

  • 本次我将利用YOLOv5算法中的C3模块搭建网络,后续理论部分介绍将在语雀以及公众号(K同学啊)中详细展开,这里主要让大家先了解C3的结构,方便后续YOLOv5算法的学习。

开发环境

  • 电脑系统:Windows 10
  • 语言环境:Python 3.8.2
  • 编译器:无(直接在cmd.exe内运行)
  • 深度学习环境:Pytorch
  • 显卡及显存:NVIDIA GeForce GTX 1660 Ti 12G
  • CUDA版本:Release 10.2, V10.2.89(cmd输入nvcc -Vnvcc --version指令可查看)
  • 数据:K同学啊的百度网盘

二、前期准备

1.设置GPU

如果设备上支持GPU就使用GPU,否则使用CPU

import torch
import torchvision

if __name__=='__main__':
    ''' 设置GPU '''
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    print("Using {} device\n".format(device))
Using cuda device

2.导入数据并划分数据集

import os
import PIL
import random
import pathlib
import warnings
import numpy as np
import matplotlib.pyplot as plt

''' 读取本地数据集并划分训练集与测试集 '''
def localDataset(data_dir):
    data_dir = pathlib.Path(data_dir)
    
    # 读取本地数据集
    data_paths = list(data_dir.glob('*'))
    classeNames = [str(path).split("\\")[-1] for path in data_paths]
    
    # 关于transforms.Compose的更多介绍可以参考:https://blog.csdn.net/qq_38251616/article/details/124878863
    train_transforms = torchvision.transforms.Compose([
        torchvision.transforms.Resize([224, 224]),  # 将输入图片resize成统一尺寸
        # torchvision.transforms.RandomHorizontalFlip(), # 随机水平翻转
        torchvision.transforms.ToTensor(),          # 将PIL Image或numpy.ndarray转换为tensor,并归一化到[0,1]之间
        torchvision.transforms.Normalize(           # 标准化处理-->转换为标准正太分布(高斯分布),使模型更容易收敛
            mean=[0.485, 0.456, 0.406], 
            std=[0.229, 0.224, 0.225])  # 其中 mean=[0.485,0.456,0.406]与std=[0.229,0.224,0.225] 从数据集中随机抽样计算得到的。
    ])
    
    total_dataset = torchvision.datasets.ImageFolder(data_dir, transform=train_transforms)
    print(total_dataset, '\n')
    print(total_dataset.class_to_idx, '\n')
    
    # 划分训练集与测试集
    train_size = int(0.8 * len(total_dataset))
    test_size  = len(total_dataset) - train_size
    print('train_size', train_size, 'test_size', test_size, '\n')
    train_dataset, test_dataset = torch.utils.data.random_split(total_dataset, [train_size, test_size])
    
    return classeNames, train_dataset, test_dataset


''' 加载数据,并设置batch_size '''
def loadData(train_ds, test_ds, batch_size=32, root='', show_flag=False):
    # 从 train_ds 加载训练集
    train_dl = torch.utils.data.DataLoader(train_ds,
                                           batch_size=batch_size,
                                           shuffle=True,
                                           num_workers=1)
    # 从 test_ds 加载测试集
    test_dl  = torch.utils.data.DataLoader(test_ds,
                                           batch_size=batch_size,
                                           shuffle=True,
                                           num_workers=1)
    
    # 取一个批次查看数据格式
    # 数据的shape为:[batch_size, channel, height, weight]
    # 其中batch_size为自己设定,channel,height和weight分别是图片的通道数,高度和宽度。
    for X, y in test_dl:
        print('Shape of X [N, C, H, W]: ', X.shape)
        print('Shape of y: ', y.shape, y.dtype, '\n')
        break
    
    imgs, labels = next(iter(train_dl))
    print('Image shape: ', imgs.shape, '\n')
    # torch.Size([32, 3, 224, 224])  # 所有数据集中的图像都是224*224的RGB图
    displayData(imgs, root, show_flag)
    return train_dl, test_dl


batch_size = 4
data_dir = './data/weather_photos/'
train_ds, test_ds = localDataset(data_dir)
train_dl, test_dl = loadData(train_ds, test_ds, batch_size, data_dir, True)
Dataset ImageFolder
    Number of datapoints: 1125
    Root location: data\weather_photos
    StandardTransform
Transform: Compose(
               Resize(size=[224, 224], interpolation=bilinear)
               ToTensor()
               Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
           )

{'cloudy': 0, 'rain': 1, 'shine': 2, 'sunrise': 3}

train_size 900 test_size 225

num_classes 4
Shape of X [N, C, H, W]:  torch.Size([4, 3, 224, 224])
Shape of y:  torch.Size([4]) torch.int64

Image shape:  torch.Size([4, 3, 224, 224])

3.数据可视化

''' 数据可视化 '''
def displayData(imgs, root='', flag=False):
    # 指定图片大小,图像大小为20宽、5高的绘图(单位为英寸inch)
    plt.figure('Data Visualization', figsize=(20, 5)) 
    for i, imgs in enumerate(imgs[:20]):
        # 维度顺序调整 [3, 224, 224]->[224, 224, 3]
        npimg = imgs.numpy().transpose((1, 2, 0))
        # 将整个figure分成2行10列,绘制第i+1个子图。
        plt.subplot(2, 10, i+1)
        plt.imshow(npimg)  # cmap=plt.cm.binary
        plt.axis('off')
    plt.savefig(os.path.join(root, 'DatasetDisplay.png'))
    if flag:
        plt.show()
    else:
        plt.close('all')

数据可视化


三、搭建包含C3模块的模型

对于一般的CNN网络来说,都是由特征提取网络和分类网络构成,其中特征提取网络用于提取图片的特征,分类网络用于将图片进行分类。

K同学啊提示:是否可以尝试通过增加/调整C3模块与Conv模块来提高准确率?
365天深度学习训练营-第P8周:YOLOv5-C3模块实现_第1张图片

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


''' 搭建包含C3模块的模型 '''
def autopad(k, p=None):  # kernel, padding
    # Pad to 'same'
    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):  # ch_in, ch_out, kernel, stride, padding, groups
        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())
    
    def forward(self, x):
        return self.act(self.bn(self.conv(x)))
    
    def forward_fuse(self, x):
        return self.act(self.conv(x))


class Bottleneck(nn.Module):
    # Standard bottleneck
    def __init__(self, c1, c2, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, shortcut, groups, expansion
        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.5):  # 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)))
    
    def forward(self, x):
        return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))


class Model_K(nn.Module):
    def __init__(self):
        super(Model_K, self).__init__()
        
        # 卷积模块
        self.Conv = Conv(3, 32, 3, 2) 
        
        # C3模块1
        self.C3_1 = C3(32, 64, 3, 2)
        
        # 全连接网络层,用于分类
        self.classifier = nn.Sequential(
            nn.Linear(in_features=802816, out_features=100),
            nn.ReLU(),
            nn.Linear(in_features=100, out_features=4)
        )
    
    def forward(self, x):
        x = self.Conv(x)
        x = self.C3_1(x)
        x = torch.flatten(x, start_dim=1)
        x = self.classifier(x)

        return x


device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using {} device\n".format(device))
''' 调用并将模型转移到GPU中(我们模型运行均在GPU中进行) '''
model = Model_K().to(device)
''' 显示网络结构 '''
torchsummary.summary(model, (3, 224, 224))
print(model)
Using cuda device

----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1         [-1, 32, 112, 112]             864
       BatchNorm2d-2         [-1, 32, 112, 112]              64
              SiLU-3         [-1, 32, 112, 112]               0
              Conv-4         [-1, 32, 112, 112]               0
            Conv2d-5         [-1, 32, 112, 112]           1,024
       BatchNorm2d-6         [-1, 32, 112, 112]              64
              SiLU-7         [-1, 32, 112, 112]               0
              Conv-8         [-1, 32, 112, 112]               0
            Conv2d-9         [-1, 32, 112, 112]           1,024
      BatchNorm2d-10         [-1, 32, 112, 112]              64
             SiLU-11         [-1, 32, 112, 112]               0
             Conv-12         [-1, 32, 112, 112]               0
           Conv2d-13         [-1, 32, 112, 112]           9,216
      BatchNorm2d-14         [-1, 32, 112, 112]              64
             SiLU-15         [-1, 32, 112, 112]               0
             Conv-16         [-1, 32, 112, 112]               0
       Bottleneck-17         [-1, 32, 112, 112]               0
           Conv2d-18         [-1, 32, 112, 112]           1,024
      BatchNorm2d-19         [-1, 32, 112, 112]              64
             SiLU-20         [-1, 32, 112, 112]               0
             Conv-21         [-1, 32, 112, 112]               0
           Conv2d-22         [-1, 32, 112, 112]           9,216
      BatchNorm2d-23         [-1, 32, 112, 112]              64
             SiLU-24         [-1, 32, 112, 112]               0
             Conv-25         [-1, 32, 112, 112]               0
       Bottleneck-26         [-1, 32, 112, 112]               0
           Conv2d-27         [-1, 32, 112, 112]           1,024
      BatchNorm2d-28         [-1, 32, 112, 112]              64
             SiLU-29         [-1, 32, 112, 112]               0
             Conv-30         [-1, 32, 112, 112]               0
           Conv2d-31         [-1, 32, 112, 112]           9,216
      BatchNorm2d-32         [-1, 32, 112, 112]              64
             SiLU-33         [-1, 32, 112, 112]               0
             Conv-34         [-1, 32, 112, 112]               0
       Bottleneck-35         [-1, 32, 112, 112]               0
           Conv2d-36         [-1, 32, 112, 112]           1,024
      BatchNorm2d-37         [-1, 32, 112, 112]              64
             SiLU-38         [-1, 32, 112, 112]               0
             Conv-39         [-1, 32, 112, 112]               0
           Conv2d-40         [-1, 64, 112, 112]           4,096
      BatchNorm2d-41         [-1, 64, 112, 112]             128
             SiLU-42         [-1, 64, 112, 112]               0
             Conv-43         [-1, 64, 112, 112]               0
               C3-44         [-1, 64, 112, 112]               0
           Linear-45                  [-1, 100]      80,281,700
             ReLU-46                  [-1, 100]               0
           Linear-47                    [-1, 4]             404
================================================================
Total params: 80,320,536
Trainable params: 80,320,536
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.57
Forward/backward pass size (MB): 150.06
Params size (MB): 306.40
Estimated Total Size (MB): 457.04
----------------------------------------------------------------
Model_K(
  (Conv): Conv(
    (conv): Conv2d(3, 32, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
    (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (act): SiLU()
  )
  (C3_1): C3(
    (cv1): Conv(
      (conv): Conv2d(32, 32, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (act): SiLU()
    )
    (cv2): Conv(
      (conv): Conv2d(32, 32, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (act): SiLU()
    )
    (cv3): Conv(
      (conv): Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (act): SiLU()
    )
    (m): Sequential(
      (0): Bottleneck(
        (cv1): Conv(
          (conv): Conv2d(32, 32, kernel_size=(1, 1), stride=(1, 1), bias=False)
          (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
          (act): SiLU()
        )
        (cv2): Conv(
          (conv): Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
          (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
          (act): SiLU()
        )
      )
      (1): Bottleneck(
        (cv1): Conv(
          (conv): Conv2d(32, 32, kernel_size=(1, 1), stride=(1, 1), bias=False)
          (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
          (act): SiLU()
        )
        (cv2): Conv(
          (conv): Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
          (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
          (act): SiLU()
        )
      )
      (2): Bottleneck(
        (cv1): Conv(
          (conv): Conv2d(32, 32, kernel_size=(1, 1), stride=(1, 1), bias=False)
          (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
          (act): SiLU()
        )
        (cv2): Conv(
          (conv): Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
          (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
          (act): SiLU()
        )
      )
    )
  )
  (classifier): Sequential(
    (0): Linear(in_features=802816, out_features=100, bias=True)
    (1): ReLU()
    (2): Linear(in_features=100, out_features=4, bias=True)
  )
)

四、训练模型

1.编写训练函数

optimizer.zero_grad()
loss.backward()
optimizer.step()
关于以上三个函数,我在之前的文章中有做说明,这里不再赘述

# 训练循环
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)  # 计算网络输出和真实值之间的差距,targets为真实值,计算二者差值即为损失
        
        # 反向传播
        optimizer.zero_grad()  # grad属性归零
        loss.backward()        # 反向传播
        optimizer.step()       # 每一步自动更新
        
        # 记录acc与loss
        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.正式训练

model.train()
model.eval()

关于以上两个个函数,我在之前的文章中有做说明,这里不再赘述

start_epoch = 0
epochs      = 50
learn_rate  = 1e-4 # 初始学习率
loss_fn     = nn.CrossEntropyLoss()  # 创建损失函数
#optimizer   = torch.optim.SGD(model.parameters(), lr=learn_rate)
optimizer   = torch.optim.Adam(model.parameters(),lr=learn_rate)
# 调用官方动态学习率接口时使用
#lambda1 = lambda epoch: 0.92 ** (epoch // 4)
#scheduler   = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda1)  # 选定调整方法

train_loss  = []
train_acc   = []
test_loss   = []
test_acc    = []
epoch_best_acc = 0

''' 加载之前保存的模型 '''
if not os.path.exists(output) or not os.path.isdir(output):
    os.makedirs(output)
if start_epoch > 0:
    resumeFile = os.path.join(output, 'epoch'+str(start_epoch)+'.pkl')
    if not os.path.exists(resumeFile) or not os.path.isfile(resumeFile):
        start_epoch = 0
    else:
        model.load_state_dict(torch.load(resumeFile))  # 加载模型参数

''' 加载之前保存的模型 '''
    if not os.path.exists(output) or not os.path.isdir(output):
        os.makedirs(output)
    if start_epoch > 0:
        resumeFile = os.path.join(output, 'epoch'+str(start_epoch)+'.pkl')
        if not os.path.exists(resumeFile) or not os.path.isfile(resumeFile):
            start_epoch = 0
        else:
            model.load_state_dict(torch.load(resumeFile))  # 加载模型参数
    
''' 开始训练模型 '''
print('\nStart training...')
best_model = None
for epoch in range(start_epoch, epochs):
    # 更新学习率(使用自定义学习率时使用)
    # adjust_learning_rate(optimizer, epoch, learn_rate)
    
    model.train()
    epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, optimizer)
    # scheduler.step() # 更新学习率(调用官方动态学习率接口时使用)
    
    model.eval()
    epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)
    
    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(time.strftime('[%Y-%m-%d %H:%M:%S]'), template.format(epoch+1, epoch_train_acc*100, epoch_train_loss, epoch_test_acc*100, epoch_test_loss, lr))
    
    # 保存最佳模型
    if epoch_test_acc>epoch_best_acc:
        ''' 保存最优模型参数 '''
        epoch_best_acc = epoch_test_acc
        best_model = copy.deepcopy(model)
        print(('acc = {:.1f}%, saving model to best.pkl').format(epoch_best_acc*100))
        saveFile = os.path.join(output, 'best.pkl')
        torch.save(best_model.state_dict(), saveFile)
    if epoch_test_acc==1 and epoch_train_acc==1:
        saveFile = os.path.join(output, 'epoch'+str(epoch+1)+'.pkl')
        torch.save(model.state_dict(), saveFile)
print('Done\n')

''' 保存模型参数 '''
saveFile = os.path.join(output, 'epoch'+str(epochs)+'.pkl')
torch.save(model.state_dict(), saveFile)
Start training...
[2022-11-17 13:52:32] Epoch: 1, Train_acc:68.4%, Train_loss:1.552, Test_acc:83.1%, Test_loss:0.648, Lr:1.00E-04
acc = 83.1%, saving model to best.pkl
[2022-11-17 13:52:56] Epoch: 2, Train_acc:87.0%, Train_loss:0.362, Test_acc:86.2%, Test_loss:0.458, Lr:1.00E-04
acc = 86.2%, saving model to best.pkl
[2022-11-17 13:53:18] Epoch: 3, Train_acc:94.3%, Train_loss:0.163, Test_acc:84.0%, Test_loss:0.689, Lr:1.00E-04
[2022-11-17 13:53:35] Epoch: 4, Train_acc:95.9%, Train_loss:0.131, Test_acc:85.8%, Test_loss:0.611, Lr:1.00E-04
[2022-11-17 13:53:52] Epoch: 5, Train_acc:93.1%, Train_loss:0.288, Test_acc:82.2%, Test_loss:1.285, Lr:1.00E-04
[2022-11-17 13:54:10] Epoch: 6, Train_acc:96.4%, Train_loss:0.138, Test_acc:89.3%, Test_loss:0.500, Lr:1.00E-04
acc = 89.3%, saving model to best.pkl
[2022-11-17 13:54:32] Epoch: 7, Train_acc:97.6%, Train_loss:0.088, Test_acc:87.6%, Test_loss:0.667, Lr:1.00E-04
[2022-11-17 13:54:50] Epoch: 8, Train_acc:97.8%, Train_loss:0.067, Test_acc:84.4%, Test_loss:0.783, Lr:1.00E-04
[2022-11-17 13:55:07] Epoch: 9, Train_acc:97.4%, Train_loss:0.140, Test_acc:86.7%, Test_loss:0.811, Lr:1.00E-04
[2022-11-17 13:55:25] Epoch:10, Train_acc:96.1%, Train_loss:0.161, Test_acc:88.0%, Test_loss:0.649, Lr:1.00E-04
[2022-11-17 13:55:43] Epoch:11, Train_acc:99.4%, Train_loss:0.019, Test_acc:91.1%, Test_loss:0.502, Lr:1.00E-04
acc = 91.1%, saving model to best.pkl
[2022-11-17 13:56:06] Epoch:12, Train_acc:99.4%, Train_loss:0.032, Test_acc:88.4%, Test_loss:0.849, Lr:1.00E-04
[2022-11-17 13:56:23] Epoch:13, Train_acc:99.7%, Train_loss:0.010, Test_acc:88.4%, Test_loss:0.882, Lr:1.00E-04
[2022-11-17 13:56:41] Epoch:14, Train_acc:99.1%, Train_loss:0.021, Test_acc:86.2%, Test_loss:0.835, Lr:1.00E-04
[2022-11-17 13:57:34] Epoch:15, Train_acc:98.2%, Train_loss:0.068, Test_acc:85.8%, Test_loss:0.920, Lr:1.00E-04
[2022-11-17 13:59:01] Epoch:16, Train_acc:98.8%, Train_loss:0.077, Test_acc:88.0%, Test_loss:1.033, Lr:1.00E-04
[2022-11-17 14:00:28] Epoch:17, Train_acc:97.6%, Train_loss:0.080, Test_acc:85.3%, Test_loss:1.399, Lr:1.00E-04
[2022-11-17 14:01:54] Epoch:18, Train_acc:97.0%, Train_loss:0.138, Test_acc:87.6%, Test_loss:1.180, Lr:1.00E-04
[2022-11-17 14:03:21] Epoch:19, Train_acc:98.4%, Train_loss:0.071, Test_acc:84.9%, Test_loss:1.231, Lr:1.00E-04
[2022-11-17 14:04:48] Epoch:20, Train_acc:99.0%, Train_loss:0.032, Test_acc:85.3%, Test_loss:1.060, Lr:1.00E-04
[2022-11-17 14:06:16] Epoch:21, Train_acc:99.2%, Train_loss:0.015, Test_acc:86.2%, Test_loss:1.007, Lr:1.00E-04
[2022-11-17 14:07:44] Epoch:22, Train_acc:98.6%, Train_loss:0.076, Test_acc:90.7%, Test_loss:0.805, Lr:1.00E-04
[2022-11-17 14:09:11] Epoch:23, Train_acc:99.9%, Train_loss:0.004, Test_acc:92.4%, Test_loss:0.821, Lr:1.00E-04
acc = 92.4%, saving model to best.pkl
[2022-11-17 14:10:42] Epoch:24, Train_acc:98.9%, Train_loss:0.063, Test_acc:88.9%, Test_loss:0.730, Lr:1.00E-04
[2022-11-17 14:12:09] Epoch:25, Train_acc:99.9%, Train_loss:0.005, Test_acc:90.2%, Test_loss:0.767, Lr:1.00E-04
[2022-11-17 14:13:37] Epoch:26, Train_acc:99.3%, Train_loss:0.022, Test_acc:88.0%, Test_loss:2.544, Lr:1.00E-04
[2022-11-17 14:15:04] Epoch:27, Train_acc:98.8%, Train_loss:0.067, Test_acc:90.2%, Test_loss:1.048, Lr:1.00E-04
[2022-11-17 14:16:32] Epoch:28, Train_acc:98.4%, Train_loss:0.111, Test_acc:86.2%, Test_loss:1.503, Lr:1.00E-04
[2022-11-17 14:17:59] Epoch:29, Train_acc:99.1%, Train_loss:0.056, Test_acc:82.7%, Test_loss:1.568, Lr:1.00E-04
[2022-11-17 14:19:25] Epoch:30, Train_acc:99.8%, Train_loss:0.015, Test_acc:84.0%, Test_loss:1.521, Lr:1.00E-04
[2022-11-17 14:20:51] Epoch:31, Train_acc:99.8%, Train_loss:0.010, Test_acc:88.0%, Test_loss:1.070, Lr:1.00E-04
[2022-11-17 14:22:18] Epoch:32, Train_acc:99.7%, Train_loss:0.024, Test_acc:87.6%, Test_loss:1.060, Lr:1.00E-04
[2022-11-17 14:23:44] Epoch:33, Train_acc:99.9%, Train_loss:0.010, Test_acc:88.0%, Test_loss:1.107, Lr:1.00E-04
[2022-11-17 14:25:10] Epoch:34, Train_acc:99.8%, Train_loss:0.006, Test_acc:89.3%, Test_loss:0.817, Lr:1.00E-04
[2022-11-17 14:26:37] Epoch:35, Train_acc:99.9%, Train_loss:0.002, Test_acc:90.2%, Test_loss:0.808, Lr:1.00E-04
[2022-11-17 14:28:03] Epoch:36, Train_acc:99.7%, Train_loss:0.051, Test_acc:88.9%, Test_loss:0.843, Lr:1.00E-04
[2022-11-17 14:29:30] Epoch:37, Train_acc:97.4%, Train_loss:0.132, Test_acc:83.6%, Test_loss:2.068, Lr:1.00E-04
[2022-11-17 14:30:56] Epoch:38, Train_acc:97.8%, Train_loss:0.129, Test_acc:89.3%, Test_loss:1.257, Lr:1.00E-04
[2022-11-17 14:32:23] Epoch:39, Train_acc:99.2%, Train_loss:0.049, Test_acc:84.9%, Test_loss:1.713, Lr:1.00E-04
[2022-11-17 14:33:49] Epoch:40, Train_acc:98.8%, Train_loss:0.085, Test_acc:84.9%, Test_loss:2.200, Lr:1.00E-04
[2022-11-17 14:35:16] Epoch:41, Train_acc:99.6%, Train_loss:0.022, Test_acc:91.6%, Test_loss:1.183, Lr:1.00E-04
[2022-11-17 14:36:42] Epoch:42, Train_acc:99.7%, Train_loss:0.016, Test_acc:92.0%, Test_loss:1.148, Lr:1.00E-04
[2022-11-17 14:38:08] Epoch:43, Train_acc:100.0%, Train_loss:0.001, Test_acc:91.1%, Test_loss:1.151, Lr:1.00E-04
[2022-11-17 14:39:35] Epoch:44, Train_acc:99.9%, Train_loss:0.013, Test_acc:90.7%, Test_loss:1.089, Lr:1.00E-04
[2022-11-17 14:41:01] Epoch:45, Train_acc:99.7%, Train_loss:0.008, Test_acc:90.2%, Test_loss:1.465, Lr:1.00E-04
[2022-11-17 14:42:27] Epoch:46, Train_acc:99.7%, Train_loss:0.007, Test_acc:90.7%, Test_loss:1.260, Lr:1.00E-04
[2022-11-17 14:43:54] Epoch:47, Train_acc:99.6%, Train_loss:0.059, Test_acc:89.3%, Test_loss:1.411, Lr:1.00E-04
[2022-11-17 14:45:22] Epoch:48, Train_acc:99.6%, Train_loss:0.008, Test_acc:87.6%, Test_loss:1.830, Lr:1.00E-04
[2022-11-17 14:46:49] Epoch:49, Train_acc:99.7%, Train_loss:0.042, Test_acc:91.1%, Test_loss:1.541, Lr:1.00E-04
[2022-11-17 14:48:15] Epoch:50, Train_acc:99.6%, Train_loss:0.015, Test_acc:82.2%, Test_loss:1.839, Lr:1.00E-04
Done

最终结果,在第23轮时(Epoch:23的结果)的训练集准确率达到99.9%,测试集准确率达到92.4%


五、结果可视化&模型评估

1.训练结果可视化

import matplotlib.pyplot as plt
import warnings


''' 结果可视化 '''
def displayResult(train_acc, test_acc, train_loss, test_loss, start_epoch, epochs, output=''):
    # 隐藏警告
    warnings.filterwarnings("ignore")                # 忽略警告信息
    plt.rcParams['font.sans-serif']    = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False       # 用来正常显示负号
    plt.rcParams['figure.dpi']         = 100         # 分辨率
    
    epochs_range = range(start_epoch, epochs)
    
    plt.figure('Result Visualization', 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.savefig(os.path.join(output, 'AccuracyLoss.png'))
    plt.show()


''' 绘制准确率&损失率曲线图 '''
displayResult(train_acc, test_acc, train_loss, test_loss, start_epoch, epochs, output)

365天深度学习训练营-第P8周:YOLOv5-C3模块实现_第2张图片


2.模型评估

best_model.eval()
epoch_test_acc, epoch_test_loss = test(test_dl, best_model, loss_fn)
print("EVAL {:.3f}, {:.3f}".format(epoch_test_acc, epoch_test_loss))
EVAL 0.924, 0.821

你可能感兴趣的:(365天深度学习训练记录,深度学习,python,pytorch)