YOLOv5-7.0改进(一)MobileNetv3替换主干网络

本文介绍如何将YOLOv5的主干网络替换为MobileNetV3,实现模型轻量化,平衡速度与精度。包括使用MobileNetV3_Small和MobileNetV3_Large两种配置,以及改进后的训练步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

本篇博客主要讲解YOLOv5主干网络的替换,使用MobileNetv3实现模型轻量化,平衡速度和精度。以下为改进的具体流程~

目录

一、改进MobileNetV3_Small

第一步:修改common.py,新增MobileNetV3

第二步:在yolo.py的parse_model函数中添加类名

第三步:制作模型配置文件

第四步:验证新加入的主干网络

二、改进MobileNetV3_Large

第一步:制作模型配置文件

第二步:验证新加入的主干网络

三、改进训练

第一步:修改train.py中的cfg参数

第二步:运行python train.py


一、改进MobileNetV3_Small

第一步:修改common.py,新增MobileNetV3

将以下代码复制到common.py末尾

# Mobilenetv3Small
 
class h_sigmoid(nn.Module):
    def __init__(self, inplace=True):
        super(h_sigmoid, self).__init__()
        self.relu = nn.ReLU6(inplace=inplace)
 
    def forward(self, x):
        return self.relu(x + 3) / 6
 
 
class h_swish(nn.Module):
    def __init__(self, inplace=True):
        super(h_swish, self).__init__()
        self.sigmoid = h_sigmoid(inplace=inplace)
 
    def forward(self, x):
        return x * self.sigmoid(x)
 
 
