学习资源站

YOLOv11改进-独家创新篇-结合iRMB和EMA形成全新的iEMA机制(全网独家创新,教你如何二次创新)

一、本文介绍

本文给大家带来的最新改进机制是 二次创新 的机制,二次创新是我们发表论文中关键的一环,为什么这么说,从去年的三月份开始对于图像领域的论文发表其实是变难的了,在那之前大家可能搭搭积木的情况下就可以简单的发表一篇论文,但是从去年开始单纯的搭积木其实发表论文变得越来越难,所以这个时候就需要二次创新,以此来迷惑审稿人,彰显大家的工作量,所以二次创新是非常重要的一点,因为二次创新出来的模块其实基本上就可以算作一个全新的模块了, 本文内容经过YOLOv8专栏很多读者反应效果很好, 同时本文含如何二次创新的思路。

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



二、如何进行二次创新

这里给大家介绍以下如何进行二次创新。

我的视频中说过二次创新主要分为两种,本文介绍的是另外一种。

组合为: 一种全新的结构 + 其他模块(可以是 卷积 ,也可以是注意力机制,也可以是重参数化模块)

iRMB主要提出了一种倒置残差的结构,然后其中涉及到一种 Transformer 注意力机制 ,因为创新注意力机制是十分困难的事情大家都是炼丹师所以这肯定不现实,但是借鉴其中的结构还是一个比较容易的事情,所以我们借鉴了iRMB其中倒置残差结构结合一种即插即用的EMA注意力机制 (也可以替换其它的注意力机制) ,形成一个新的模块iEMA也是一种创新对于写论文来说,总比你单用iRMB或者EMA要好对吧?最起码工作量的方面我们是堆叠上去了。


三、iEMA的核心代码

