学习资源站

YOLOv11改进-Conv_卷积篇-全维度动态卷积ODConv卷积二次创新C3k2助力YOLOv11有效涨点

一、本文介绍

这篇文章给大家带来的是 ODConv (Omni-Dimensional Dynamic Convolution)中文名字 全维度动态卷积 ,该卷积可以 即插即用 ,可以直接替换网络结构中的任何一个卷积模块 在本文的末尾提供可以直接替换卷积模块的ODConv,添加ODConv模块的C2f和Bottleneck(配合教程将代码复制粘贴到你自己的代码中即可运行)给大家 ,该卷积模块主要具有更小的计算量和更高的精度下面的图片是精度的对比( 本文提供了两种代码一种是二次创新C3k2,另外一种是利用ODConv替换传统的Conv进行下采样)。

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

适用场景: 轻量化、所有检测目标时均可使用进行有效涨点



二、基本原理介绍

论文地址: 论文地址点击即可跳转阅读

代码地址: 文末提供复制粘贴的代码块


大家估计只是冲着代码来看,估计很少想要看其原理的, 所以我们这里只做略微的介绍和简单的讲解 最起码知道其基本的原理。


2.1ODConv基本原理介绍

ODConv 创新之处 在于它 采用了一种多维注意力机制 。这种机制通过并行策略来学习 卷积核 在核空间所有四个维度(即空间大小、输入通道数和每个卷积层的输出通道数)上的互补注意力。这种方法适用于任何卷积层,增强了网络的灵活性和 适应性 (这个四个维度的卷积可以在代码中清晰的体现出来)

ODConv卷积主要的改进机制就是在上面的地方体现出来的,这个变量名aggregate_weight就是文中提到的四个维度,其中的通道数[16,16,3,3]的含义为其具有16个维度,每个卷积核有16个通道,卷积核的大小是3x3,所以这处就是体现其具体改动的地方,这处的代码可以在我文末提供的代码中可以找到如果想要了解可以自己debug看一下。

那么大家可能想问了,它是如何减少计算量的呢?因为他具有16个通道数所以他计算是通过并行的方式,因为这一机制导致它的计算量也变小了( 是不是感觉一举两得 )。

总结: 其实ODConv就是提出了这么一种具有多维度的卷积核所以其减少了计算量同时提高了检测精度。

上面的总结是我个人的理解,下面的是文章中的总结->


2.2论文总结

Omni-Dimensional Dynamic Convolution(ODConv) 的基本原理是对传统的 卷积神经网络 (CNN)中卷积层的设计进行创新。在传统的CNN中,每个卷积层通常使用固定的、静态的卷积核来提取特征。相比之下,ODConv引入了一种动态的、多维的注意力机制,对卷积核的设计进行了全面的改进。下面详细介绍其原理:

  1. 多维动态注意力机制 :ODConv的核心创新是其多维动态注意力机制。传统的 动态卷积 通常只在卷积核数量这一个维度上实现动态性,即通过对多个卷积核进行加权组合以适应不同的输入特征。ODConv则进一步扩展了这一概念,它不仅在卷积核数量上动态调整,还涉及到卷积核的其他三个维度:空间大小、输入通道数、输出通道数。这意味着ODConv能够更精细地适应输入数据的特征,从而提高特征提取的效果。

  2. 并行策略 :ODConv采用并行策略来同时学习不同维度上的注意力。这种策略允许网络在处理每个维度的特征时更加高效,同时确保各维度之间的互补性和协同作用。

下面的图片左边的是传统的动态卷积右边是文章中提出的ODConv。

ODConv的独特之处 与DyConv和CondConv不同,ODConv采用了一种新颖的多维注意力机制。这种机制不是仅针对每个卷积核计算一个单一的注意力标量,而是沿着卷积核空间的所有四个维度计算四种类型的注意力:αsi​, αci​, αfi​, 和αwi​。这样的设计允许ODConv在空间大小、输入通道数、过滤器数量(输出通道数)和卷积核数量这四个维度上进行细粒度的动态调整。 这一处在代码中也有清晰的体现如下图->