class SELayer(nn.Module):
    def __init__(self, channel, reduction=4):
        super(SELayer, self).__init__()
        # Squeeze操作
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        # Excitation操作(FC+ReLU+FC+Sigmoid)
        self.fc = nn.Sequential(
            nn.Linear(channel, channel // reduction),
            nn.ReLU(inplace=True),
            nn.Linear(channel // reduction, channel),
            h_sigmoid()
        )
 
    def forward(self, x):
        b, c, _, _ = x.size()
        y = self.avg_pool(x)
        y = y.view(b, c)
        y = self.fc(y).view(b, c, 1, 1)  # 学习到的每一channel的权重
        return x * y
 
 
class conv_bn_hswish(nn.Module):
    """
    This equals to
    def conv_3x3_bn(inp, oup, stride):
        return nn.Sequential(
            nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
            nn.BatchNorm2d(oup),
            h_swish()
        )
    """
 
    def __init__(self, c1, c2, stride):
        super(conv_bn_hswish, self).__init__()
        self.conv = nn.Conv2d(c1, c2, 3, stride, 1, bias=False)
        self.bn = nn.BatchNorm2d(c2)
        self.act = h_swish()
 
    def forward(self, x):
        return self.act(self.bn(self.conv(x)))
 
    def fuseforward(self, x):
        return self.act(self.conv(x))
 
 
class MobileNetV3(nn.Module):
    def __init__(self, inp, oup, hidden_dim, kernel_size, stride, use_se, use_hs):
        super(MobileNetV3, self).__init__()
        assert stride in [1, 2]
 
        self.identity = stride == 1 and inp == oup
 
        # 输入通道数=扩张通道数 则不进行通道扩张
        if inp == hidden_dim:
            self.conv = nn.Sequential(
                # dw
                nn.Conv2d(hidden_dim, hidden_dim, kernel_size, stride, (kernel_size - 1) // 2, groups=hidden_dim,
                          bias=False),
                nn.BatchNorm2d(hidden_dim),
                h_swish() if use_hs else nn.ReLU(inplace=True),
                # Squeeze-and-Excite
                SELayer(hidden_dim) if use_se else nn.Sequential(),
                # pw-linear
                nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
                nn.BatchNorm2d(oup),
            )
        else:
            # 否则 先进行通道扩张
            self.conv = nn.Sequential(
                # pw
                nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False),
                nn.BatchNorm2d(hidden_dim),
                h_swish() if use_hs else nn.ReLU(inplace=True),
                # dw
                nn.Conv2d(hidden_dim, hidden_dim, kernel_size, stride, (kernel_size - 1) // 2, groups=hidden_dim,
                          bias=False),
                nn.BatchNorm2d(hidden_dim),
                # Squeeze-and-Excite
                SELayer(hidden_dim) if use_se else nn.Sequential(),
                h_swish() if use_hs else nn.ReLU(inplace=True),
                # pw-linear
                nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
                nn.BatchNorm2d(oup),
            )
 
    def forward(self, x):
        y = self.conv(x)
        if self.identity:
            return x + y
        else:
            return y

第二步:在yolo.py的parse_model函数中添加类名

(1)在YOLOv5/v7项目文件下的models/yolo.py中在文件首部添加代码

from models.common import *

(2)添加内容:

h_sigmoid, h_swish, SELayer, conv_bn_hswish, MobileNetV3

(3)添加效果:

第三步:制作模型配置文件

1、复制models/yolov5s.yaml文件,并重命名

2、根据MobileNetv3的网络结构修改配置文件

根据网络结构我们可以看出MobileNetV3模块包含六个参数[out_ch, hidden_ch, kernel_size, stride, use_se, use_hs]:
• out_ch: 输出通道
• hidden_ch: 表示在Inverted residuals中的扩张通道数
• kernel_size: 卷积核大小
• stride: 步长
• use_se: 表示是否使用 SELayer,使用了是1,不使用是0
• use_hs: 表示使用 h_swish 还是 ReLU,使用h_swish是1,使用 ReLU是0

修改的时候,需要注意/8,/16,/32等位置特征图的变换

3、修改head部分concat的层数

修改完成代码如下:

# YOLOv5 🚀 by Ultralytics, GPL-3.0 license

# Parameters
nc: 12  # number of classes
depth_multiple: 0.33  # model depth multiple
width_multiple: 0.50  # layer channel multiple
anchors:
  - [10,13, 16,30, 33,23]  # P3/8
  - [30,61, 62,45, 59,119]  # P4/16
  - [116,90, 156,198, 373,326]  # P5/32

# Mobilenetv3-small backbone
# MobileNetV3_InvertedResidual [out_ch, hid_ch, k_s, stride, SE, HardSwish]
backbone:
  # [from, number, module, args]
  [[-1, 1, conv_bn_hswish, [16, 2]],             # 0-p1/2   320*320
   [-1, 1, MobileNetV3, [16,  16, 3, 2, 1, 0]],  # 1-p2/4   160*160
   [-1, 1, MobileNetV3, [24,  72, 3, 2, 0, 0]],  # 2-p3/8   80*80
   [-1, 1, MobileNetV3, [24,  88, 3, 1, 0, 0]],  # 3        80*80
   [-1, 1, MobileNetV3, [40,  96, 5, 2, 1, 1]],  # 4-p4/16  40*40
   [-1, 1, MobileNetV3, [40, 240, 5, 1, 1, 1]],  # 5        40*40
   [-1, 1, MobileNetV3, [40, 240, 5, 1, 1, 1]],  # 6        40*40
   [-1, 1, MobileNetV3, [48, 120, 5, 1, 1, 1]],  # 7        40*40
   [-1, 1, MobileNetV3, [48, 144, 5, 1, 1, 1]],  # 8        40*40
   [-1, 1, MobileNetV3, [96, 288, 5, 2, 1, 1]],  # 9-p5/32  20*20
   [-1, 1, MobileNetV3, [96, 576, 5, 1, 1, 1]],  # 10       20*20
   [-1, 1, MobileNetV3, [96, 576, 5, 1, 1, 1]],  # 11       20*20
  ]

# YOLOv5 v6.0 head
head:
  [[-1, 1, Conv, [512, 1, 1]],
   [-1, 1, nn.Upsample, [None, 2, 'nearest']],
   [[-1, 8], 1, Concat, [1]],  # cat backbone P4
   [-1, 3, C3, [512, False]],  # 13

   [-1, 1, Conv, [256, 1, 1]],
   [-1, 1, nn.Upsample, [None, 2, 'nearest']],
   [[-1, 3], 1, Concat, [1]],  # cat backbone P3
   [-1, 3, C3, [256, False]],  # 17 (P3/8-small)

   [-1, 1, Conv, [256, 3, 2]],
   [[-1, 16], 1, Concat, [1]],  # cat head P4
   [-1, 3, C3, [512, False]],  # 20 (P4/16-medium)

   [-1, 1, Conv, [512, 3, 2]],
   [[-1, 12], 1, Concat, [1]],  # cat head P5
   [-1, 3, C3, [1024, False]],  # 23 (P5/32-large)

   [[19, 22, 25], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)
  ]

第四步:验证新加入的主干网络

1、修改yolo.py中以下两个地方

(1)DetectionModel函数下的cfg

(2)parser = argparse.ArgumentParser()下的sfg

2、运行yolo.py

(1)yolov5s_MobileNetV3_Small.yaml

(2)yolov5s.yaml

实验结果对比:可以看到替换主干网络为MobileNetV3_Small之后层数变多,可以学习到更多的特征,参数量从723万减少到338万,GFLOPs由16.6变为6.1

二、改进MobileNetV3_Large

MobileNetV3_Small和MobileNetV3_Large区别在于yaml文件中head中concat连接不同,深度因子和宽度因子不同。前两步参考以上内容

第一步:制作模型配置文件

1、复制models/yolov5s.yaml文件,并重命名

2、根据MobileNetv3的网络结构修改配置文件

3、修改head部分concat的层数

修改完成代码如下:

# YOLOv5 🚀 by Ultralytics, GPL-3.0 license

# Parameters
nc: 12  # number of classes
depth_multiple: 0.33  # model depth multiple
width_multiple: 0.50  # layer channel multiple
anchors:
  - [10,13, 16,30, 33,23]  # P3/8
  - [30,61, 62,45, 59,119]  # P4/16
  - [116,90, 156,198, 373,326]  # P5/32

# MobileNetV3_Large
backbone:
  [[-1, 1, conv_bn_hswish, [16, 2]],                  # 0-p1/2
   [-1, 1, MobileNetV3, [ 16,  16, 3, 1, 0, 0]],  # 1-p1/2
   [-1, 1, MobileNetV3, [ 24,  64, 3, 2, 0, 0]],  # 2-p2/4
   [-1, 1, MobileNetV3, [ 24,  72, 3, 1, 0, 0]],  # 3-p2/4
   [-1, 1, MobileNetV3, [ 40,  72, 5, 2, 1, 0]],  # 4-p3/8
   [-1, 1, MobileNetV3, [ 40, 120, 5, 1, 1, 0]],  # 5-p3/8
   [-1, 1, MobileNetV3, [ 40, 120, 5, 1, 1, 0]],  # 6-p3/8
   [-1, 1, MobileNetV3, [ 80, 240, 3, 2, 0, 1]],  # 7-p4/16
   [-1, 1, MobileNetV3, [ 80, 200, 3, 1, 0, 1]],  # 8-p4/16
   [-1, 1, MobileNetV3, [ 80, 184, 3, 1, 0, 1]],  # 9-p4/16
   [-1, 1, MobileNetV3, [ 80, 184, 3, 1, 0, 1]],  # 10-p4/16
   [-1, 1, MobileNetV3, [112, 480, 3, 1, 1, 1]],  # 11-p4/16
   [-1, 1, MobileNetV3, [112, 672, 3, 1, 1, 1]],  # 12-p4/16
   [-1, 1, MobileNetV3, [160, 672, 5, 1, 1, 1]],  # 13-p4/16
   [-1, 1, MobileNetV3, [160, 960, 5, 2, 1, 1]],  # 14-p5/32   
   [-1, 1, MobileNetV3, [160, 960, 5, 1, 1, 1]],  # 15-p5/32
  ]

# YOLOv5 v6.0 head
head:
  [[-1, 1, Conv, [512, 1, 1]],
   [-1, 1, nn.Upsample, [None, 2, 'nearest']],
   [[-1, 13], 1, Concat, [1]],  # cat backbone P4
   [-1, 3, C3, [512, False]],  # 13

   [-1, 1, Conv, [256, 1, 1]],
   [-1, 1, nn.Upsample, [None, 2, 'nearest']],
   [[-1, 6], 1, Concat, [1]],  # cat backbone P3
   [-1, 3, C3, [256, False]],  # 17 (P3/8-small)

   [-1, 1, Conv, [256, 3, 2]],
   [[-1, 20], 1, Concat, [1]],  # cat head P4
   [-1, 3, C3, [512, False]],  # 20 (P4/16-medium)

   [-1, 1, Conv, [512, 3, 2]],
   [[-1, 16], 1, Concat, [1]],  # cat head P5
   [-1, 3, C3, [1024, False]],  # 23 (P5/32-large)

   [[23, 26, 29], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)
  ]

第二步:验证新加入的主干网络

1、运行yolo.py

(1)yolov5s_MobileNetV3_Large.yaml

可以看到MobileNetV3-large模型比MobileNetV3-small多了更多的MobileNet_Block结构,残差倒置结构中通道数维度也增大了许多,速度比YOLOv5s慢将近一半,但是参数变少,效果介乎MobileNetV3-small和YOLOv5s之间。

三、改进训练

第一步:修改train.py中的cfg参数

将模型配置文件修改为yolov5s_MobileNetV3_Small.yaml

第二步:运行python train.py

开始训练:

训练结束后结果保存到run/train文件夹下~

好了,到这里关于YOLOv5和MobileNetV3结合的改进就完成了!

### 替换YOLOv8主干网络MobileNetV3 为了在YOLOv8中使用MobileNetV3作为主干网络,需执行几个关键操作。首先,理解YOLO系列模型架构及其配置文件至关重要;其次,掌握MobileNetV3的特点对于移植工作同样重要。 #### 修改配置文件 通常情况下,YOLOv8的配置由Python脚本定义,在此过程中需要调整`model.py`或其他相关模块内的类定义,以适应新的骨干网结构。具体来说: - **导入必要的库**:确保已安装并可以访问PyTorch以及torchvision等依赖项。 - **加载预训练权重**:如果计划利用迁移学习,则应考虑下载官方发布的MobileNetV3预训练模型,并将其集成到项目中。 ```python import torch from torchvision.models import mobilenet_v3_large, MobileNet_V3_Large_Weights pretrained_model = mobilenet_v3_large(weights=MobileNet_V3_Large_Weights.IMAGENET1K_V2) ``` - **定制化修改**:根据需求裁剪或扩展原生MobileNetV3的最后层,使其输出维度匹配YOLO所需的特征图大小。 ```python class CustomMobileNetV3(torch.nn.Module): def __init__(self, num_classes=1000): super(CustomMobileNetV3, self).__init__() base_model = pretrained_model.features # 去掉最后几层,保留倒数第二层之前的结构 last_channel = list(base_model)[-2].out_channels self.backbone = torch.nn.Sequential(*list(pretrained_model.children())[:-1]) # 添加自定义头部 self.head = torch.nn.Conv2d(last_channel, out_channels=num_classes, kernel_size=(1, 1)) def forward(self, x): x = self.backbone(x) x = self.head(x) return x ``` #### 集成至YOLO框架 完成上述准备工作之后,下步就是将这个经过改造后的MobileNetV3融入YOLO体系内。这步骤涉及对原有YOLO代码逻辑做出适当改动,比如更改输入张量处理方式、调整损失函数计算方法等。 考虑到不同版本之间可能存在差异,建议仔细阅读官方文档和源码注释,以便更精准地实施这些变更[^2]。 #### 训练与评估 旦成功替换主干网络,就可以按照常规流程准备数据集、设置超参数并启动训练过程。值得注意的是,由于更换了基础架构,可能需要重新调优些超参(如学习率),以获得最佳效果。 ---
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值