学习资源站

YOLOv11改进-添加注意力机制篇-2024最新适用于遥感目标检测的注意力机制CAA二次创新C2PSA机制(全网独家首发)

一、本文介绍

本文给大家带来的最新改进机制是 PKINet 网络提出的 CAA 注意力机制 , 其首先通过平均池化和一个 1x1 卷积获取局部区域的特征。接着应用两个深度分离的条状卷积,一个是水平方向,另一个是垂直方向。这种条状卷积可以模拟大核卷积,但计算成本低,轻量化。这种配置在捕捉桥梁等拉长的物体结构上特别有效。 本文将其用于二次创新PSA和另外一种使用方式,本文内容为个人整理, 文章内含有代码 + 添加教程 + 使用方式。

欢迎大家订阅我的专栏一起学习YOLO!



二、原理介绍

官方论文地址: 官方论文地址点击此处即可跳转

官方代码地址: 官方代码地址点击此处即可跳转


CAA(Context Anchor Attention)注意力模块的主要内容很少其实,他是集成在PKINet网络中的:

1. 功能:CAA 集成在 PKI 模块中,旨在通过关注远距离像素间的上下文依赖关系,补充多尺度的局部特征,增强中央区域的特征。

2. 机制:

  • 首先通过平均池化和一个 1x1 卷积获取局部区域的特征。
  • 接着应用两个深度分离的条状卷积,一个是水平方向,另一个是垂直方向。这种条状卷积可以模拟大核卷积,但计算成本低,轻量化。
  • 这种配置在捕捉桥梁等拉长的物体结构上特别有效。

3. 感受野扩展:条状卷积的 卷积核大小 随着模块深度增加而增大,使得 PKINet 能够更有效地建立远距离像素之间的关系,同时不显著增加计算量。

4. 注意力机制:CAA 模块通过对条状卷积输出应用 Sigmoid 函数 生成注意力图,并利用该注意力图对特征图进行缩放,增强相关特征,从而赋予 PKINet 强大的上下文信息处理能力,适应各种物体尺度。

CAA 与 PKI 模块结合,使得 PKINet 能够同时捕捉局部和全局上下文信息,这对遥感目标检测任务尤为关键。


三、核心代码