并行计算 :ODConv能够以并行的方式计算这四种类型的注意力,这提高了其效率,并允许它更全面地捕捉和利用输入数据的多维特征。

上面提到了每个通道分别计算其注意力机制,那么其是如何生效的呢?并且提高 模型 精度的呢?

下面图片中分别具有a,b,c,d代表四个不同通道的注意力机制生效方式。

如何在其四种不同类型的注意力机制中逐步应用到卷积核上的过程的呢,下面是对这一过程的解释:

  1. 位置维度的逐点乘法(Location-wise Multiplication) :如上图(a)所示,这一步涉及到沿着卷积核的空间维度(即卷积核的高度和宽度)进行的乘法操作。在这里,ODConv计算的位置维度注意力(αsi​)被应用于卷积核的每个空间位置上,这允许网络动态调整卷积核在处理不同空间位置的信息时的重要性。

  2. 通道维度的逐通道乘法(Channel-wise Multiplication) :如上图(b)所示,这一步是沿着输入通道维度进行的乘法操作。在这个阶段,通道维度的注意力(αci​)被应用于卷积核的每个输入通道上,使得网络能够针对不同的输入特征通道动态调整其处理方式。

  3. 输出通道维度的逐滤波器乘法(Filter-wise Multiplication) :如上图(c)所示,这一步是沿着输出通道维度进行的乘法操作。在这里,输出通道维度的注意力(αfi​)影响卷积核的每个输出滤波器,从而使网络能够根据不同输出特征的重要性进行调整。

  4. 卷积核维度的逐核乘法(Kernel-wise Multiplication) :如上图(d)所示,这一步是沿着卷积核维度进行的乘法操作。卷积核维度的注意力(αwi​)在这一阶段被应用,它允许网络动态调整不同卷积核的重要性。

通过这种分步骤的乘法操作,ODConv能够在卷积过程中综合考虑空间位置、输入通道、输出通道和卷积核数量等多个维度的信息,从而实现对卷积核的全方位动态调整。这种细致的调整方式使得ODConv能够更精准地提取特征,增强网络的学习和表达能力。论文的方法部分对这些操作的具体数学表达和实现细节 (大家有兴趣可以看看论文,论文在开头我提供了地址)。


