学习资源站

YOLOv11改进-添加注意力篇-利用SENetV1改进网络结构(ILSVRC冠军得主)(附二次创新C2PSASENet)

一、本文介绍

本文给大家带来的改进机制是SENet(Squeeze-and-Excitation Networks)其是一种通过调整卷积网络中的通道关系来提升 性能 的网络结构。SENet并不是一个独立的 网络模型 ,而是一个可以和现有的任何一个模型相结合的模块 ( 可以看作是一种通道型的注意力机制 ) 。在SENet中,所谓的 挤压和激励 (Squeeze-and-Excitation)操作是作为一个单元添加到传统的卷积网络结构中,如残差单元中 ( 后面我会把修改好的残差单元给大家大家直接复制粘贴即可使用 ) 。这样可以增强 模型 对通道间关系的捕获,提升整体的特征表达能力,而不需要从头开始设计一个全新的网络架构。因此,SENet可以看作是对现有网络模型的一种改进和增强 ( 亲测大中小三中目标检测上都有一定程度的涨点效果 ) ,附二次创新C2PSASENet。


二、SENetV1框架原理

论文地址: 官方论文地址

代码地址: 官方代码地址


SENet(Squeeze-and-Excitation Networks)的主要思想 在于通过挤压-激励(SE)块强化了网络对通道间依赖性的建模。这一创新的核心在于自适应地重新校准每个通道的特征响应,显著提升了网络对特征的表示能力。SE块的叠加构成了 SENet架构 ,有效提高了模型在不同数据集上的泛化性。SENet的创新点包括其独特的结构设计,它在增加极少计算成本的情况下,为现有CNN模型带来了显著的性能提升,并在国际 图像识别 竞赛ILSVRC 2017中取得了突破性的成果

上图展示了一个挤压-激励(Squeeze-and-Excitation, SE)块的结构。输入特征图 X 经过一个变换 F_{tr} 后产生特征图 U 。然后,特征图 U 被压缩成一个全局描述子,这是通过全局平均池化 F_{sq} 实现的,产生一个通道描述子。这个描述子经过两个全连接层 F_{ex} ,第一个是 降维 ,第二个是升维,并通过激活函数如ReLU和Sigmoid激活。最后,原始特征图 U 与学习到的通道权重 F_{scale} 相乘,得到重新校准的特征图 hat{X} 。这种结构有助于网络通过学习通道间的依赖性,自适应地强化或抑制某些特征通道。

上面的图片展示了两种 神经网络 模块的结构图:Inception模块和残差(ResNet)模块。每个模块都有其标准形式和一个修改形式,对比图融入了Squeeze-and-Excitation (SE)块来提升性能。

左面的部分是原始Inception模块(左)和SE-Inception模块(右)。SE-Inception模块通过全局平均池化和两个全连接层(第一个使用ReLU激活函数,第二个使用Sigmoid函数)来生成通道级权重,然后对输入特征图进行缩放。

右面的部分展示了原始残差模块(左)和SE-ResNet模块(右)。SE-ResNet模块在传统的残差连接之后添加了SE块,同样使用全局平均池化和全连接层来获得通道级权重,并对残差模块的输出进行缩放。

这两个修改版模块都旨在增强网络对特征的重要性评估能力,从而提升整体模型的性能。


三、SENetV1核心代码

