学习资源站

YOLOv11改进-添加注意力机制-可变形大核注意力Deformable-LKA二次创新C2PSA机制助力yolov11改进

一、本文介绍

本文给大家带来的改进内容是 Deformable-LKA 。Deformable-LKA结合了大 卷积核 的广阔感受野和可变形卷积的灵活性,有效地处理复杂的视觉信息。这一机制通过动态调整卷积核的形状和大小来适应不同的图像特征,提高了 模型 对目标形状和尺寸的适应性。在YOLOv11中,Deformable-LKA可以被用于 提升对小目标和不规则形状目标的检测能力 特别是在复杂背景或不同光照条件下 我进行了简单的实验,这一改进显著提高了模型mAP, 含二次创新C2PSA机制

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



二、D eformable-LKA机制原理

论文地址: 官方论文地址

代码地址: 官方代码地址


2.1 D eformable-LKA的基本原理

Deformable Large Kernel Attention (D-LKA) 的基本原理是结合了大卷积核和 可变形卷积 的注意力机制,通过采用大卷积核来模拟类似自我关注的感受野,同时避免了传统自我关注机制的高计算成本。此外,D-LKA通过 可变形卷积 来灵活调整采样网格,使得模型能够更好地适应不同的数据模式。可以将其分为以下几点:

1. 大卷积核: D-LKA 使用大卷积核来捕捉图像的广泛上下文信息,模仿自我关注机制的 感受野

2. 可变形卷积: 结合可变形卷积技术,允许模型的采样网格根据图像特征灵活变形,适应不同的数据模式。

3. 2D和3D适应性: D-LKA的2D和3D版本,使其在处理不同深度的数据时表现出色。

下面我来分别讲解这三种主要的改进机制->


2.2 大卷积核

大卷积核(Large Kernel) 是一种用于捕捉图像中的广泛上下文信息的机制。它模仿自注意力(self-attention)机制的感受野,但是使用更少的参数和计算量。通过 使用深度可分离的卷积(depth-wise convolution) 深度可分离的带扩张的卷积(depth-wise dilated convolution) ,可以有效地构造大卷积核。这种方法允许网络在较大的感受野内学习特征,同时通过减少参数数量来降低计算复杂度。在Deformable LKA中,大卷积核与可变形卷积结合使用,进一步增加了模型对复杂图像模式的 适应性

上图为变形大核注意力(Deformable Large Kernel Attention, D-LKA)模块的架构。从图中可以看出,该模块由多个卷积层组成,包括:

1. 标准的2D卷积(Conv2D)。
2. 带有偏移量的变形卷积(Deformable Convolution, Deform-DW Conv2D),允许网络根据输入特征自适应地调整其感受野。
3. 偏移场(Offsets Field)的计算,它是由一个标准卷积层生成,用于指导变形卷积层如何调整其采样位置。
4. 激活函数 GELU,增加非线性。


2.3 可变形卷积

可变形卷积(Deformable Convolution) 被用来增强模型对医学图像中的不规则形状和大小的捕捉能力。可变形卷积通过 添加额外的偏移量 来调整标准卷积的采样位置,从而允许卷积核动态地适应图像的内容。这样的机制使得卷积层能够更加灵活地捕捉到各种形态的结构,特别是在医学图像中常见的不规则和可变形的器官。通过学习图像特征本身来确定这些偏移量,可变形卷积能够提供一种自适应的内核形状,这有助于提升分割的精确性和边缘定义。


2.4 2D和3D适应性

2D和3D适应性指的是Deformable Large Kernel Attention(D-LKA)技术 应用于不同维度数据的能力 2D D-LKA 专为处理二维图像数据设计,适用于常见的医学成像方法,如X射线或MRI中的单层切片。而 3D D-LKA 则扩展了这种技术,使其能够处理三维数据集,充分利用体积图像数据中的空间上下文信息。3D版本特别擅长于交叉深度数据理解,即能够在多个层面上分析和识别图像特征,这对于体积重建和更复杂的医学成像任务非常有用。

上图展示了3D和2D Deformable Large Kernel Attention(D-LKA)模型的网络架构。左侧是3D D-LKA模型,右侧是2D D-LKA模型。

1. 3D D-LKA模型(左侧): 包含多个3D D-LKA块,这些块在下采样和上采样之间交替,用于深度特征学习和分辨率恢复。

2. 2D D-LKA模型(右侧): 利用MaxViT块作为编码器组件,并在不同的分辨率级别上使用2D D-LKA块,通过扩展(Patch Expanding)和D-LKA注意力机制进行特征学习。


三、核心代码

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

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


四、手把手教你添加 D -LKA

4.1 修改一

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


4.2 修改二

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


4.3 修改三

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

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


4.4 修改四

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


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


五、DLKA的yaml文件和运行记录

5.1 DLKA的yaml文件1

此版本训练信息:YOLO11-C2PSA-DLKA summary: 319 layers, 3,377,199 parameters, 3,377,183 gradients, 7.1 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_DLKA, [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 DLKA的yaml文件2

此版本训练信息:YOLO11-DLKA summary: 355 layers, 5,598,999 parameters, 5,598,983 gradients, 15.6 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, deformable_LKA_Attention, []] # 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, deformable_LKA_Attention, []] # 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, deformable_LKA_Attention, []] # 25 (P5/32-large) 大目标检测层输出位置增加注意力机制
  43. # 具体在那一层用注意力机制可以根据自己的数据集场景进行选择。
  44. # 如果你自己配置注意力位置注意from[17, 21, 25]位置要对应上对应的检测层!
  45. - [[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('ultralytics/cfg/models/v8/yolov8-C2f-FasterBlock.yaml')
  6. # model.load('yolov8n.pt') # loading pretrain weights
  7. model.train(data=r'替换数据集yaml文件地址',
  8. # 如果大家任务是其它的'ultralytics/cfg/default.yaml'找到这里修改task可以改成detect, segment, classify, pose
  9. cache=False,
  10. imgsz=640,
  11. epochs=150,
  12. single_cls=False, # 是否是单类别检测
  13. batch=4,
  14. close_mosaic=10,
  15. workers=0,
  16. device='0',
  17. optimizer='SGD', # using SGD
  18. # resume='', # 如过想续训就设置last.pt的地址
  19. amp=False, # 如果出现训练损失为Nan可以关闭amp
  20. project='runs/train',
  21. name='exp',
  22. )


5.4 DLKA的训练过程截图


六、本文总结

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