使用方式看章节四!

  1. import math
  2. import torch
  3. import torch.nn as nn
  4. from functools import partial
  5. from einops import rearrange
  6. from timm.models._efficientnet_blocks import SqueezeExcite
  7. from timm.models.layers import DropPath
  8. __all__ = ['iEMA', 'C2PSAiEMA']
  9. class EMA(nn.Module):
  10. def __init__(self, channels, factor=32):
  11. super(EMA, self).__init__()
  12. self.groups = factor
  13. assert channels // self.groups > 0
  14. self.softmax = nn.Softmax(-1)
  15. self.agp = nn.AdaptiveAvgPool2d((1, 1))
  16. self.pool_h = nn.AdaptiveAvgPool2d((None, 1))
  17. self.pool_w = nn.AdaptiveAvgPool2d((1, None))
  18. self.gn = nn.GroupNorm(channels // self.groups, channels // self.groups)
  19. self.conv1x1 = nn.Conv2d(channels // self.groups, channels // self.groups, kernel_size=1, stride=1, padding=0)
  20. self.conv3x3 = nn.Conv2d(channels // self.groups, channels // self.groups, kernel_size=3, stride=1, padding=1)
  21. def forward(self, x):
  22. b, c, h, w = x.size()
  23. group_x = x.reshape(b * self.groups, -1, h, w) # b*g,c//g,h,w
  24. x_h = self.pool_h(group_x)
  25. x_w = self.pool_w(group_x).permute(0, 1, 3, 2)
  26. hw = self.conv1x1(torch.cat([x_h, x_w], dim=2))
  27. x_h, x_w = torch.split(hw, [h, w], dim=2)
  28. x1 = self.gn(group_x * x_h.sigmoid() * x_w.permute(0, 1, 3, 2).sigmoid())
  29. x2 = self.conv3x3(group_x)
  30. x11 = self.softmax(self.agp(x1).reshape(b * self.groups, -1, 1).permute(0, 2, 1))
  31. x12 = x2.reshape(b * self.groups, c // self.groups, -1) # b*g, c//g, hw
  32. x21 = self.softmax(self.agp(x2).reshape(b * self.groups, -1, 1).permute(0, 2, 1))
  33. x22 = x1.reshape(b * self.groups, c // self.groups, -1) # b*g, c//g, hw
  34. weights = (torch.matmul(x11, x12) + torch.matmul(x21, x22)).reshape(b * self.groups, 1, h, w)
  35. return (group_x * weights.sigmoid()).reshape(b, c, h, w)
  36. inplace = True
  37. class LayerNorm2d(nn.Module):
  38. def __init__(self, normalized_shape, eps=1e-6, elementwise_affine=True):
  39. super().__init__()
  40. self.norm = nn.LayerNorm(normalized_shape, eps, elementwise_affine)
  41. def forward(self, x):
  42. x = rearrange(x, 'b c h w -> b h w c').contiguous()
  43. x = self.norm(x)
  44. x = rearrange(x, 'b h w c -> b c h w').contiguous()
  45. return x
  46. def get_norm(norm_layer='in_1d'):
  47. eps = 1e-6
  48. norm_dict = {
  49. 'none': nn.Identity,
  50. 'in_1d': partial(nn.InstanceNorm1d, eps=eps),
  51. 'in_2d': partial(nn.InstanceNorm2d, eps=eps),
  52. 'in_3d': partial(nn.InstanceNorm3d, eps=eps),
  53. 'bn_1d': partial(nn.BatchNorm1d, eps=eps),
  54. 'bn_2d': partial(nn.BatchNorm2d, eps=eps),
  55. # 'bn_2d': partial(nn.SyncBatchNorm, eps=eps),
  56. 'bn_3d': partial(nn.BatchNorm3d, eps=eps),
  57. 'gn': partial(nn.GroupNorm, eps=eps),
  58. 'ln_1d': partial(nn.LayerNorm, eps=eps),
  59. 'ln_2d': partial(LayerNorm2d, eps=eps),
  60. }
  61. return norm_dict[norm_layer]
  62. def get_act(act_layer='relu'):
  63. act_dict = {
  64. 'none': nn.Identity,
  65. 'relu': nn.ReLU,
  66. 'relu6': nn.ReLU6,
  67. 'silu': nn.SiLU
  68. }
  69. return act_dict[act_layer]
  70. class ConvNormAct(nn.Module):
  71. def __init__(self, dim_in, dim_out, kernel_size, stride=1, dilation=1, groups=1, bias=False,
  72. skip=False, norm_layer='bn_2d', act_layer='relu', inplace=True, drop_path_rate=0.):
  73. super(ConvNormAct, self).__init__()
  74. self.has_skip = skip and dim_in == dim_out
  75. padding = math.ceil((kernel_size - stride) / 2)
  76. self.conv = nn.Conv2d(dim_in, dim_out, kernel_size, stride, padding, dilation, groups, bias)
  77. self.norm = get_norm(norm_layer)(dim_out)
  78. self.act = get_act(act_layer)(inplace=inplace)
  79. self.drop_path = DropPath(drop_path_rate) if drop_path_rate else nn.Identity()
  80. def forward(self, x):
  81. shortcut = x
  82. x = self.conv(x)
  83. x = self.norm(x)
  84. x = self.act(x)
  85. if self.has_skip:
  86. x = self.drop_path(x) + shortcut
  87. return x
  88. class iEMA(nn.Module):
  89. def __init__(self, dim_in, norm_in=True, has_skip=True, exp_ratio=1.0, norm_layer='bn_2d',
  90. act_layer='relu', v_proj=True, dw_ks=3, stride=1, dilation=1, se_ratio=0.0,
  91. attn_s=True, qkv_bias=False, drop=0., drop_path=0.):
  92. super().__init__()
  93. dim_out = dim_in
  94. self.norm = get_norm(norm_layer)(dim_in) if norm_in else nn.Identity()
  95. dim_mid = int(dim_in * exp_ratio)
  96. self.has_skip = (dim_in == dim_out and stride == 1) and has_skip
  97. self.attn_s = attn_s
  98. if self.attn_s:
  99. self.ema = EMA(dim_in)
  100. else:
  101. if v_proj:
  102. self.v = ConvNormAct(dim_in, dim_mid, kernel_size=1, bias=qkv_bias, norm_layer='none',
  103. act_layer=act_layer, inplace=inplace)
  104. else:
  105. self.v = nn.Identity()
  106. self.conv_local = ConvNormAct(dim_mid, dim_mid, kernel_size=dw_ks, stride=stride, dilation=dilation,
  107. groups=dim_mid, norm_layer='bn_2d', act_layer='silu', inplace=inplace)
  108. self.se = SqueezeExcite(dim_mid, rd_ratio=se_ratio, act_layer=get_act(act_layer)) if se_ratio > 0.0 else nn.Identity()
  109. self.proj_drop = nn.Dropout(drop)
  110. self.proj = ConvNormAct(dim_mid, dim_out, kernel_size=1, norm_layer='none', act_layer='none', inplace=inplace)
  111. self.drop_path = DropPath(drop_path) if drop_path else nn.Identity()
  112. def forward(self, x):
  113. shortcut = x
  114. x = self.norm(x)
  115. if self.attn_s:
  116. x = self.ema(x)
  117. else:
  118. x = self.v(x)
  119. x = x + self.se(self.conv_local(x)) if self.has_skip else self.se(self.conv_local(x))
  120. x = self.proj_drop(x)
  121. x = self.proj(x)
  122. x = (shortcut + self.drop_path(x)) if self.has_skip else x
  123. return x
  124. def autopad(k, p=None, d=1): # kernel, padding, dilation
  125. """Pad to 'same' shape outputs."""
  126. if d > 1:
  127. k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size
  128. if p is None:
  129. p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
  130. return p
  131. class Conv(nn.Module):
  132. """Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation)."""
  133. default_act = nn.SiLU() # default activation
  134. def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
  135. """Initialize Conv layer with given arguments including activation."""
  136. super().__init__()
  137. self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
  138. self.bn = nn.BatchNorm2d(c2)
  139. self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
  140. def forward(self, x):
  141. """Apply convolution, batch normalization and activation to input tensor."""
  142. return self.act(self.bn(self.conv(x)))
  143. def forward_fuse(self, x):
  144. """Perform transposed convolution of 2D data."""
  145. return self.act(self.conv(x))
  146. class PSABlock(nn.Module):
  147. """
  148. PSABlock class implementing a Position-Sensitive Attention block for neural networks.
  149. This class encapsulates the functionality for applying multi-head attention and feed-forward neural network layers
  150. with optional shortcut connections.
  151. Attributes:
  152. attn (Attention): Multi-head attention module.
  153. ffn (nn.Sequential): Feed-forward neural network module.
  154. add (bool): Flag indicating whether to add shortcut connections.
  155. Methods:
  156. forward: Performs a forward pass through the PSABlock, applying attention and feed-forward layers.
  157. Examples:
  158. Create a PSABlock and perform a forward pass
  159. """
  160. def __init__(self, c, attn_ratio=0.5, num_heads=4, shortcut=True) -> None:
  161. """Initializes the PSABlock with attention and feed-forward layers for enhanced feature extraction."""
  162. super().__init__()
  163. self.attn = iEMA(c)
  164. self.ffn = nn.Sequential(Conv(c, c * 2, 1), Conv(c * 2, c, 1, act=False))
  165. self.add = shortcut
  166. def forward(self, x):
  167. """Executes a forward pass through PSABlock, applying attention and feed-forward layers to the input tensor."""
  168. x = x + self.attn(x) if self.add else self.attn(x)
  169. x = x + self.ffn(x) if self.add else self.ffn(x)
  170. return x
  171. class C2PSAiEMA(nn.Module):
  172. """
  173. C2PSA module with attention mechanism for enhanced feature extraction and processing.
  174. This module implements a convolutional block with attention mechanisms to enhance feature extraction and processing
  175. capabilities. It includes a series of PSABlock modules for self-attention and feed-forward operations.
  176. Attributes:
  177. c (int): Number of hidden channels.
  178. cv1 (Conv): 1x1 convolution layer to reduce the number of input channels to 2*c.
  179. cv2 (Conv): 1x1 convolution layer to reduce the number of output channels to c.
  180. m (nn.Sequential): Sequential container of PSABlock modules for attention and feed-forward operations.
  181. Methods:
  182. forward: Performs a forward pass through the C2PSA module, applying attention and feed-forward operations.
  183. Notes:
  184. This module essentially is the same as PSA module, but refactored to allow stacking more PSABlock modules.
  185. Examples:
  186. """
  187. def __init__(self, c1, c2, n=1, e=0.5):
  188. """Initializes the C2PSA module with specified input/output channels, number of layers, and expansion ratio."""
  189. super().__init__()
  190. assert c1 == c2
  191. self.c = int(c1 * e)
  192. self.cv1 = Conv(c1, 2 * self.c, 1, 1)
  193. self.cv2 = Conv(2 * self.c, c1, 1)
  194. self.m = nn.Sequential(*(PSABlock(self.c, attn_ratio=0.5, num_heads=self.c // 64) for _ in range(n)))
  195. def forward(self, x):
  196. """Processes the input tensor 'x' through a series of PSA blocks and returns the transformed tensor."""
  197. a, b = self.cv1(x).split((self.c, self.c), dim=1)
  198. b = self.m(b)
  199. return self.cv2(torch.cat((a, b), 1))
  200. if __name__ == "__main__":
  201. # Generating Sample image
  202. image_size = (1, 64, 640, 640)
  203. image = torch.rand(*image_size)
  204. # Model
  205. model = C2PSAiEMA(64, 64)
  206. out = model(image)
  207. 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-iEMA summary: 330 layers, 2,556,931 parameters, 2,556,915 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, C2PSAiEMA, [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-iEMA summary: 388 layers, 2,682,771 parameters, 2,682,755 gradients, 6.7 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, iEMA, []] # 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, iEMA, []] # 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, iEMA, []] # 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分,后期我会根据各种最新的前沿顶会进行论文复现,也会对一些老的改进机制进行补充,如果大家觉得本文帮助到你了,订阅本专栏,关注后续更多的更新~