三、ODConv代码

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

  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. import torch.autograd
  5. __all__ = ['C3k2_ODConv', 'ODConv2d']
  6. def autopad(k, p=None, d=1): # kernel, padding, dilation
  7. """Pad to 'same' shape outputs."""
  8. if d > 1:
  9. k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size
  10. if p is None:
  11. p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
  12. return p
  13. class Conv(nn.Module):
  14. """Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation)."""
  15. default_act = nn.SiLU() # default activation
  16. def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
  17. """Initialize Conv layer with given arguments including activation."""
  18. super().__init__()
  19. self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
  20. self.bn = nn.BatchNorm2d(c2)
  21. self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
  22. def forward(self, x):
  23. """Apply convolution, batch normalization and activation to input tensor."""
  24. return self.act(self.bn(self.conv(x)))
  25. def forward_fuse(self, x):
  26. """Perform transposed convolution of 2D data."""
  27. return self.act(self.conv(x))
  28. class Attention(nn.Module):
  29. def __init__(self, in_planes, out_planes, kernel_size=3, groups=1, reduction=0.0625, kernel_num=4, min_channel=16):
  30. super(Attention, self).__init__()
  31. attention_channel = max(int(in_planes * reduction), min_channel)
  32. self.kernel_size = kernel_size
  33. self.kernel_num = kernel_num
  34. self.temperature = 1.0
  35. self.avgpool = nn.AdaptiveAvgPool2d(1)
  36. self.fc = nn.Conv2d(in_planes, attention_channel, 1, bias=False)
  37. self.bn = nn.BatchNorm2d(attention_channel)
  38. self.relu = nn.ReLU(inplace=True)
  39. self.channel_fc = nn.Conv2d(attention_channel, in_planes, 1, bias=True)
  40. self.func_channel = self.get_channel_attention
  41. if in_planes == groups and in_planes == out_planes: # depth-wise convolution
  42. self.func_filter = self.skip
  43. else:
  44. self.filter_fc = nn.Conv2d(attention_channel, out_planes, 1, bias=True)
  45. self.func_filter = self.get_filter_attention
  46. if kernel_size == 1: # point-wise convolution
  47. self.func_spatial = self.skip
  48. else:
  49. self.spatial_fc = nn.Conv2d(attention_channel, kernel_size * kernel_size, 1, bias=True)
  50. self.func_spatial = self.get_spatial_attention
  51. if kernel_num == 1:
  52. self.func_kernel = self.skip
  53. else:
  54. self.kernel_fc = nn.Conv2d(attention_channel, kernel_num, 1, bias=True)
  55. self.func_kernel = self.get_kernel_attention
  56. self._initialize_weights()
  57. def _initialize_weights(self):
  58. for m in self.modules():
  59. if isinstance(m, nn.Conv2d):
  60. nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
  61. if m.bias is not None:
  62. nn.init.constant_(m.bias, 0)
  63. if isinstance(m, nn.BatchNorm2d):
  64. nn.init.constant_(m.weight, 1)
  65. nn.init.constant_(m.bias, 0)
  66. def update_temperature(self, temperature):
  67. self.temperature = temperature
  68. @staticmethod
  69. def skip(_):
  70. return 1.0
  71. def get_channel_attention(self, x):
  72. channel_attention = torch.sigmoid(self.channel_fc(x).view(x.size(0), -1, 1, 1) / self.temperature)
  73. return channel_attention
  74. def get_filter_attention(self, x):
  75. filter_attention = torch.sigmoid(self.filter_fc(x).view(x.size(0), -1, 1, 1) / self.temperature)
  76. return filter_attention
  77. def get_spatial_attention(self, x):
  78. spatial_attention = self.spatial_fc(x).view(x.size(0), 1, 1, 1, self.kernel_size, self.kernel_size)
  79. spatial_attention = torch.sigmoid(spatial_attention / self.temperature)
  80. return spatial_attention
  81. def get_kernel_attention(self, x):
  82. kernel_attention = self.kernel_fc(x).view(x.size(0), -1, 1, 1, 1, 1)
  83. kernel_attention = F.softmax(kernel_attention / self.temperature, dim=1)
  84. return kernel_attention
  85. def forward(self, x):
  86. x = self.avgpool(x)
  87. x = self.fc(x)
  88. # x = self.bn(x) # 在外面我提供了一个bn这里会报错
  89. x = self.relu(x)
  90. return self.func_channel(x), self.func_filter(x), self.func_spatial(x), self.func_kernel(x)
  91. class ODConv2d(nn.Module):
  92. def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=1, dilation=1, groups=1,
  93. reduction=0.0625, kernel_num=4):
  94. super(ODConv2d, self).__init__()
  95. in_planes = in_planes
  96. self.in_planes = in_planes
  97. self.out_planes = out_planes
  98. self.kernel_size = kernel_size
  99. self.stride = stride
  100. self.padding = padding
  101. self.dilation = dilation
  102. self.groups = groups
  103. self.kernel_num = kernel_num
  104. self.attention = Attention(in_planes, out_planes, kernel_size, groups=groups,
  105. reduction=reduction, kernel_num=kernel_num)
  106. self.weight = nn.Parameter(torch.randn(kernel_num, out_planes, in_planes // groups, kernel_size, kernel_size),
  107. requires_grad=True)
  108. self._initialize_weights()
  109. if self.kernel_size == 1 and self.kernel_num == 1:
  110. self._forward_impl = self._forward_impl_pw1x
  111. else:
  112. self._forward_impl = self._forward_impl_common
  113. def _initialize_weights(self):
  114. for i in range(self.kernel_num):
  115. nn.init.kaiming_normal_(self.weight[i], mode='fan_out', nonlinearity='relu')
  116. def update_temperature(self, temperature):
  117. self.attention.update_temperature(temperature)
  118. def _forward_impl_common(self, x):
  119. # Multiplying channel attention (or filter attention) to weights and feature maps are equivalent,
  120. # while we observe that when using the latter method the models will run faster with less gpu memory cost.
  121. channel_attention, filter_attention, spatial_attention, kernel_attention = self.attention(x)
  122. batch_size, in_planes, height, width = x.size()
  123. x = x * channel_attention
  124. x = x.reshape(1, -1, height, width)
  125. aggregate_weight = spatial_attention * kernel_attention * self.weight.unsqueeze(dim=0)
  126. aggregate_weight = torch.sum(aggregate_weight, dim=1).view(
  127. [-1, self.in_planes // self.groups, self.kernel_size, self.kernel_size])
  128. output = F.conv2d(x, weight=aggregate_weight, bias=None, stride=self.stride, padding=self.padding,
  129. dilation=self.dilation, groups=self.groups * batch_size)
  130. output = output.view(batch_size, self.out_planes, output.size(-2), output.size(-1))
  131. output = output * filter_attention
  132. return output
  133. def _forward_impl_pw1x(self, x):
  134. channel_attention, filter_attention, spatial_attention, kernel_attention = self.attention(x)
  135. x = x * channel_attention
  136. output = F.conv2d(x, weight=self.weight.squeeze(dim=0), bias=None, stride=self.stride, padding=self.padding,
  137. dilation=self.dilation, groups=self.groups)
  138. output = output * filter_attention
  139. return output
  140. def forward(self, x):
  141. return self._forward_impl(x)
  142. def autopad(k, p=None, d=1): # kernel, padding, dilation
  143. """Pad to 'same' shape outputs."""
  144. if d > 1:
  145. k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size
  146. if p is None:
  147. p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
  148. return p
  149. class Conv(nn.Module):
  150. """Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation)."""
  151. default_act = nn.SiLU() # default activation
  152. def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
  153. """Initialize Conv layer with given arguments including activation."""
  154. super().__init__()
  155. self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
  156. self.bn = nn.BatchNorm2d(c2)
  157. self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
  158. def forward(self, x):
  159. """Apply convolution, batch normalization and activation to input tensor."""
  160. return self.act(self.bn(self.conv(x)))
  161. def forward_fuse(self, x):
  162. """Perform transposed convolution of 2D data."""
  163. return self.act(self.conv(x))
  164. class Bottleneck(nn.Module):
  165. """Standard bottleneck."""
  166. def __init__(self, c1, c2, shortcut=True, g=1, k=(3, 3), e=0.5):
  167. """Initializes a bottleneck module with given input/output channels, shortcut option, group, kernels, and
  168. expansion.
  169. """
  170. super().__init__()
  171. c_ = int(c2 * e) # hidden channels
  172. self.cv1 = Conv(c1, c_, k[0], 1)
  173. self.cv2 = ODConv2d(c_, c2, 3, 1)
  174. self.add = shortcut and c1 == c2
  175. def forward(self, x):
  176. """'forward()' applies the YOLO FPN to input data."""
  177. return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
  178. class C2f(nn.Module):
  179. """Faster Implementation of CSP Bottleneck with 2 convolutions."""
  180. def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5):
  181. """Initializes a CSP bottleneck with 2 convolutions and n Bottleneck blocks for faster processing."""
  182. super().__init__()
  183. self.c = int(c2 * e) # hidden channels
  184. self.cv1 = Conv(c1, 2 * self.c, 1, 1)
  185. self.cv2 = Conv((2 + n) * self.c, c2, 1) # optional act=FReLU(c2)
  186. self.m = nn.ModuleList(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n))
  187. def forward(self, x):
  188. """Forward pass through C2f layer."""
  189. y = list(self.cv1(x).chunk(2, 1))
  190. y.extend(m(y[-1]) for m in self.m)
  191. return self.cv2(torch.cat(y, 1))
  192. def forward_split(self, x):
  193. """Forward pass using split() instead of chunk()."""
  194. y = list(self.cv1(x).split((self.c, self.c), 1))
  195. y.extend(m(y[-1]) for m in self.m)
  196. return self.cv2(torch.cat(y, 1))
  197. class C3(nn.Module):
  198. """CSP Bottleneck with 3 convolutions."""
  199. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
  200. """Initialize the CSP Bottleneck with given channels, number, shortcut, groups, and expansion values."""
  201. super().__init__()
  202. c_ = int(c2 * e) # hidden channels
  203. self.cv1 = Conv(c1, c_, 1, 1)
  204. self.cv2 = Conv(c1, c_, 1, 1)
  205. self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2)
  206. self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, k=((1, 1), (3, 3)), e=1.0) for _ in range(n)))
  207. def forward(self, x):
  208. """Forward pass through the CSP bottleneck with 2 convolutions."""
  209. return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
  210. class C3k(C3):
  211. """C3k is a CSP bottleneck module with customizable kernel sizes for feature extraction in neural networks."""
  212. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, k=3):
  213. """Initializes the C3k module with specified channels, number of layers, and configurations."""
  214. super().__init__(c1, c2, n, shortcut, g, e)
  215. c_ = int(c2 * e) # hidden channels
  216. # self.m = nn.Sequential(*(RepBottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
  217. self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
  218. class C3k2_ODConv(C2f):
  219. """Faster Implementation of CSP Bottleneck with 2 convolutions."""
  220. def __init__(self, c1, c2, n=1, c3k=False, e=0.5, g=1, shortcut=True):
  221. """Initializes the C3k2 module, a faster CSP Bottleneck with 2 convolutions and optional C3k blocks."""
  222. super().__init__(c1, c2, n, shortcut, g, e)
  223. self.m = nn.ModuleList(
  224. C3k(self.c, self.c, 2, shortcut, g) if c3k else Bottleneck(self.c, self.c, shortcut, g) for _ in range(n)
  225. )
  226. if __name__ == "__main__":
  227. # Generating Sample image
  228. image_size = (1, 64, 240, 240)
  229. image = torch.rand(*image_size)
  230. # Model
  231. mobilenet_v1 = C3k2_ODConv(64, 64)
  232. out = mobilenet_v1(image)
  233. print(out.size())


