学习资源站

YOLOv11改进-Conv_卷积篇-2024最新深度可分卷积与多尺度卷积结合的模块MSCB助力yolov11有效涨点(全网独家首发)

一、本文介绍

本文给大家带来的最新改进机制是2024最新深度可分卷积与多尺度卷积的结合的模块MSCB,其核心机制是 Multi-scale Depth-wise Convolution (MSDC) 是一种改进的 卷积神经网络 CNN )结构,旨在提升卷积操作的多尺度特征提取能力。它的核心思想是通过在多个尺度下进行卷积操作,以捕获不同层级的图像特征,同时保持 深度可分卷积(Depth-wise Convolution) 的计算效率,我将其和C3k2进行结合(多种结合方式),分别为辅助yolov11进行特征提取能力和特征融合能力,本文内容为独家创新,文章内涵代码和添加方法。

训练信息:YOLO11-C3k2-MSCB1 summary: 395 layers, 2,555,235 parameters, 2,555,219 gradients, 6.3 GFLOPs
训练信息:YOLO11-C3k2-MSCB2 summary: 410 layers, 2,358,867 parameters, 2,358,851 gradients, 6.2 GFLOPs
未优化版本:YOLO11 summary: 319 layers, 2,590,035 parameters, 2,590,019 gradients, 6.4 GFLOPs

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



二、原理介绍

论文地址: 官方论文地址

代码地址: 官方代码地址

Multi-scale Depth-wise Convolution (MSDC) 是一种改进的卷积神经网络(CNN)结构,旨在提升卷积操作的 多尺度特征 提取能力。它的核心思想是通过在多个尺度下进行卷积操作,以捕获不同层级的图像特征,同时保持 深度可分卷积(Depth-wise Convolution) 的计算效率。

下面我们了解一下MSDC的 基本原理:

1. 深度可分卷积(Depth-wise Convolution)

在传统卷积中,卷积核会对输入的每个通道进行操作,然后得到一个新的特征图,而这种操作往往涉及大量的计算,尤其是在输入数据和卷积核的通道数较多时,计算量会急剧增加。

深度可分卷(Depth-wise Convolution)将传统卷积操作分解成 两个阶段:
(1)逐通道卷积: 对于输入的每个通道,使用一个卷积核单独进行卷积操作。每个卷积核只处理一个通道,通常使用较小的卷积核(例如3x3)。
(2)逐点卷积: 在每个通道的输出特征图上使用一个1x1卷积核进行线性组合(即通过逐点卷积将每个通道的输出进行融合)。

2. 多尺度卷积核的引入

传统的卷积神经网络通常使用固定大小的卷积核(如3x3、5x5等)来提取特征。然而,单一尺寸的卷积核往往只能捕捉到固定尺度的特征,无法全面地捕捉图像中不同大小、不同尺度的物体特征。为了解决这个问题, 多尺度卷积核(Multi-scale Kernels) 被引入到 MSDC 中。

在 MSDC 中,通过引入多种尺度(尺寸不同)的卷积核来提取图像的多尺度特征。常见的做法是使用不同尺寸的卷积核并行处理输入特征图,比如:使用 3 \times 3 的卷积核捕捉局部的细节信息。使用 5 \times 57 \times 7 的卷积核捕捉较大的上下文信息。这些不同尺度的卷积核能够捕捉到图像中的多种尺度特征(例如:小物体、大物体等),尤其是在图像中物体尺度变化较大的情况下,多尺度卷积能够帮助网络提高对不同尺度特征的感知能力。

3. 深度可分卷积与多尺度卷积的结合

将深度可分卷积与多尺度卷积结合,MSDC 在保持计算效率的同时,能够有效地捕捉图像中不同尺度的特征。具体而言,MSDC 使用多尺度卷积核(例如 3 \times 35 \times 57 \times 7 等)分别对输入的特征图进行卷积操作,并通过深度可分卷积的方式对每个尺度的卷积核进行操作,最后将这些不同尺度的特征进行融合(例如通过拼接或加和的方式)。

