YOLO-v8:对yolov8网络的改进教程(以GAM注意力模块为例)

本文将介绍如何在YOLOv8网络中进行模块化修改。

通过将改进的核心模块添加到项目中,即可直接运行各种 YOLOv8-xxx.yaml 网络配置文件,支持乐高式创新扩展。无论是进行网络结构的调整还是增加新的功能模块,用户只需一键运行,轻松实现YOLOv8的改进与优化。

本文以添加 (Global Attention Mechanism,GAM) 注意力机制(参考文献:https://paperswithcode.com/paper/global-attention-mechanism-retain-information)模块为例进行演示。

只需要无脑跟着本教程复现一遍,即可实现对 yolov8 网络的改进。



注意:

  • 为了不出现环境混乱,我直接在 D:\miniconda\setup\Lib\site-packages\ultralytics 文件下进行代码修改。
  • 像 GAM 注意力机制模块的类似模块的代码可以在网上搜索到,或者查看作者的源码,或者访问一些大牛的github库,他们都整理了。

一、创建 GAM.py 文件

ultralytics\nn\modules\GAM.py 目录下新建一个 GAM.py 文件,如下图所示,

在这里插入图片描述

复制以下代码到 GAM.py 文件,


import numpy as np
import torch
from torch import nn
from torch.nn import init

class GAMAttention(nn.Module):
       #https://paperswithcode.com/paper/global-attention-mechanism-retain-information
    def __init__(self, c1, c2, group=True,rate=4):
        super(GAMAttention, self).__init__()
        
        self.channel_attention = nn.Sequential(
            nn.Linear(c1, int(c1 / rate)),
            nn.ReLU(inplace=True),
            nn.Linear(int(c1 / rate), c1)
        )
        self.spatial_attention = nn.Sequential(
            nn.Conv2d(c1, c1//rate, kernel_size=7, padding=3,groups=rate)if group else nn.Conv2d(c1, int(c1 / rate), kernel_size=7, padding=3), 
            nn.BatchNorm2d(int(c1 /rate)),
            nn.ReLU(inplace=True),
            nn.Conv2d(c1//rate, c2, kernel_size=7, padding=3,groups=rate) if group else nn.Conv2d(int(c1 / rate), c2, kernel_size=7, padding=3), 
            nn.BatchNorm2d(c2)
        )

    def forward(self, x):
        b, c, h, w = x.shape
        x_permute = x.permute(0, 2, 3, 1).view(b, -1, c)
        x_att_permute = self.channel_attention(x_permute).view(b, h, w, c)
        x_channel_att = x_att_permute.permute(0, 3, 1, 2)
        x = x * x_channel_att
 
        x_spatial_att = self.spatial_attention(x).sigmoid()
        x_spatial_att=channel_shuffle(x_spatial_att,4) #last shuffle 
        out = x * x_spatial_att
        return out  

def channel_shuffle(x, groups=2):
        B, C, H, W = x.size()
        out = x.view(B, groups, C // groups, H, W).permute(0, 2, 1, 3, 4).contiguous()
        out=out.view(B, C, H, W) 
        return out

二、修改 __init__.py

__init__.py 文件存在于包的目录中,用来告诉 Python 该目录是一个包。在 __init__.py 中,可以指定包中哪些模块或变量对外部可见。通过设置 __all__ 变量,可以控制从包中导入 * 时哪些模块或函数会被导入。

如下图所示,修改 ultralytics\nn\modules\__init__.py 文件,加入以下两行代码,__all__ 里面添加 "GAMAttention",,以使 GAMAttention 可以被 task.py 引入。

from .GAM import GAMAttention

__all__ = (
    "GAMAttention",
)

在这里插入图片描述

三、引入 GAMAttention 到 tasks.py

ultralytics\nn\tasks.py 文件中,将 GAMAttention 引入,如下图所示,

加入代码

from ultralytics.nn.modules import (
    GAMAttention,
)

在这里插入图片描述

然后在 ultralytics\nn\tasks.py 文件的 parse_model 函数中,加入以下代码:

        elif m in {GAMAttention}:
            c1, c2 = ch[f], args[0]
            if c2 != nc:  # if c2 not equal to number of classes (i.e. for Classify() output)
                c2 = make_divisible(min(c2, max_channels) * width, 8)
            args = [c1, c2, *args[1:]]

在这里插入图片描述

四、模型 yolov8-gam 网络配置文件

创建模型网络配置文件 yolov8-gam.yaml 文件。文件位置可以创建在任何地方。如下图所示,

在这里插入图片描述

# Ultralytics YOLO 🚀, AGPL-3.0 license
# YOLOv8 object detection model. More improvement points for YOLOv8, please see https://github.com/iscyy/ultralyticsPro

# Parameters
nc: 80  # number of classes
scales: # model compound scaling constants, i.e. 'model=yolov8n.yaml' will call yolov8.yaml with scale 'n'
  # [depth, width, max_channels]
  n: [0.33, 0.25, 1024]  # YOLOv8n summary: 225 layers,  3157200 parameters,  3157184 gradients,   8.9 GFLOPs
  s: [0.33, 0.50, 1024]  # YOLOv8s summary: 225 layers, 11166560 parameters, 11166544 gradients,  28.8 GFLOPs
  m: [0.67, 0.75, 768]   # YOLOv8m summary: 295 layers, 25902640 parameters, 25902624 gradients,  79.3 GFLOPs
  l: [1.00, 1.00, 512]   # YOLOv8l summary: 365 layers, 43691520 parameters, 43691504 gradients, 165.7 GFLOPs
  x: [1.00, 1.25, 512]   # YOLOv8x summary: 365 layers, 68229648 parameters, 68229632 gradients, 258.5 GFLOPs

# YOLOv8.0n backbone
backbone:
  # [from, repeats, module, args]
  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2
  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4
  - [-1, 3, C2f, [128, True]]
  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8
  - [-1, 6, C2f, [256, True]]
  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16
  - [-1, 6, C2f, [512, True]]
  - [-1, 1, Conv, [1024, 3, 2]]  # 7-P5/32
  - [-1, 3, C2f, [1024, True]]
  - [-1, 3, GAMAttention, [1024]]
  - [-1, 1, SPPF, [1024, 5]]  # 9

# YOLOv8.0n head
head:
  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]
  - [[-1, 6], 1, Concat, [1]]  # cat backbone P4
  - [-1, 3, C2f, [512]]  # 12

  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]
  - [[-1, 4], 1, Concat, [1]]  # cat backbone P3
  - [-1, 3, C2f, [256]]  # 15 (P3/8-small)

  - [-1, 1, Conv, [256, 3, 2]]
  - [[-1, 13], 1, Concat, [1]]  # cat head P4
  - [-1, 3, C2f, [512]]  # 18 (P4/16-medium)

  - [-1, 1, Conv, [512, 3, 2]]
  - [[-1, 10], 1, Concat, [1]]  # cat head P5
  - [-1, 3, C2f, [1024]]  # 21 (P5/32-large)

  - [[16, 19, 22], 1, Detect, [nc]]  # Detect(P3, P4, P5)

五、训练

执行以下代码进行训练,修改模型路径和你的数据集配置文件路径。之后运行即可进行训练。结果会保存在代码同级目录下的 runs/train 文件夹下。

from ultralytics import YOLO
if __name__ == '__main__':
    model = YOLO('path/to/yolov8-gam.yaml')
    model.train(data=r'path/to/your_dataset.yaml', epochs=100, workers=0,)

控制台执行结果如下图所示,可以看到,识别到了新的改进的网络。

在这里插入图片描述

在这里插入图片描述

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_养乐多_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值