学习资源站

YOLOv11改进-细节创新篇篇-最新双时相特征聚合模块BFAM助力yolov11有效涨点(二次创新C3k2全网独家首发)

一、本文介绍

本文给大家带来的最新改进机制是 2024年的双时相特征聚合模块BFAM ,其中 双时相特征聚合模块(BFAM) 基于空间-时间特征聚合多种 感受野 的特征,同时保留了细粒度信息和纹理信息,增强了变化检测的准确性,我将其用于二次创新yolov11中的C3k2模块,目的是为了提高了图像变化检测的准确性,解决噪声和信息丢失的问题,本文的内容为独家创新, 下图为BFAM网络的结构图

欢迎大家订阅我的专栏一起学习YOLO,购买专栏读者联系读者入群获取进阶项目文件!


一、本文介绍

二、原理介绍

三、核心代码

四、添加教程

4.1 修改一

4.2 修改二

4.3 修改三

4.4 修改四

五、正式训练

5.1 yaml文件1

5.2 yaml文件2

5.3 训练代码

5.4 训练过程截图

五、本文总结


二、原理介绍

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

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


这篇文章的标题是《B2CNet: 一种用于多时相遥感图像 变化检测 的渐进式变化边界到中心精细化网络》。文章的核心思想是提出了一种新的变化检测方法,以解决现有深度学习方法在检测变化时遇到的边界信息丢失和噪声问题。

核心思想:

  1. 变化检测问题 :传统的变化检测方法通常会丢失边界和变化区域内部的细节信息,这会导致检测精度低。特征之间的差异可能来自于光照变化或几何变化,而非实际的变化区域,进而影响检测的准确性。

  2. 提出的解决方案——B2CNet

    • 变化边界感知模块 :该模块能够捕捉变化区域的边界信息,从而增强边界的检测,减少噪声对特征差异的影响,并提供更丰富的上下文信息来提高边界的准确性。
    • 双时相特征聚合模块(BFAM) :BFAM基于空间-时间特征聚合多种感受野的特征,同时保留了细粒度信息和纹理信息,增强了变化检测的准确性。
    • SimAM注意力机制 :网络采用了SimAM注意力机制,专注于关键特征,进一步提高了特征提取的精细程度,从而改善变化检测的效果。
    • 深度特征提取模块 :该模块负责提取图像的深度特征,减少信息损失,从而确保在变化检测过程中准确地表示图像数据。

总结: 这篇文章提出了一种新的变化检测网络(B2CNet),通过边界感知和多种精细化特征提取模块,提高了遥感图像变化检测的准确性,解决了现有方法中噪声和信息丢失的问题。