这种设计方式的具体流程如下:
1. 逐通道卷积: 每个卷积核(不同尺度)只作用于输入的每一个通道,分别对不同尺度的特征进行处理。
2. 多尺度特征提取: 多个不同尺度的卷积核会在同一层次上并行工作,每个卷积核从不同的感受野范围内提取特征。
3. 特征融合: 通过连接(concatenation)或加和(summation)等方式,将来自不同尺度卷积核的输出特征进行融合,得到包含多尺度信息的特征图。


三、核心代码

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

  1. import torch
  2. import torch.nn as nn
  3. from functools import partial
  4. import math
  5. from timm.models.layers import trunc_normal_tf_
  6. from timm.models.helpers import named_apply
  7. __all__ = ['C3k2_MSCB1', 'C3k2_MSCB2']
  8. def gcd(a, b):
  9. while b:
  10. a, b = b, a % b
  11. return a
  12. # Other types of layers can go here (e.g., nn.Linear, etc.)
  13. def _init_weights(module, name, scheme=''):
  14. if isinstance(module, nn.Conv2d) or isinstance(module, nn.Conv3d):
  15. if scheme == 'normal':
  16. nn.init.normal_(module.weight, std=.02)
  17. if module.bias is not None:
  18. nn.init.zeros_(module.bias)
  19. elif scheme == 'trunc_normal':
  20. trunc_normal_tf_(module.weight, std=.02)
  21. if module.bias is not None:
  22. nn.init.zeros_(module.bias)
  23. elif scheme == 'xavier_normal':
  24. nn.init.xavier_normal_(module.weight)
  25. if module.bias is not None:
  26. nn.init.zeros_(module.bias)
  27. elif scheme == 'kaiming_normal':
  28. nn.init.kaiming_normal_(module.weight, mode='fan_out', nonlinearity='relu')
  29. if module.bias is not None:
  30. nn.init.zeros_(module.bias)
  31. else:
  32. # efficientnet like
  33. fan_out = module.kernel_size[0] * module.kernel_size[1] * module.out_channels
  34. fan_out //= module.groups
  35. nn.init.normal_(module.weight, 0, math.sqrt(2.0 / fan_out))
  36. if module.bias is not None:
  37. nn.init.zeros_(module.bias)
  38. elif isinstance(module, nn.BatchNorm2d) or isinstance(module, nn.BatchNorm3d):
  39. nn.init.constant_(module.weight, 1)
  40. nn.init.constant_(module.bias, 0)
  41. elif isinstance(module, nn.LayerNorm):
  42. nn.init.constant_(module.weight, 1)
  43. nn.init.constant_(module.bias, 0)
  44. def act_layer(act, inplace=False, neg_slope=0.2, n_prelu=1):
  45. # activation layer
  46. act = act.lower()
  47. if act == 'relu':
  48. layer = nn.ReLU(inplace)
  49. elif act == 'relu6':
  50. layer = nn.ReLU6(inplace)
  51. elif act == 'leakyrelu':
  52. layer = nn.LeakyReLU(neg_slope, inplace)
  53. elif act == 'prelu':
  54. layer = nn.PReLU(num_parameters=n_prelu, init=neg_slope)
  55. elif act == 'gelu':
  56. layer = nn.GELU()
  57. elif act == 'hswish':
  58. layer = nn.Hardswish(inplace)
  59. else:
  60. raise NotImplementedError('activation layer [%s] is not found' % act)
  61. return layer
  62. def channel_shuffle(x, groups):
  63. batchsize, num_channels, height, width = x.data.size()
  64. channels_per_group = num_channels // groups
  65. # reshape
  66. x = x.view(batchsize, groups,
  67. channels_per_group, height, width)
  68. x = torch.transpose(x, 1, 2).contiguous()
  69. # flatten
  70. x = x.view(batchsize, -1, height, width)
  71. return x
  72. # Multi-scale depth-wise convolution (MSDC)
  73. class MSDC(nn.Module):
  74. def __init__(self, in_channels, kernel_sizes, stride, activation='relu6', dw_parallel=True):
  75. super(MSDC, self).__init__()
  76. self.in_channels = in_channels
  77. self.kernel_sizes = kernel_sizes
  78. self.activation = activation
  79. self.dw_parallel = dw_parallel
  80. self.dwconvs = nn.ModuleList([
  81. nn.Sequential(
  82. nn.Conv2d(self.in_channels, self.in_channels, kernel_size, stride, kernel_size // 2,
  83. groups=self.in_channels, bias=False),
  84. nn.BatchNorm2d(self.in_channels),
  85. act_layer(self.activation, inplace=True)
  86. )
  87. for kernel_size in self.kernel_sizes
  88. ])
  89. self.init_weights('normal')
  90. def init_weights(self, scheme=''):
  91. named_apply(partial(_init_weights, scheme=scheme), self)
  92. def forward(self, x):
  93. # Apply the convolution layers in a loop
  94. outputs = []
  95. for dwconv in self.dwconvs:
  96. dw_out = dwconv(x)
  97. outputs.append(dw_out)
  98. if self.dw_parallel == False:
  99. x = x + dw_out
  100. # You can return outputs based on what you intend to do with them
  101. return outputs
  102. class MSCB(nn.Module):
  103. """
  104. Multi-scale convolution block (MSCB)
  105. """
  106. def __init__(self, in_channels, out_channels, shortcut=False, stride=1, kernel_sizes=[1, 3, 5], expansion_factor=2, dw_parallel=True, activation='relu6'):
  107. super(MSCB, self).__init__()
  108. add = shortcut
  109. self.in_channels = in_channels
  110. self.out_channels = out_channels
  111. self.stride = stride
  112. self.kernel_sizes = kernel_sizes
  113. self.expansion_factor = expansion_factor
  114. self.dw_parallel = dw_parallel
  115. self.add = add
  116. self.activation = activation
  117. self.n_scales = len(self.kernel_sizes)
  118. # check stride value
  119. assert self.stride in [1, 2]
  120. # Skip connection if stride is 1
  121. self.use_skip_connection = True if self.stride == 1 else False
  122. # expansion factor
  123. self.ex_channels = int(self.in_channels * self.expansion_factor)
  124. self.pconv1 = nn.Sequential(
  125. # pointwise convolution
  126. nn.Conv2d(self.in_channels, self.ex_channels, 1, 1, 0, bias=False),
  127. nn.BatchNorm2d(self.ex_channels),
  128. act_layer(self.activation, inplace=True)
  129. )
  130. self.msdc = MSDC(self.ex_channels, self.kernel_sizes, self.stride, self.activation,
  131. dw_parallel=self.dw_parallel)
  132. if self.add == True:
  133. self.combined_channels = self.ex_channels * 1
  134. else:
  135. self.combined_channels = self.ex_channels * self.n_scales
  136. self.pconv2 = nn.Sequential(
  137. # pointwise convolution
  138. nn.Conv2d(self.combined_channels, self.out_channels, 1, 1, 0, bias=False),
  139. nn.BatchNorm2d(self.out_channels),
  140. )
  141. if self.use_skip_connection and (self.in_channels != self.out_channels):
  142. self.conv1x1 = nn.Conv2d(self.in_channels, self.out_channels, 1, 1, 0, bias=False)
  143. self.init_weights('normal')
  144. def init_weights(self, scheme=''):
  145. named_apply(partial(_init_weights, scheme=scheme), self)
  146. def forward(self, x):
  147. pout1 = self.pconv1(x)
  148. msdc_outs = self.msdc(pout1)
  149. if self.add == True:
  150. dout = 0
  151. for dwout in msdc_outs:
  152. dout = dout + dwout
  153. else:
  154. dout = torch.cat(msdc_outs, dim=1)
  155. dout = channel_shuffle(dout, gcd(self.combined_channels, self.out_channels))
  156. out = self.pconv2(dout)
  157. if self.use_skip_connection:
  158. if self.in_channels != self.out_channels:
  159. x = self.conv1x1(x)
  160. return x + out
  161. else:
  162. return out
  163. def autopad(k, p=None, d=1): # kernel, padding, dilation
  164. """Pad to 'same' shape outputs."""
  165. if d > 1:
  166. k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size
  167. if p is None:
  168. p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
  169. return p
  170. class Conv(nn.Module):
  171. """Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation)."""
  172. default_act = nn.SiLU() # default activation
  173. def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
  174. """Initialize Conv layer with given arguments including activation."""
  175. super().__init__()
  176. self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
  177. self.bn = nn.BatchNorm2d(c2)
  178. self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
  179. def forward(self, x):
  180. """Apply convolution, batch normalization and activation to input tensor."""
  181. return self.act(self.bn(self.conv(x)))
  182. def forward_fuse(self, x):
  183. """Perform transposed convolution of 2D data."""
  184. return self.act(self.conv(x))
  185. class Bottleneck(nn.Module):
  186. """Standard bottleneck."""
  187. def __init__(self, c1, c2, shortcut=True, g=1, k=(3, 3), e=0.5):
  188. """Initializes a standard bottleneck module with optional shortcut connection and configurable parameters."""
  189. super().__init__()
  190. c_ = int(c2 * e) # hidden channels
  191. self.cv1 = Conv(c1, c_, k[0], 1)
  192. self.cv2 = Conv(c_, c2, k[1], 1, g=g)
  193. self.add = shortcut and c1 == c2
  194. def forward(self, x):
  195. """Applies the YOLO FPN to input data."""
  196. return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
  197. class C2f(nn.Module):
  198. """Faster Implementation of CSP Bottleneck with 2 convolutions."""
  199. def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5):
  200. """Initializes a CSP bottleneck with 2 convolutions and n Bottleneck blocks for faster processing."""
  201. super().__init__()
  202. self.c = int(c2 * e) # hidden channels
  203. self.cv1 = Conv(c1, 2 * self.c, 1, 1)
  204. self.cv2 = Conv((2 + n) * self.c, c2, 1) # optional act=FReLU(c2)
  205. self.m = nn.ModuleList(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n))
  206. def forward(self, x):
  207. """Forward pass through C2f layer."""
  208. y = list(self.cv1(x).chunk(2, 1))
  209. y.extend(m(y[-1]) for m in self.m)
  210. return self.cv2(torch.cat(y, 1))
  211. def forward_split(self, x):
  212. """Forward pass using split() instead of chunk()."""
  213. y = list(self.cv1(x).split((self.c, self.c), 1))
  214. y.extend(m(y[-1]) for m in self.m)
  215. return self.cv2(torch.cat(y, 1))
  216. class C3(nn.Module):
  217. """CSP Bottleneck with 3 convolutions."""
  218. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
  219. """Initialize the CSP Bottleneck with given channels, number, shortcut, groups, and expansion values."""
  220. super().__init__()
  221. c_ = int(c2 * e) # hidden channels
  222. self.cv1 = Conv(c1, c_, 1, 1)
  223. self.cv2 = Conv(c1, c_, 1, 1)
  224. self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2)
  225. self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, k=((1, 1), (3, 3)), e=1.0) for _ in range(n)))
  226. def forward(self, x):
  227. """Forward pass through the CSP bottleneck with 2 convolutions."""
  228. return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
  229. class C3k(C3):
  230. """C3k is a CSP bottleneck module with customizable kernel sizes for feature extraction in neural networks."""
  231. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, k=3):
  232. """Initializes the C3k module with specified channels, number of layers, and configurations."""
  233. super().__init__(c1, c2, n, shortcut, g, e)
  234. c_ = int(c2 * e) # hidden channels
  235. # self.m = nn.Sequential(*(RepBottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
  236. self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
  237. class C3k_MSCB(C3):
  238. """C3k is a CSP bottleneck module with customizable kernel sizes for feature extraction in neural networks."""
  239. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, k=3):
  240. """Initializes the C3k module with specified channels, number of layers, and configurations."""
  241. super().__init__(c1, c2, n, shortcut, g, e)
  242. c_ = int(c2 * e) # hidden channels
  243. # self.m = nn.Sequential(*(RepBottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
  244. self.m = nn.Sequential(*(MSCB(c_, c_, shortcut) for _ in range(n)))
  245. class C3k2_MSCB1(C2f):
  246. """Faster Implementation of CSP Bottleneck with 2 convolutions."""
  247. def __init__(self, c1, c2, n=1, c3k=False, e=0.5, g=1, shortcut=True):
  248. """Initializes the C3k2 module, a faster CSP Bottleneck with 2 convolutions and optional C3k blocks."""
  249. super().__init__(c1, c2, n, shortcut, g, e)
  250. self.m = nn.ModuleList(
  251. C3k(self.c, self.c, 2, shortcut, g) if c3k else MSCB(self.c, self.c, shortcut) for _ in range(n)
  252. )
  253. # 解析 c3k在主干和网络最后一个C3k2的时候设置True走的是C3k, 否则我们走的是MSBlock
  254. class C3k2_MSCB2(C2f):
  255. """Faster Implementation of CSP Bottleneck with 2 convolutions."""
  256. def __init__(self, c1, c2, n=1, c3k=False, e=0.5, g=1, shortcut=True):
  257. """Initializes the C3k2 module, a faster CSP Bottleneck with 2 convolutions and optional C3k blocks."""
  258. super().__init__(c1, c2, n, shortcut, g, e)
  259. self.m = nn.ModuleList(
  260. C3k_MSCB(self.c, self.c, 2, shortcut, g) if c3k else Bottleneck(self.c, self.c, shortcut, g) for _ in range(n)
  261. )
  262. if __name__ == "__main__":
  263. # Generating Sample image
  264. image_size = (1, 64, 240, 240)
  265. image = torch.rand(*image_size)
  266. image_size1 = (1, 64, 480, 480)
  267. image1 = torch.rand(*image_size1)
  268. # Model
  269. mobilenet_v1 = MSCB(64, 64,)
  270. out = mobilenet_v1(image)
  271. 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-C3k2-MSCB1 summary: 395 layers, 2,555,235 parameters, 2,555,219 gradients, 6.3 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_MSCB1, [256, False, 0.25]]
  18. - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8
  19. - [-1, 2, C3k2_MSCB1, [512, False, 0.25]]
  20. - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16
  21. - [-1, 2, C3k2_MSCB1, [512, True]]
  22. - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32
  23. - [-1, 2, C3k2_MSCB1, [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_MSCB1, [512, False]] # 13
  31. - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
  32. - [[-1, 4], 1, Concat, [1]] # cat backbone P3
  33. - [-1, 2, C3k2_MSCB1, [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_MSCB1, [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_MSCB1, [1024, True]] # 22 (P5/32-large)
  40. - [[16, 19, 22], 1, Detect, [nc]] # Detect(P3, P4, P5)


5.2 yaml文件2

训练信息:YOLO11-C3k2-MSCB2 summary: 410 layers, 2,358,867 parameters, 2,358,851 gradients, 6.2 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_MSCB2, [256, False, 0.25]]
  18. - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8
  19. - [-1, 2, C3k2_MSCB2, [512, False, 0.25]]
  20. - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16
  21. - [-1, 2, C3k2_MSCB2, [512, True]]
  22. - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32
  23. - [-1, 2, C3k2_MSCB2, [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_MSCB2, [512, False]] # 13
  31. - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
  32. - [[-1, 4], 1, Concat, [1]] # cat backbone P3
  33. - [-1, 2, C3k2_MSCB2, [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_MSCB2, [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_MSCB2, [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('模型配置文件')
  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分,后期我会根据各种最新的前沿顶会进行论文复现,也会对一些老的改进机制进行补充,如果大家觉得本文帮助到你了,订阅本专栏,关注后续更多的更新~