核心代码的使用方式看章节四!

  1. import torch
  2. import torch.nn as nn
  3. from typing import Optional
  4. __all__ = ['CAA', 'C2PSA_CAA']
  5. class ConvModule(nn.Module):
  6. # 代码重构 CSDN Snu77
  7. def __init__(
  8. self,
  9. in_channels: int, # Number of input channels
  10. out_channels: int, # Number of output channels
  11. kernel_size: int, # Kernel size for convolution
  12. stride: int = 1, # Stride
  13. padding: int = 0, # Padding
  14. groups: int = 1, # Number of groups for grouped convolution
  15. norm_cfg: Optional[dict] = None, # Normalization configuration
  16. act_cfg: Optional[dict] = None): # Activation function configuration
  17. super().__init__()
  18. layers = []
  19. # Convolution layer
  20. layers.append(nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, groups=groups, bias=(norm_cfg is None)))
  21. # Normalization layer
  22. if norm_cfg:
  23. norm_layer = self._get_norm_layer(out_channels, norm_cfg)
  24. layers.append(norm_layer)
  25. # Activation layer
  26. if act_cfg:
  27. act_layer = self._get_act_layer(act_cfg)
  28. layers.append(act_layer)
  29. # Combine all layers into a sequential layer
  30. self.block = nn.Sequential(*layers)
  31. def forward(self, x):
  32. return self.block(x)
  33. # Helper function to retrieve the normalization layer
  34. def _get_norm_layer(self, num_features, norm_cfg):
  35. if norm_cfg['type'] == 'BN':
  36. return nn.BatchNorm2d(num_features, momentum=norm_cfg.get('momentum', 0.1), eps=norm_cfg.get('eps', 1e-5))
  37. # Add other normalization types here if needed
  38. raise NotImplementedError(f"Normalization layer '{norm_cfg['type']}' is not implemented.")
  39. # Helper function to retrieve the activation layer
  40. def _get_act_layer(self, act_cfg):
  41. if act_cfg['type'] == 'ReLU':
  42. return nn.ReLU(inplace=True)
  43. if act_cfg['type'] == 'SiLU':
  44. return nn.SiLU(inplace=True)
  45. # Add other activation types here if needed
  46. raise NotImplementedError(f"Activation layer '{act_cfg['type']}' is not implemented.")
  47. class CAA(nn.Module):
  48. """Context Anchor Attention"""
  49. def __init__(
  50. self,
  51. channels: int,
  52. h_kernel_size: int = 11,
  53. v_kernel_size: int = 11,
  54. norm_cfg: Optional[dict] = dict(type='BN', momentum=0.03, eps=0.001),
  55. act_cfg: Optional[dict] = dict(type='SiLU'),
  56. ):
  57. super().__init__()
  58. self.avg_pool = nn.AvgPool2d(7, 1, 3)
  59. self.conv1 = ConvModule(channels, channels, 1, 1, 0,
  60. norm_cfg=norm_cfg, act_cfg=act_cfg)
  61. self.h_conv = ConvModule(channels, channels, (1, h_kernel_size), 1,
  62. (0, h_kernel_size // 2), groups=channels,
  63. norm_cfg=None, act_cfg=None)
  64. self.v_conv = ConvModule(channels, channels, (v_kernel_size, 1), 1,
  65. (v_kernel_size // 2, 0), groups=channels,
  66. norm_cfg=None, act_cfg=None)
  67. self.conv2 = ConvModule(channels, channels, 1, 1, 0,
  68. norm_cfg=norm_cfg, act_cfg=act_cfg)
  69. self.act = nn.Sigmoid()
  70. def forward(self, x):
  71. attn_factor = self.act(self.conv2(self.v_conv(self.h_conv(self.conv1(self.avg_pool(x))))))
  72. return attn_factor
  73. def autopad(k, p=None, d=1): # kernel, padding, dilation
  74. """Pad to 'same' shape outputs."""
  75. if d > 1:
  76. k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size
  77. if p is None:
  78. p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
  79. return p
  80. class Conv(nn.Module):
  81. """Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation)."""
  82. default_act = nn.SiLU() # default activation
  83. def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
  84. """Initialize Conv layer with given arguments including activation."""
  85. super().__init__()
  86. self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
  87. self.bn = nn.BatchNorm2d(c2)
  88. self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
  89. def forward(self, x):
  90. """Apply convolution, batch normalization and activation to input tensor."""
  91. return self.act(self.bn(self.conv(x)))
  92. def forward_fuse(self, x):
  93. """Perform transposed convolution of 2D data."""
  94. return self.act(self.conv(x))
  95. class PSABlock(nn.Module):
  96. """
  97. PSABlock class implementing a Position-Sensitive Attention block for neural networks.
  98. This class encapsulates the functionality for applying multi-head attention and feed-forward neural network layers
  99. with optional shortcut connections.
  100. Attributes:
  101. attn (Attention): Multi-head attention module.
  102. ffn (nn.Sequential): Feed-forward neural network module.
  103. add (bool): Flag indicating whether to add shortcut connections.
  104. Methods:
  105. forward: Performs a forward pass through the PSABlock, applying attention and feed-forward layers.
  106. Examples:
  107. Create a PSABlock and perform a forward pass
  108. """
  109. def __init__(self, c, attn_ratio=0.5, num_heads=4, shortcut=True) -> None:
  110. """Initializes the PSABlock with attention and feed-forward layers for enhanced feature extraction."""
  111. super().__init__()
  112. self.attn = CAA(c)
  113. self.ffn = nn.Sequential(Conv(c, c * 2, 1), Conv(c * 2, c, 1, act=False))
  114. self.add = shortcut
  115. def forward(self, x):
  116. """Executes a forward pass through PSABlock, applying attention and feed-forward layers to the input tensor."""
  117. x = x + self.attn(x) if self.add else self.attn(x)
  118. x = x + self.ffn(x) if self.add else self.ffn(x)
  119. return x
  120. class C2PSA_CAA(nn.Module):
  121. """
  122. C2PSA module with attention mechanism for enhanced feature extraction and processing.
  123. This module implements a convolutional block with attention mechanisms to enhance feature extraction and processing
  124. capabilities. It includes a series of PSABlock modules for self-attention and feed-forward operations.
  125. Attributes:
  126. c (int): Number of hidden channels.
  127. cv1 (Conv): 1x1 convolution layer to reduce the number of input channels to 2*c.
  128. cv2 (Conv): 1x1 convolution layer to reduce the number of output channels to c.
  129. m (nn.Sequential): Sequential container of PSABlock modules for attention and feed-forward operations.
  130. Methods:
  131. forward: Performs a forward pass through the C2PSA module, applying attention and feed-forward operations.
  132. Notes:
  133. This module essentially is the same as PSA module, but refactored to allow stacking more PSABlock modules.
  134. Examples:
  135. """
  136. def __init__(self, c1, c2, n=1, e=0.5):
  137. """Initializes the C2PSA module with specified input/output channels, number of layers, and expansion ratio."""
  138. super().__init__()
  139. assert c1 == c2
  140. self.c = int(c1 * e)
  141. self.cv1 = Conv(c1, 2 * self.c, 1, 1)
  142. self.cv2 = Conv(2 * self.c, c1, 1)
  143. self.m = nn.Sequential(*(PSABlock(self.c, attn_ratio=0.5, num_heads=self.c // 64) for _ in range(n)))
  144. def forward(self, x):
  145. """Processes the input tensor 'x' through a series of PSA blocks and returns the transformed tensor."""
  146. a, b = self.cv1(x).split((self.c, self.c), dim=1)
  147. b = self.m(b)
  148. return self.cv2(torch.cat((a, b), 1))
  149. if __name__ == "__main__":
  150. # Generating Sample image
  151. image_size = (1, 36, 224, 224)
  152. image = torch.rand(*image_size)
  153. # Model
  154. model = CAA(36)
  155. out = model(image)
  156. print(out.size())


四、添加教程

4.1 修改一

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


4.2 修改二

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

​​


4.3 修改三

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

​​


4.4 修改四

按照我的添加在parse_model里添加即可。

​​


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


五、正式训练


5.1 yaml文件1

训练信息:YOLO11-C2PSA-CAA summary: 326 layers, 2,575,059 parameters, 2,575,043 gradients, 6.4 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_CAA, [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)


5.2 yaml文件2

训练信息:YOLO11-CAA summary: 376 layers, 2,774,611 parameters, 2,774,595 gradients, 6.8 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, CAA, []] # 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, CAA, []] # 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, CAA, []] # 25 (P5/32-large) 大目标检测层输出位置增加注意力机制
  43. # 注意力机制我这里其实是添加了三个但是实际一般生效就只添加一个就可以了,所以大家可以自行注释来尝试, 上面三个仅建议大家保留一个, 但是from位置要对齐.
  44. # 具体在那一层用注意力机制可以根据自己的数据集场景进行选择。
  45. # 如果你自己配置注意力位置注意from[17, 21, 25]位置要对应上对应的检测层!
  46. - [[17, 21, 25], 1, Detect, [nc]] # Detect(P3, P4, P5)


5.3 训练代码

大家可以创建一个py文件将我给的代码复制粘贴进去,配置好自己的文件路径即可运行。

  1. import warnings
  2. warnings.filterwarnings('ignore')
  3. from ultralytics import YOLO
  4. if __name__ == '__main__':
  5. model = YOLO('模型配置文件')
  6. # 如何切换模型版本, 上面的ymal文件可以改为 yolov8s.yaml就是使用的v8s,
  7. # 类似某个改进的yaml文件名称为yolov8-XXX.yaml那么如果想使用其它版本就把上面的名称改为yolov8l-XXX.yaml即可(改的是上面YOLO中间的名字不是配置文件的)!
  8. # model.load('yolov8n.pt') # 是否加载预训练权重,科研不建议大家加载否则很难提升精度
  9. model.train(data=r"C:\Users\Administrator\PycharmProjects\yolov5-master\yolov5-master\Construction Site Safety.v30-raw-images_latestversion.yolov8\data.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=16,
  16. close_mosaic=0,
  17. workers=0,
  18. device='0',
  19. optimizer='SGD', # using SGD
  20. # resume='runs/train/exp21/weights/last.pt', # 如过想续训就设置last.pt的地址
  21. amp=True, # 如果出现训练损失为Nan可以关闭amp
  22. project='runs/train',
  23. name='exp',
  24. )


5.4 训练过程截图


五、本文总结

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