YOLOv8改进 - 注意力篇 - 引入SEAttention注意力机制

一、本文介绍

作为入门性篇章,这里介绍了SEAttention注意力在YOLOv8中的使用。包含SEAttention原理分析,SEAttention的代码、SEAttention的使用方法、以及添加以后的yaml文件及运行记录。

二、SEAttention原理分析

SEAttention官方论文地址:SE文章

SEAttention注意力机制(挤压-激励):一种通道注意力,核心思想:

  1. Squeeze:通过全局平均池化(Global Average Pooling)将特征图的空间维度(高和宽)压缩成一个值,从而获得每个通道的全局表示。
  2. Excitation:使用一个包含非线性激活函数的全连接层网络来学习每个通道的重要性权重。
  3. Reweight:将学习到的通道权重应用于原始特征图,强化有用特征并抑制无关特征。

相关代码:

SEAttention注意力的代码,如下:

python 复制代码
class SEAttention(nn.Module):

    def __init__(self, channel=512,reduction=16):
        super().__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.fc = nn.Sequential(
            nn.Linear(channel, channel // reduction, bias=False),
            nn.ReLU(inplace=True),
            nn.Linear(channel // reduction, channel, bias=False),
            nn.Sigmoid()
        )


    def init_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                init.kaiming_normal_(m.weight, mode='fan_out')
                if m.bias is not None:
                    init.constant_(m.bias, 0)
            elif isinstance(m, nn.BatchNorm2d):
                init.constant_(m.weight, 1)
                init.constant_(m.bias, 0)
            elif isinstance(m, nn.Linear):
                init.normal_(m.weight, std=0.001)
                if m.bias is not None:
                    init.constant_(m.bias, 0)

    def forward(self, x):
        b, c, _, _ = x.size()
        y = self.avg_pool(x).view(b, c)
        y = self.fc(y).view(b, c, 1, 1)
        return x * y.expand_as(x)

四、YOLOv8中SEAttention使用方法

1.YOLOv8中添加SEAttention模块:

首先在ultralytics/nn/modules/conv.py最后添加SEAttention模块的代码。

2.在conv.py的开头__all__ = 内添加SEAttention模块的类别名:

3.在同级文件夹下的__init__.py内添加SEAttention的相关内容:(分别是from .conv import SEAttention ;以及在__all__内添加SEAttention)

4.在ultralytics/nn/tasks.py进行LSKA注意力机制的注册,以及在YOLOv8的yaml配置文件中添加SEAttention即可。

首先打开task.py文件,按住Ctrl+F,输入parse_model进行搜索。找到parse_model函数。在其最后一个else前面添加以下注册代码:

python 复制代码
 elif m in {CBAM,SEAttention}:#自己加的注意力模块
            c1, c2 = ch[f], args[0]
            if c2 != nc:
                c2 = make_divisible(min(c2, max_channels) * width, 8)
            args = [c1, *args[1:]]

然后,就是新建一个名为YOLOv8_SEAttention.yaml的配置文件:(路径:ultralytics/cfg/models/v8/YOLOv8_SEAttention.yaml)其中参数中nc,由自己的数据集决定。本文测试,采用的coco8数据集,有80个类别。

python 复制代码
# Ultralytics YOLO 🚀, AGPL-3.0 license
# YOLOv8 object detection model with P3-P5 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect

# Parameters
nc: 80  # number of classes
scales: # model compound scaling constants, i.e. 'model=yolov8n.yaml' will call CPAM-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, 1, SEAttention, [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)

在根目录新建一个train.py文件,内容如下

python 复制代码
from ultralytics import YOLO

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
# 加载一个模型
    model = YOLO('ultralytics/cfg/models/v8/YOLOv8_SE.yaml')  # 从YAML建立一个新模型
# 训练模型
    results = model.train(data='ultralytics/cfg/datasets/coco8.yaml', epochs=1,imgsz=640,optimizer="SGD")

训练输出:​

​​

五、总结

以上就是SEAttention的原理及使用方式,但具体SEAttention注意力机制的具体位置放哪里,效果更好。需要根据不同的数据集做相应的实验验证。希望本文能够帮助你入门YOLO中注意力机制的使用。

相关推荐
天远Date Lab4 小时前
零信任架构实战:基于天远行驶OCR证识别构建自动化高并发物流车队准入网关
人工智能·架构·自动化·ocr
厚皮龙4 小时前
CoT Monitoring 与 Activation Monitoring 总结
人工智能
QYR-分析4 小时前
高端精密制造赋能,管材旋锻机行业市场格局、痛点趋势与发展研判
人工智能·制造
Hody914 小时前
【XR硬件介绍】苹果N50智能眼镜技术解读:Vision Pro让位之后,“无屏AI眼镜”凭什么接棒
人工智能·xr
kaixin_啊啊4 小时前
PandaWiki 本地 AI 知识库实战:文档导入、智能问答与远程访问
linux·服务器·人工智能·windows·ai
海宇数据4 小时前
零信任架构实战:基于海宇运营商近3个月平均账单构建自动化分布式租赁网关
人工智能·分布式·架构·自动化
2601_967935564 小时前
PCB制造检测机器视觉系统哪个牌子好?五大品牌能力解析
人工智能·microsoft
Elastic 中国社区官方博客5 小时前
Elasticsearch:ES|QL 搜索教程
大数据·数据库·人工智能·sql·elasticsearch·搜索引擎·全文检索
程序员于老七5 小时前
漫话大模型:训练效率翻倍的秘密——Muon 优化器凭什么干翻 AdamW
深度学习·大模型·ai编程·优化器·muon
程序员柒叔5 小时前
Dify -- 定时任务系统
人工智能·github·agent·dify·rag