使用方式看章节四。

  1. import torch
  2. import torch.nn as nn
  3. __all__ = ['SELayerV1', 'C2PSA_SENetV1']
  4. class SELayerV1(nn.Module):
  5. def __init__(self, channel, reduction=16):
  6. super(SELayerV1, self).__init__()
  7. self.avg_pool = nn.AdaptiveAvgPool2d(1)
  8. self.fc = nn.Sequential(
  9. nn.Linear(channel, channel // reduction, bias=False),
  10. nn.ReLU(inplace=True),
  11. nn.Linear(channel // reduction, channel, bias=False),
  12. nn.Sigmoid()
  13. )
  14. def forward(self, x):
  15. b, c, _, _ = x.size()
  16. y = self.avg_pool(x).view(b, c)
  17. y = self.fc(y).view(b, c, 1, 1)
  18. return x * y.expand_as(x)
  19. def autopad(k, p=None, d=1): # kernel, padding, dilation
  20. """Pad to 'same' shape outputs."""
  21. if d > 1:
  22. k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size
  23. if p is None:
  24. p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
  25. return p
  26. class Conv(nn.Module):
  27. """Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation)."""
  28. default_act = nn.SiLU() # default activation
  29. def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
  30. """Initialize Conv layer with given arguments including activation."""
  31. super().__init__()
  32. self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
  33. self.bn = nn.BatchNorm2d(c2)
  34. self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
  35. def forward(self, x):
  36. """Apply convolution, batch normalization and activation to input tensor."""
  37. return self.act(self.bn(self.conv(x)))
  38. def forward_fuse(self, x):
  39. """Perform transposed convolution of 2D data."""
  40. return self.act(self.conv(x))
  41. class PSABlock(nn.Module):
  42. """
  43. PSABlock class implementing a Position-Sensitive Attention block for neural networks.
  44. This class encapsulates the functionality for applying multi-head attention and feed-forward neural network layers
  45. with optional shortcut connections.
  46. Attributes:
  47. attn (Attention): Multi-head attention module.
  48. ffn (nn.Sequential): Feed-forward neural network module.
  49. add (bool): Flag indicating whether to add shortcut connections.
  50. Methods:
  51. forward: Performs a forward pass through the PSABlock, applying attention and feed-forward layers.
  52. Examples:
  53. Create a PSABlock and perform a forward pass
  54. >>> psablock = PSABlock(c=128, attn_ratio=0.5, num_heads=4, shortcut=True)
  55. >>> input_tensor = torch.randn(1, 128, 32, 32)
  56. >>> output_tensor = psablock(input_tensor)
  57. """
  58. def __init__(self, c, attn_ratio=0.5, num_heads=4, shortcut=True) -> None:
  59. """Initializes the PSABlock with attention and feed-forward layers for enhanced feature extraction."""
  60. super().__init__()
  61. self.attn = SELayerV1(c)
  62. self.ffn = nn.Sequential(Conv(c, c * 2, 1), Conv(c * 2, c, 1, act=False))
  63. self.add = shortcut
  64. def forward(self, x):
  65. """Executes a forward pass through PSABlock, applying attention and feed-forward layers to the input tensor."""
  66. x = x + self.attn(x) if self.add else self.attn(x)
  67. x = x + self.ffn(x) if self.add else self.ffn(x)
  68. return x
  69. class C2PSA_SENetV1(nn.Module):
  70. """
  71. C2PSA module with attention mechanism for enhanced feature extraction and processing.
  72. This module implements a convolutional block with attention mechanisms to enhance feature extraction and processing
  73. capabilities. It includes a series of PSABlock modules for self-attention and feed-forward operations.
  74. Attributes:
  75. c (int): Number of hidden channels.
  76. cv1 (Conv): 1x1 convolution layer to reduce the number of input channels to 2*c.
  77. cv2 (Conv): 1x1 convolution layer to reduce the number of output channels to c.
  78. m (nn.Sequential): Sequential container of PSABlock modules for attention and feed-forward operations.
  79. Methods:
  80. forward: Performs a forward pass through the C2PSA module, applying attention and feed-forward operations.
  81. Notes:
  82. This module essentially is the same as PSA module, but refactored to allow stacking more PSABlock modules.
  83. Examples:
  84. >>> c2psa = C2PSA(c1=256, c2=256, n=3, e=0.5)
  85. >>> input_tensor = torch.randn(1, 256, 64, 64)
  86. >>> output_tensor = c2psa(input_tensor)
  87. """
  88. def __init__(self, c1, c2, n=1, e=0.5):
  89. """Initializes the C2PSA module with specified input/output channels, number of layers, and expansion ratio."""
  90. super().__init__()
  91. assert c1 == c2
  92. self.c = int(c1 * e)
  93. self.cv1 = Conv(c1, 2 * self.c, 1, 1)
  94. self.cv2 = Conv(2 * self.c, c1, 1)
  95. self.m = nn.Sequential(*(PSABlock(self.c, attn_ratio=0.5, num_heads=self.c // 64) for _ in range(n)))
  96. def forward(self, x):
  97. """Processes the input tensor 'x' through a series of PSA blocks and returns the transformed tensor."""
  98. a, b = self.cv1(x).split((self.c, self.c), dim=1)
  99. b = self.m(b)
  100. return self.cv2(torch.cat((a, b), 1))
  101. if __name__ == "__main__":
  102. # Generating Sample image
  103. image_size = (1, 64, 240, 240)
  104. image = torch.rand(*image_size)
  105. # Model
  106. mobilenet_v1 = C2PSA_SENetV1(64, 64)
  107. out = mobilenet_v1(image)
  108. print(out.size())


四、手把手教你添加SENetV1模块

4.1 修改一

第一还是建立文件,我们找到如下 ultralytics /nn文件夹下建立一个目录名字呢就是'Addmodules'文件夹( 用群内的文件的话已经有了无需新建) !然后在其内部建立一个新的py文件将核心代码复制粘贴进去即可。


4.2 修改二

第二步我们在该目录下创建一个新的py文件名字为'__init__.py'( 用群内的文件的话已经有了无需新建) ,然后在其内部导入我们的检测头如下图所示。


4.3 修改三

第三步我门中到如下文件'ultralytics/nn/tasks.py'进行导入和注册我们的模块( 用群内的文件的话已经有了无需重新导入直接开始第四步即可)

从今天开始以后的教程就都统一成这个样子了,因为我默认大家用了我群内的文件来进行修改!!


4.4 修改四

按照我的添加在parse_model里添加即可,两个图片都是本文的机制大家按照图片进行添加即可!


到此就修改完成了,大家可以复制下面的yaml文件运行。


4.2 SENetV1的yaml文件和训练截图


4.2.1 SENetV1的yaml版本一(推荐)

此版本训练信息:YOLO11-C2PSA-SENetV1 summary: 314 layers, 2,545,435 parameters, 2,545,419 gradients, 6.4 GFLOPs

版本说明:优化C2PSA注意力机制

  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. # YOLO11 object detection model with P3-P5 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect
  3. # Parameters
  4. nc: 80 # number of classes
  5. scales: # model compound scaling constants, i.e. 'model=yolo11n.yaml' will call yolo11.yaml with scale 'n'
  6. # [depth, width, max_channels]
  7. n: [0.50, 0.25, 1024] # summary: 319 layers, 2624080 parameters, 2624064 gradients, 6.6 GFLOPs
  8. s: [0.50, 0.50, 1024] # summary: 319 layers, 9458752 parameters, 9458736 gradients, 21.7 GFLOPs
  9. m: [0.50, 1.00, 512] # summary: 409 layers, 20114688 parameters, 20114672 gradients, 68.5 GFLOPs
  10. l: [1.00, 1.00, 512] # summary: 631 layers, 25372160 parameters, 25372144 gradients, 87.6 GFLOPs
  11. x: [1.00, 1.50, 512] # summary: 631 layers, 56966176 parameters, 56966160 gradients, 196.0 GFLOPs
  12. # YOLO11n backbone
  13. backbone:
  14. # [from, repeats, module, args]
  15. - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2
  16. - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4
  17. - [-1, 2, C3k2, [256, False, 0.25]]
  18. - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8
  19. - [-1, 2, C3k2, [512, False, 0.25]]
  20. - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16
  21. - [-1, 2, C3k2, [512, True]]
  22. - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32
  23. - [-1, 2, C3k2, [1024, True]]
  24. - [-1, 1, SPPF, [1024, 5]] # 9
  25. - [-1, 2, C2PSA_MSDA, [1024]] # 10
  26. # YOLO11n head
  27. head:
  28. - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
  29. - [[-1, 6], 1, Concat, [1]] # cat backbone P4
  30. - [-1, 2, C3k2, [512, False]] # 13
  31. - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
  32. - [[-1, 4], 1, Concat, [1]] # cat backbone P3
  33. - [-1, 2, C3k2, [256, False]] # 16 (P3/8-small)
  34. - [-1, 1, Conv, [256, 3, 2]]
  35. - [[-1, 13], 1, Concat, [1]] # cat head P4
  36. - [-1, 2, C3k2, [512, False]] # 19 (P4/16-medium)
  37. - [-1, 1, Conv, [512, 3, 2]]
  38. - [[-1, 10], 1, Concat, [1]] # cat head P5
  39. - [-1, 2, C3k2, [1024, True]] # 22 (P5/32-large)
  40. - [[16, 19, 22], 1, Detect, [nc]] # Detect(P3, P4, P5)


4.2.2 SENetV1的yaml版本二

添加的版本二具体那种适合你需要大家自己多做实验来尝试。

此版本训练信息:YOLO11-SENetV1 summary: 340 layers, 2,605,467 parameters, 2,605,451 gradients, 6.5 GFLOPs

  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. # YOLO11 object detection model with P3-P5 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect
  3. # Parameters
  4. nc: 80 # number of classes
  5. scales: # model compound scaling constants, i.e. 'model=yolo11n.yaml' will call yolo11.yaml with scale 'n'
  6. # [depth, width, max_channels]
  7. n: [0.50, 0.25, 1024] # summary: 319 layers, 2624080 parameters, 2624064 gradients, 6.6 GFLOPs
  8. s: [0.50, 0.50, 1024] # summary: 319 layers, 9458752 parameters, 9458736 gradients, 21.7 GFLOPs
  9. m: [0.50, 1.00, 512] # summary: 409 layers, 20114688 parameters, 20114672 gradients, 68.5 GFLOPs
  10. l: [1.00, 1.00, 512] # summary: 631 layers, 25372160 parameters, 25372144 gradients, 87.6 GFLOPs
  11. x: [1.00, 1.50, 512] # summary: 631 layers, 56966176 parameters, 56966160 gradients, 196.0 GFLOPs
  12. # YOLO11n backbone
  13. backbone:
  14. # [from, repeats, module, args]
  15. - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2
  16. - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4
  17. - [-1, 2, C3k2, [256, False, 0.25]]
  18. - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8
  19. - [-1, 2, C3k2, [512, False, 0.25]]
  20. - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16
  21. - [-1, 2, C3k2, [512, True]]
  22. - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32
  23. - [-1, 2, C3k2, [1024, True]]
  24. - [-1, 1, SPPF, [1024, 5]] # 9
  25. - [-1, 2, C2PSA, [1024]] # 10
  26. # YOLO11n head
  27. head:
  28. - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
  29. - [[-1, 6], 1, Concat, [1]] # cat backbone P4
  30. - [-1, 2, C3k2, [512, False]] # 13
  31. - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
  32. - [[-1, 4], 1, Concat, [1]] # cat backbone P3
  33. - [-1, 2, C3k2, [256, False]] # 16 (P3/8-small)
  34. - [-1, 1, SELayerV1, []] # 17 (P3/8-small) 小目标检测层输出位置增加注意力机制
  35. - [-1, 1, Conv, [256, 3, 2]]
  36. - [[-1, 13], 1, Concat, [1]] # cat head P4
  37. - [-1, 2, C3k2, [512, False]] # 20 (P4/16-medium)
  38. - [-1, 1, SELayerV1, []] # 21 (P4/16-medium) 中目标检测层输出位置增加注意力机制
  39. - [-1, 1, Conv, [512, 3, 2]]
  40. - [[-1, 10], 1, Concat, [1]] # cat head P5
  41. - [-1, 2, C3k2, [1024, True]] # 24 (P5/32-large)
  42. - [-1, 1, SELayerV1, []] # 25 (P5/32-large) 大目标检测层输出位置增加注意力机制
  43. # 具体在那一层用注意力机制可以根据自己的数据集场景进行选择。
  44. # 如果你自己配置注意力位置注意from[17, 21, 25]位置要对应上对应的检测层!
  45. - [[17, 21, 25], 1, Detect, [nc]] # Detect(P3, P4, P5)

4.4 SENetV1的训练过程截图


4.5 训练代码

  1. import warnings
  2. warnings.filterwarnings('ignore')
  3. from ultralytics import YOLO
  4. if __name__ == '__main__':
  5. model = YOLO('模型yaml文件地址')
  6. # 如何切换模型版本, 上面的ymal文件可以改为 yolov8s.yaml就是使用的v8s,
  7. # 类似某个改进的yaml文件名称为yolov8-XXX.yaml那么如果想使用其它版本就把上面的名称改为yolov8l-XXX.yaml即可(改的是上面YOLO中间的名字不是配置文件的)!
  8. # model.load('yolov8n.pt') # 是否加载预训练权重,科研不建议大家加载否则很难提升精度
  9. model.train(data=r"填写你数据集yaml文件地址",
  10. # 如果大家任务是其它的'ultralytics/cfg/default.yaml'找到这里修改task可以改成detect, segment, classify, pose
  11. cache=False,
  12. imgsz=640,
  13. epochs=150,
  14. single_cls=False, # 是否是单类别检测
  15. batch=4,
  16. close_mosaic=0,
  17. workers=0,
  18. device='0',
  19. optimizer='SGD', # using SGD
  20. # resume=True, # 这里是填写True
  21. amp=False, # 如果出现训练损失为Nan可以关闭amp
  22. project='runs/train',
  23. name='exp',
  24. )


五、本文总结

到此本文的正式分享内容就结束了,在这里给大家推荐我的YOLOv11改进有效涨点专栏,本专栏目前为新开的平均质量分98分,后期我会根据各种最新的前沿顶会进行论文复现,也会对一些老的改进机制进行补充, 目前本专栏免费阅读(暂时,大家尽早关注不迷路~) ,如果大家觉得本文帮助到你了,订阅本专栏,关注后续更多的更新~

​​