四、在模型中调用ODConv模块

4.1 修改一

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


4.2 修改二

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


4.3 修改三

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


4.4 修改四

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


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


五、正式训练


5.1 yaml文件1(C3K2-ODConv)

训练信息:YOLO11-C3k2-ODConv summary: 397 layers, 3,258,770 parameters, 3,258,754 gradients, 6.0 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_ODConv, [256, False, 0.25]]
  18. - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8
  19. - [-1, 2, C3k2_ODConv, [512, False, 0.25]]
  20. - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16
  21. - [-1, 2, C3k2_ODConv, [512, True]]
  22. - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32
  23. - [-1, 2, C3k2_ODConv, [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_ODConv, [512, False]] # 13
  31. - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
  32. - [[-1, 4], 1, Concat, [1]] # cat backbone P3
  33. - [-1, 2, C3k2_ODConv, [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_ODConv, [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_ODConv, [1024, True]] # 22 (P5/32-large)
  40. - [[16, 19, 22], 1, Detect, [nc]] # Detect(P3, P4, P5)

5.2 yaml文件2(ODConv2d)

此版本训练信息:YOLO11-ODConv summary: 361 layers, 4,628,217 parameters, 4,628,201 gradients, 4.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, ODConv2d, [128, 3, 2]] # 1-P2/4
  17. - [-1, 2, C3k2, [256, False, 0.25]]
  18. - [-1, 1, ODConv2d, [256, 3, 2]] # 3-P3/8
  19. - [-1, 2, C3k2, [512, False, 0.25]]
  20. - [-1, 1, ODConv2d, [512, 3, 2]] # 5-P4/16
  21. - [-1, 2, C3k2, [512, True]]
  22. - [-1, 1, ODConv2d, [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, ODConv2d, [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, ODConv2d, [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.3 训练代码

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

  1. import warnings
  2. warnings.filterwarnings('ignore')
  3. from ultralytics import YOLO
  4. if __name__ == '__main__':
  5. model = YOLO('yolov8-MLLA.yaml')
  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=False, # 如果出现训练损失为Nan可以关闭amp
  22. project='runs/train',
  23. name='exp',
  24. )


5.4 训练过程截图


五、本文总结

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