三、核心代码

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

  1. import torch
  2. import torch.nn as nn
  3. __all__ = ['C3k2_BFAM_1', 'C3k2_BFAM_2']
  4. def initialize_weights(*models):
  5. for model in models:
  6. for module in model.modules():
  7. if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear):
  8. nn.init.kaiming_normal_(module.weight)
  9. if module.bias is not None:
  10. module.bias.data.zero_()
  11. elif isinstance(module, nn.BatchNorm2d):
  12. module.weight.data.fill_(1)
  13. module.bias.data.zero_()
  14. class simam_module(torch.nn.Module):
  15. def __init__(self, channels=None, e_lambda=1e-4):
  16. super(simam_module, self).__init__()
  17. self.activaton = nn.Sigmoid()
  18. self.e_lambda = e_lambda
  19. def __repr__(self):
  20. s = self.__class__.__name__ + '('
  21. s += ('lambda=%f)' % self.e_lambda)
  22. return s
  23. @staticmethod
  24. def get_module_name():
  25. return "simam"
  26. def forward(self, x):
  27. b, c, h, w = x.size()
  28. n = w * h - 1
  29. x_minus_mu_square = (x - x.mean(dim=[2, 3], keepdim=True)).pow(2)
  30. y = x_minus_mu_square / (4 * (x_minus_mu_square.sum(dim=[2, 3], keepdim=True) / n + self.e_lambda)) + 0.5
  31. return x * self.activaton(y)
  32. class BFAM(nn.Module):
  33. def __init__(self,inp):
  34. super(BFAM, self).__init__()
  35. out = inp
  36. inp = int (inp * 2)
  37. self.pre_siam = simam_module()
  38. self.lat_siam = simam_module()
  39. out_1 = int(inp/2)
  40. self.conv_1 = nn.Conv2d(inp, out_1 , padding=1, kernel_size=3,groups=out_1,
  41. dilation=1)
  42. self.conv_2 = nn.Conv2d(inp, out_1, padding=2, kernel_size=3,groups=out_1,
  43. dilation=2)
  44. self.conv_3 = nn.Conv2d(inp, out_1, padding=3, kernel_size=3,groups=out_1,
  45. dilation=3)
  46. self.conv_4 = nn.Conv2d(inp, out_1, padding=4, kernel_size=3,groups=out_1,
  47. dilation=4)
  48. self.conv_4 = nn.Conv2d(inp, out_1, 1, 1)
  49. self.fuse = nn.Sequential(
  50. nn.Conv2d(out_1 * 4, out_1, kernel_size=1, padding=0),
  51. nn.BatchNorm2d(out_1),
  52. nn.ReLU(inplace=True)
  53. )
  54. self.fuse_siam = simam_module()
  55. self.out = nn.Sequential(
  56. nn.Conv2d(out_1, out, kernel_size=3, padding=1),
  57. nn.BatchNorm2d(out),
  58. nn.ReLU(inplace=True)
  59. )
  60. def forward(self, inp1, inp2, last_feature=None):
  61. x = torch.cat([inp1, inp2],dim=1)
  62. c1 = self.conv_1(x)
  63. c2 = self.conv_2(x)
  64. c3 = self.conv_3(x)
  65. c4 = self.conv_4(x)
  66. cat = torch.cat([c1,c2,c3,c4],dim=1)
  67. fuse = self.fuse(cat)
  68. inp1_siam = self.pre_siam(inp1)
  69. inp2_siam = self.lat_siam(inp2)
  70. inp1_mul = torch.mul(inp1_siam,fuse)
  71. inp2_mul = torch.mul(inp2_siam,fuse)
  72. fuse = self.fuse_siam(fuse)
  73. if last_feature is None:
  74. out = self.out(fuse + inp1 + inp2 + inp2_mul + inp1_mul)
  75. else:
  76. out = self.out(fuse+inp2_mul+inp1_mul+last_feature+inp1+inp2)
  77. out = self.fuse_siam(out)
  78. return out
  79. class Bottleneck_BFAM(nn.Module):
  80. """Standard bottleneck."""
  81. def __init__(self, c1, c2, shortcut=True, g=1, k=(3, 3), e=0.5):
  82. """Initializes a bottleneck module with given input/output channels, shortcut option, group, kernels, and
  83. expansion.
  84. """
  85. super().__init__()
  86. c_ = int(c2 * e) # hidden channels
  87. self.cv1 = Conv(c1, c_, k[0], 1)
  88. self.cv2 = Conv(c_, c2, k[1], 1, g=g)
  89. self.add = shortcut and c1 == c2
  90. self.BFAM = BFAM(c2)
  91. def forward(self, x):
  92. """'forward()' applies the YOLO FPN to input data."""
  93. if self.add:
  94. results = self.BFAM(x, self.cv2(self.cv1(x)))
  95. else:
  96. results = self.cv2(self.cv1(x))
  97. return results
  98. class Bottleneck(nn.Module):
  99. """Standard bottleneck."""
  100. def __init__(self, c1, c2, shortcut=True, g=1, k=(3, 3), e=0.5):
  101. """Initializes a standard bottleneck module with optional shortcut connection and configurable parameters."""
  102. super().__init__()
  103. c_ = int(c2 * e) # hidden channels
  104. self.cv1 = Conv(c1, c_, k[0], 1)
  105. self.cv2 = Conv(c_, c2, k[1], 1, g=g)
  106. self.add = shortcut and c1 == c2
  107. def forward(self, x):
  108. """Applies the YOLO FPN to input data."""
  109. return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
  110. class C2f(nn.Module):
  111. """Faster Implementation of CSP Bottleneck with 2 convolutions."""
  112. def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5):
  113. """Initializes a CSP bottleneck with 2 convolutions and n Bottleneck blocks for faster processing."""
  114. super().__init__()
  115. self.c = int(c2 * e) # hidden channels
  116. self.cv1 = Conv(c1, 2 * self.c, 1, 1)
  117. self.cv2 = Conv((2 + n) * self.c, c2, 1) # optional act=FReLU(c2)
  118. self.m = nn.ModuleList(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n))
  119. def forward(self, x):
  120. """Forward pass through C2f layer."""
  121. y = list(self.cv1(x).chunk(2, 1))
  122. y.extend(m(y[-1]) for m in self.m)
  123. return self.cv2(torch.cat(y, 1))
  124. def forward_split(self, x):
  125. """Forward pass using split() instead of chunk()."""
  126. y = list(self.cv1(x).split((self.c, self.c), 1))
  127. y.extend(m(y[-1]) for m in self.m)
  128. return self.cv2(torch.cat(y, 1))
  129. def autopad(k, p=None, d=1): # kernel, padding, dilation
  130. """Pad to 'same' shape outputs."""
  131. if d > 1:
  132. k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size
  133. if p is None:
  134. p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
  135. return p
  136. class Conv(nn.Module):
  137. """Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation)."""
  138. default_act = nn.SiLU() # default activation
  139. def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
  140. """Initialize Conv layer with given arguments including activation."""
  141. super().__init__()
  142. self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
  143. self.bn = nn.BatchNorm2d(c2)
  144. self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
  145. def forward(self, x):
  146. """Apply convolution, batch normalization and activation to input tensor."""
  147. return self.act(self.bn(self.conv(x)))
  148. def forward_fuse(self, x):
  149. """Perform transposed convolution of 2D data."""
  150. return self.act(self.conv(x))
  151. class C3(nn.Module):
  152. """CSP Bottleneck with 3 convolutions."""
  153. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
  154. """Initialize the CSP Bottleneck with given channels, number, shortcut, groups, and expansion values."""
  155. super().__init__()
  156. c_ = int(c2 * e) # hidden channels
  157. self.cv1 = Conv(c1, c_, 1, 1)
  158. self.cv2 = Conv(c1, c_, 1, 1)
  159. self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2)
  160. self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, k=((1, 1), (3, 3)), e=1.0) for _ in range(n)))
  161. def forward(self, x):
  162. """Forward pass through the CSP bottleneck with 2 convolutions."""
  163. return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
  164. class C3k(C3):
  165. """C3k is a CSP bottleneck module with customizable kernel sizes for feature extraction in neural networks."""
  166. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, k=3):
  167. """Initializes the C3k module with specified channels, number of layers, and configurations."""
  168. super().__init__(c1, c2, n, shortcut, g, e)
  169. c_ = int(c2 * e) # hidden channels
  170. # self.m = nn.Sequential(*(RepBottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
  171. self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
  172. class C3kBFAM(C3):
  173. """C3k is a CSP bottleneck module with customizable kernel sizes for feature extraction in neural networks."""
  174. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, k=3):
  175. """Initializes the C3k module with specified channels, number of layers, and configurations."""
  176. super().__init__(c1, c2, n, shortcut, g, e)
  177. c_ = int(c2 * e) # hidden channels
  178. # self.m = nn.Sequential(*(RepBottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
  179. self.m = nn.Sequential(*(Bottleneck_BFAM(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
  180. class C3k2_BFAM_1(C2f):
  181. """Faster Implementation of CSP Bottleneck with 2 convolutions."""
  182. def __init__(self, c1, c2, n=1, c3k=False, e=0.5, g=1, shortcut=True):
  183. """Initializes the C3k2 module, a faster CSP Bottleneck with 2 convolutions and optional C3k blocks."""
  184. super().__init__(c1, c2, n, shortcut, g, e)
  185. self.m = nn.ModuleList(
  186. C3k(self.c, self.c, 2, shortcut, g) if c3k else Bottleneck_BFAM(self.c, self.c, shortcut, g)for _ in range(n)
  187. )
  188. # 解析利用Bottleneck_iAFF替换Bottneck
  189. class C3k2_BFAM_2(C2f):
  190. """Faster Implementation of CSP Bottleneck with 2 convolutions."""
  191. def __init__(self, c1, c2, n=1, c3k=False, e=0.5, g=1, shortcut=True):
  192. """Initializes the C3k2 module, a faster CSP Bottleneck with 2 convolutions and optional C3k blocks."""
  193. super().__init__(c1, c2, n, shortcut, g, e)
  194. self.m = nn.ModuleList(
  195. C3kBFAM(self.c, self.c, 2, shortcut, g) if c3k else Bottleneck(self.c, self.c, shortcut, g)for _ in range(n)
  196. )
  197. # 解析利用Bottleneck_iAFF替换Bottneck
  198. if __name__ == '__main__':
  199. from thop import profile, clever_format
  200. inp1= torch.rand(1,48,256,256)
  201. model = C3k2_BFAM_2(48,48)
  202. out = model(inp1)
  203. print(out.shape)


四、添加教程

4.1 修改一

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


4.2 修改二

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


4.3 修改三

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


4.4 修改四

找到文件到如下文件'ultralytics/nn/tasks.py',在其中的parse_model方法中添加即可。


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

如果不会添加可联系作者入群观看视频教程。


五、正式训练


5.1 yaml文件1

YOLO11-C3k2-BFAM-1 summary: 415 layers, 2,761,762 parameters, 2,761,746 gradients, 7.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_BFAM_1, [256, False, 0.25]]
  18. - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8
  19. - [-1, 2, C3k2_BFAM_1, [512, False, 0.25]]
  20. - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16
  21. - [-1, 2, C3k2_BFAM_1, [512, True]]
  22. - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32
  23. - [-1, 2, C3k2_BFAM_1, [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_BFAM_1, [512, False]] # 13
  31. - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
  32. - [[-1, 4], 1, Concat, [1]] # cat backbone P3
  33. - [-1, 2, C3k2_BFAM_1, [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_BFAM_1, [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_BFAM_1, [1024, True]] # 22 (P5/32-large)
  40. - [[16, 19, 22], 1, Detect, [nc]] # Detect(P3, P4, P5)


5.2 yaml文件2

训练信息:YOLO11-C3k2-BFAM-2 summary: 434 layers, 2,887,970 parameters, 2,887,954 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_BFAM_2, [256, False, 0.25]]
  18. - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8
  19. - [-1, 2, C3k2_BFAM_2, [512, False, 0.25]]
  20. - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16
  21. - [-1, 2, C3k2_BFAM_2, [512, True]]
  22. - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32
  23. - [-1, 2, C3k2_BFAM_2, [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_BFAM_2, [512, False]] # 13
  31. - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
  32. - [[-1, 4], 1, Concat, [1]] # cat backbone P3
  33. - [-1, 2, C3k2_BFAM_2, [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_BFAM_2, [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_BFAM_2, [1024, True]] # 22 (P5/32-large)
  40. - [[16, 19, 22], 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('替换你的模型配置文件yaml文件地址')
  6. # 如何切换模型版本, 上面的ymal文件可以改为 yolov11s.yaml就是使用的v11s,
  7. # 类似某个改进的yaml文件名称为yolov11-XXX.yaml那么如果想使用其它版本就把上面的名称改为yolov11l-XXX.yaml即可(改的是上面YOLO中间的名字不是配置文件的)!
  8. # model.load('yolo11n.pt') # 是否加载预训练权重,科研不建议大家加载否则很难提升精度
  9. model.train(data=r"替换你的数据集配置文件地址",
  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=False, # 如果出现训练损失为Nan可以关闭amp
  22. project='runs/train',
  23. name='exp',
  24. )


5.4 训练过程截图


五、本文总结

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