学习资源站

YOLOv11改进-Conv篇-添加SCConv空间和通道重构卷积二次创新C3k2(辅助yolov11进行特征提取)

一、本文介绍

本文给大家带来的改进内容是 SCConv ,即空间和通道重构卷积,是一种发布于2023.9月份的一个新的改进机制。它的核心创新在于能够同时处理图像的空间 (形状、结构) 和通道 色彩、深度) 信息,这样的处理方式使得SCConv在分析图像时更加精细和高效。这种技术不仅适用于复杂场景的 图像处理 ,还能在普通的对象检测任务中提供更高的精确度 (亲测在小目标检测和正常的物体检测中都有效提点) 。SCConv的这种能力,特别是在处理大量数据和复杂图像时的优势。本文通过先介绍SCConv的基本网络结构和原理当大家对该卷积有一个大概的了解,然后教大家如何将该卷积添加到自己的网络结构中

44308abda9734a91ad908faca9a7fd5a.png

适用检测目标: 所有的目标检测均有一定的提点


二、网络结构讲解

51a53656d50a4c3d8715d8357595201d.png

论文地址: 官方论文地址

代码地址: 官方代码地址

107067b614d447b58528d6c435965dd2.png


2.1 SCConv的主要思想

SCConv(空间和通道重构卷积 的高效卷积模块,以减少 卷积神经网络 (CNN)中的空间和通道冗余。SCConv旨在通过优化特征提取过程,减少计算资源消耗并提高网络性能。该模块包括两个单元:

1.空间重构单元(SRU): SRU通过分离和重构方法来减少空间冗余。

2.通道重构单元(CRU): CRU采用分割-变换-融合策略来减少通道冗余。

下面是SCConv的结构示意图->

c0aa4cd5b2f24a59b39a078abc29e91d.png

下面我将分别解释这两个单元->


2.2 空间重构单元(SRU)

空间重构单元(SRU) 是SCConv模块的一部分,负责减少特征在空间维度上的冗余。SRU接收输入特征,并通过以下步骤处理:

1. 组归一化(Group Normalization): 首先对输入特征进行归一化,以减少不同特征图之间的尺度差异。
2. 权重生成: 通过应用归一化和激活 函数 ,如Sigmoid,从归一化的特征图中生成权重。
3. 特征分离: 根据生成的权重,对输入特征进行分离,形成多个子特征集。
4. 特征重构: 最后,这些分离出来的特征集经过变换和重组,产生空间精炼的特征输出,以便进一步处理。

6c0b287f19104d6cad1a886d2fd587b9.png

上图展示了空间重构单元(SRU)的架构。SRU的工作流程如下:

1. 输入特征X:首先进行组归一化(GN)处理。
2. 分离:通过一系列的权重 eq?W_%7B1%7D , eq?W_%7B2%7D , ..., eq?W_%7BC%7D 对特征进行加权,这些权重是通过输入特征的通道 eq?%5Cgamma_1%2C%20%5Cgamma_2%2C%20...%2C%20%5Cgamma_c 经过归一化和非线性激活函数(如Sigmoid)计算得到的。
3. 重构:加权后的特征被分割成两个部分 eq?X_%7BW%7D%5E%7B1%7Deq?X_%7BW%7D%5E%7B2%7D ,然后这两部分各自经过变换,最终通过加法和拼接操作重构,得到空间精炼特征 eq?X_%7BW%7D

总结: 这个单元的设计目的是为了减少输入特征的空间冗余,从而提高卷积 神经网络 处理特征的效率。


2.3 通道重构单元(CRU)

通道重构单元(CRU) 是SCConv模块的一部分,旨在减少卷积神经网络特征的通道冗余。CRU对经过空间重构单元(SRU)处理后的特征进一步操作,通过以下步骤减少通道冗余:

f3d201d671a64fcbbea33a99438fb3d8.png

上图详细展示了通道重构单元(CRU)的架构,该单元从空间精炼特征 \( X^W \) 开始进行处理。CRU的工作流程包括以下几个步骤:

1. 分割( Split ):特征 eq?X%5E%7BW%7D 被分割成两部分,通过不同比例的 eq?%5Calphaeq?%281-%5Calpha%29 路径进行不同的1x1卷积处理。
2. 变换(Transform):通过全局卷积(GWC)和点卷积(PWC)进一步变换这两部分特征。
3. 融合(Fuse):两个变换后的特征 eq?Y_%7B1%7Deq?Y_%7B2%7D 经过池化和SoftMax加权融合,形成最终的通道精炼特征 eq?Y

总结: 这种结构旨在通过细致地处理各个通道,减少不必要的信息,并提高网络的整体性能和效率。通过这一过程,CRU有效地提高了特征的表征效率,同时减少了 模型 的参数数量和计算成本。


三、SCConv代码

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

  1. import torch
  2. import torch.nn.functional as F
  3. import torch.nn as nn
  4. __all__ = ['ScConv', 'C3k2_ScConv']
  5. class GroupBatchnorm2d(nn.Module):
  6. def __init__(self, c_num: int,
  7. group_num: int = 16,
  8. eps: float = 1e-10
  9. ):
  10. super(GroupBatchnorm2d, self).__init__()
  11. assert c_num >= group_num
  12. self.group_num = group_num
  13. self.weight = nn.Parameter(torch.randn(c_num, 1, 1))
  14. self.bias = nn.Parameter(torch.zeros(c_num, 1, 1))
  15. self.eps = eps
  16. def forward(self, x):
  17. N, C, H, W = x.size()
  18. x = x.view(N, self.group_num, -1)
  19. mean = x.mean(dim=2, keepdim=True)
  20. std = x.std(dim=2, keepdim=True)
  21. x = (x - mean) / (std + self.eps)
  22. x = x.view(N, C, H, W)
  23. return x * self.weight + self.bias
  24. class SRU(nn.Module):
  25. def __init__(self,
  26. oup_channels: int,
  27. group_num: int = 16,
  28. gate_treshold: float = 0.5,
  29. torch_gn: bool = True
  30. ):
  31. super().__init__()
  32. self.gn = nn.GroupNorm(num_channels=oup_channels, num_groups=group_num) if torch_gn else GroupBatchnorm2d(
  33. c_num=oup_channels, group_num=group_num)
  34. self.gate_treshold = gate_treshold
  35. self.sigomid = nn.Sigmoid()
  36. def forward(self, x):
  37. gn_x = self.gn(x)
  38. w_gamma = self.gn.weight / sum(self.gn.weight)
  39. w_gamma = w_gamma.view(1, -1, 1, 1)
  40. reweigts = self.sigomid(gn_x * w_gamma)
  41. # Gate
  42. w1 = torch.where(reweigts > self.gate_treshold, torch.ones_like(reweigts), reweigts) # 大于门限值的设为1,否则保留原值
  43. w2 = torch.where(reweigts > self.gate_treshold, torch.zeros_like(reweigts), reweigts) # 大于门限值的设为0,否则保留原值
  44. x_1 = w1 * x
  45. x_2 = w2 * x
  46. y = self.reconstruct(x_1, x_2)
  47. return y
  48. def reconstruct(self, x_1, x_2):
  49. x_11, x_12 = torch.split(x_1, x_1.size(1) // 2, dim=1)
  50. x_21, x_22 = torch.split(x_2, x_2.size(1) // 2, dim=1)
  51. return torch.cat([x_11 + x_22, x_12 + x_21], dim=1)
  52. class CRU(nn.Module):
  53. '''
  54. alpha: 0<alpha<1
  55. '''
  56. def __init__(self,
  57. op_channel: int,
  58. alpha: float = 1 / 2,
  59. squeeze_radio: int = 2,
  60. group_size: int = 2,
  61. group_kernel_size: int = 3,
  62. ):
  63. super().__init__()
  64. self.up_channel = up_channel = int(alpha * op_channel)
  65. self.low_channel = low_channel = op_channel - up_channel
  66. self.squeeze1 = nn.Conv2d(up_channel, up_channel // squeeze_radio, kernel_size=1, bias=False)
  67. self.squeeze2 = nn.Conv2d(low_channel, low_channel // squeeze_radio, kernel_size=1, bias=False)
  68. # up
  69. self.GWC = nn.Conv2d(up_channel // squeeze_radio, op_channel, kernel_size=group_kernel_size, stride=1,
  70. padding=group_kernel_size // 2, groups=group_size)
  71. self.PWC1 = nn.Conv2d(up_channel // squeeze_radio, op_channel, kernel_size=1, bias=False)
  72. # low
  73. self.PWC2 = nn.Conv2d(low_channel // squeeze_radio, op_channel - low_channel // squeeze_radio, kernel_size=1,
  74. bias=False)
  75. self.advavg = nn.AdaptiveAvgPool2d(1)
  76. def forward(self, x):
  77. # Split
  78. up, low = torch.split(x, [self.up_channel, self.low_channel], dim=1)
  79. up, low = self.squeeze1(up), self.squeeze2(low)
  80. # Transform
  81. Y1 = self.GWC(up) + self.PWC1(up)
  82. Y2 = torch.cat([self.PWC2(low), low], dim=1)
  83. # Fuse
  84. out = torch.cat([Y1, Y2], dim=1)
  85. out = F.softmax(self.advavg(out), dim=1) * out
  86. out1, out2 = torch.split(out, out.size(1) // 2, dim=1)
  87. return out1 + out2
  88. def autopad(k, p=None, d=1): # kernel, padding, dilation
  89. """Pad to 'same' shape outputs."""
  90. if d > 1:
  91. k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size
  92. if p is None:
  93. p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
  94. return p
  95. class Conv(nn.Module):
  96. """Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation)."""
  97. default_act = nn.SiLU() # default activation
  98. def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
  99. """Initialize Conv layer with given arguments including activation."""
  100. super().__init__()
  101. self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
  102. self.bn = nn.BatchNorm2d(c2)
  103. self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
  104. def forward(self, x):
  105. """Apply convolution, batch normalization and activation to input tensor."""
  106. return self.act(self.bn(self.conv(x)))
  107. def forward_fuse(self, x):
  108. """Perform transposed convolution of 2D data."""
  109. return self.act(self.conv(x))
  110. class ScConv(nn.Module):
  111. def __init__(self,
  112. op_channel: int,
  113. group_num: int = 4,
  114. gate_treshold: float = 0.5,
  115. alpha: float = 1 / 2,
  116. squeeze_radio: int = 2,
  117. group_size: int = 2,
  118. group_kernel_size: int = 3,
  119. ):
  120. super().__init__()
  121. self.SRU = SRU(op_channel,
  122. group_num=group_num,
  123. gate_treshold=gate_treshold)
  124. self.CRU = CRU(op_channel,
  125. alpha=alpha,
  126. squeeze_radio=squeeze_radio,
  127. group_size=group_size,
  128. group_kernel_size=group_kernel_size)
  129. def forward(self, x):
  130. x = self.SRU(x)
  131. x = self.CRU(x)
  132. return x
  133. class Bottleneck(nn.Module):
  134. """Standard bottleneck."""
  135. def __init__(self, c1, c2, shortcut=True, g=1, k=(3, 3), e=0.5):
  136. """Initializes a standard bottleneck module with optional shortcut connection and configurable parameters."""
  137. super().__init__()
  138. c_ = int(c2 * e) # hidden channels
  139. self.cv1 = Conv(c1, c_, k[0], 1)
  140. self.cv2 = Conv(c_, c2, k[1], 1, g=g)
  141. self.add = shortcut and c1 == c2
  142. def forward(self, x):
  143. """Applies the YOLO FPN to input data."""
  144. return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
  145. class Bottleneck_ScConv(nn.Module):
  146. """Standard bottleneck."""
  147. def __init__(self, c1, c2, shortcut=True, g=1, k=(3, 3), e=0.5):
  148. """Initializes a bottleneck module with given input/output channels, shortcut option, group, kernels, and
  149. expansion.
  150. """
  151. super().__init__()
  152. c_ = int(c2 * e) # hidden channels
  153. self.cv1 = Conv(c1, c_, k[0], 1)
  154. self.cv2 = ScConv(c_)
  155. self.add = shortcut and c1 == c2
  156. def forward(self, x):
  157. """'forward()' applies the YOLO FPN to input data."""
  158. return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
  159. class C2f(nn.Module):
  160. """Faster Implementation of CSP Bottleneck with 2 convolutions."""
  161. def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5):
  162. """Initializes a CSP bottleneck with 2 convolutions and n Bottleneck blocks for faster processing."""
  163. super().__init__()
  164. self.c = int(c2 * e) # hidden channels
  165. self.cv1 = Conv(c1, 2 * self.c, 1, 1)
  166. self.cv2 = Conv((2 + n) * self.c, c2, 1) # optional act=FReLU(c2)
  167. self.m = nn.ModuleList(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n))
  168. def forward(self, x):
  169. """Forward pass through C2f layer."""
  170. y = list(self.cv1(x).chunk(2, 1))
  171. y.extend(m(y[-1]) for m in self.m)
  172. return self.cv2(torch.cat(y, 1))
  173. def forward_split(self, x):
  174. """Forward pass using split() instead of chunk()."""
  175. y = list(self.cv1(x).split((self.c, self.c), 1))
  176. y.extend(m(y[-1]) for m in self.m)
  177. return self.cv2(torch.cat(y, 1))
  178. class C3(nn.Module):
  179. """CSP Bottleneck with 3 convolutions."""
  180. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
  181. """Initialize the CSP Bottleneck with given channels, number, shortcut, groups, and expansion values."""
  182. super().__init__()
  183. c_ = int(c2 * e) # hidden channels
  184. self.cv1 = Conv(c1, c_, 1, 1)
  185. self.cv2 = Conv(c1, c_, 1, 1)
  186. self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2)
  187. self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, k=((1, 1), (3, 3)), e=1.0) for _ in range(n)))
  188. def forward(self, x):
  189. """Forward pass through the CSP bottleneck with 2 convolutions."""
  190. return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
  191. class C3k(C3):
  192. """C3k is a CSP bottleneck module with customizable kernel sizes for feature extraction in neural networks."""
  193. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, k=3):
  194. """Initializes the C3k module with specified channels, number of layers, and configurations."""
  195. super().__init__(c1, c2, n, shortcut, g, e)
  196. c_ = int(c2 * e) # hidden channels
  197. # self.m = nn.Sequential(*(RepBottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
  198. self.m = nn.Sequential(*(Bottleneck_ScConv(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
  199. class C3k2_ScConv(C2f):
  200. """Faster Implementation of CSP Bottleneck with 2 convolutions."""
  201. def __init__(self, c1, c2, n=1, c3k=False, e=0.5, g=1, shortcut=True):
  202. """Initializes the C3k2 module, a faster CSP Bottleneck with 2 convolutions and optional C3k blocks."""
  203. super().__init__(c1, c2, n, shortcut, g, e)
  204. self.m = nn.ModuleList(
  205. C3k(self.c, self.c, 2, shortcut, g) if c3k else Bottleneck(self.c, self.c, shortcut, g) for _ in range(n)
  206. ) # 用ScConv提取特征, 特征融合时换回普通的Bottlenck
  207. if __name__ == "__main__":
  208. # Generating Sample image
  209. image_size = (1, 64, 240, 240)
  210. image = torch.rand(*image_size)
  211. # Model
  212. mobilenet_v1 = C3k2_ScConv(64, 64)
  213. out = mobilenet_v1(image)
  214. 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文件

模型的训练信息:YOLO11-C3k2-ScConv summary: 368 layers, 2,462,555 parameters, 2,462,539 gradients, 6.3 GFLOPs

 # 用ScConv提取特征, 特征融合时换回普通的Bottlenck
  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_ScConv, [256, False, 0.25]]
  18. - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8
  19. - [-1, 2, C3k2_ScConv, [512, False, 0.25]]
  20. - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16
  21. - [-1, 2, C3k2_ScConv, [512, True]]
  22. - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32
  23. - [-1, 2, C3k2_ScConv, [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_ScConv, [512, False]] # 13
  31. - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
  32. - [[-1, 4], 1, Concat, [1]] # cat backbone P3
  33. - [-1, 2, C3k2_ScConv, [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_ScConv, [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_ScConv, [1024, True]] # 22 (P5/32-large)
  40. - [[16, 19, 22], 1, Detect, [nc]] # Detect(P3, P4, P5)


5.2 训练截图


5.3 训练代码

  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. )


六、本文总结

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

3d51a0611af1442f833362eaf18fbae2.gif