学习资源站

YOLOv11改进-融合改进篇-华为VanillaNet配合HSFPN助力yolov11有效涨点(教你如何融合创新点)

一、本文介绍

本文给大家带来的最新改进机制是 华为VanillaNet主干 配合 HSFPN 实现融合涨点,这个主干是一种注重极简主义和效率的 神经网络 我也将其进行了实验, 其中的HSFPN其是一种为白细胞检测设计的网络结构,主要用于解决白细胞数据集中的 多尺度 挑战。它的基本原理包括两个关键部分: 特征选择模块 特征融合模块, 在本文的下面均会有讲解,这个结构是非常新颖的。其可以起到 特征选择 的作用,我将其融合在一起,大家可以复制过去在其基础上配合我的 损失函数 ,然后再加一个检测头如果在你的数据上有涨点效果大家就可以开始撰写论文了。我发的改进机制已经有多名读者在Qq私聊我已经有涨点效果了,均有记录证明! 欢迎大家订阅本专栏,本专栏每周更新3-5篇最新机制,更有包含我所有改进的文件和交流群提供给大家。

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


二、手把手教你添加华为VanillaNet主干

2.1 VanillaNet核心代码

  1. # Copyright (C) 2023. Huawei Technologies Co., Ltd. All rights reserved.
  2. # This program is free software; you can redistribute it and/or modify it under the terms of the MIT License.
  3. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MIT License for more details.
  4. import torch
  5. import torch.nn as nn
  6. from timm.layers import weight_init
  7. __all__ = ['vanillanet_5', 'vanillanet_6', 'vanillanet_7', 'vanillanet_8', 'vanillanet_9', 'vanillanet_10',
  8. 'vanillanet_11', 'vanillanet_12', 'vanillanet_13', 'vanillanet_13_x1_5', 'vanillanet_13_x1_5_ada_pool']
  9. class activation(nn.ReLU):
  10. def __init__(self, dim, act_num=3, deploy=False):
  11. super(activation, self).__init__()
  12. self.deploy = deploy
  13. self.weight = torch.nn.Parameter(torch.randn(dim, 1, act_num * 2 + 1, act_num * 2 + 1))
  14. self.bias = None
  15. self.bn = nn.BatchNorm2d(dim, eps=1e-6)
  16. self.dim = dim
  17. self.act_num = act_num
  18. weight_init.trunc_normal_(self.weight, std=.02)
  19. def forward(self, x):
  20. if self.deploy:
  21. return torch.nn.functional.conv2d(
  22. super(activation, self).forward(x),
  23. self.weight, self.bias, padding=(self.act_num * 2 + 1) // 2, groups=self.dim)
  24. else:
  25. return self.bn(torch.nn.functional.conv2d(
  26. super(activation, self).forward(x),
  27. self.weight, padding=self.act_num, groups=self.dim))
  28. def _fuse_bn_tensor(self, weight, bn):
  29. kernel = weight
  30. running_mean = bn.running_mean
  31. running_var = bn.running_var
  32. gamma = bn.weight
  33. beta = bn.bias
  34. eps = bn.eps
  35. std = (running_var + eps).sqrt()
  36. t = (gamma / std).reshape(-1, 1, 1, 1)
  37. return kernel * t, beta + (0 - running_mean) * gamma / std
  38. def switch_to_deploy(self):
  39. if not self.deploy:
  40. kernel, bias = self._fuse_bn_tensor(self.weight, self.bn)
  41. self.weight.data = kernel
  42. self.bias = torch.nn.Parameter(torch.zeros(self.dim))
  43. self.bias.data = bias
  44. self.__delattr__('bn')
  45. self.deploy = True
  46. class Block(nn.Module):
  47. def __init__(self, dim, dim_out, act_num=3, stride=2, deploy=False, ada_pool=None):
  48. super().__init__()
  49. self.act_learn = 1
  50. self.deploy = deploy
  51. if self.deploy:
  52. self.conv = nn.Conv2d(dim, dim_out, kernel_size=1)
  53. else:
  54. self.conv1 = nn.Sequential(
  55. nn.Conv2d(dim, dim, kernel_size=1),
  56. nn.BatchNorm2d(dim, eps=1e-6),
  57. )
  58. self.conv2 = nn.Sequential(
  59. nn.Conv2d(dim, dim_out, kernel_size=1),
  60. nn.BatchNorm2d(dim_out, eps=1e-6)
  61. )
  62. if not ada_pool:
  63. self.pool = nn.Identity() if stride == 1 else nn.MaxPool2d(stride)
  64. else:
  65. self.pool = nn.Identity() if stride == 1 else nn.AdaptiveMaxPool2d((ada_pool, ada_pool))
  66. self.act = activation(dim_out, act_num)
  67. def forward(self, x):
  68. if self.deploy:
  69. x = self.conv(x)
  70. else:
  71. x = self.conv1(x)
  72. x = torch.nn.functional.leaky_relu(x, self.act_learn)
  73. x = self.conv2(x)
  74. x = self.pool(x)
  75. x = self.act(x)
  76. return x
  77. def _fuse_bn_tensor(self, conv, bn):
  78. kernel = conv.weight
  79. bias = conv.bias
  80. running_mean = bn.running_mean
  81. running_var = bn.running_var
  82. gamma = bn.weight
  83. beta = bn.bias
  84. eps = bn.eps
  85. std = (running_var + eps).sqrt()
  86. t = (gamma / std).reshape(-1, 1, 1, 1)
  87. return kernel * t, beta + (bias - running_mean) * gamma / std
  88. def switch_to_deploy(self):
  89. if not self.deploy:
  90. kernel, bias = self._fuse_bn_tensor(self.conv1[0], self.conv1[1])
  91. self.conv1[0].weight.data = kernel
  92. self.conv1[0].bias.data = bias
  93. # kernel, bias = self.conv2[0].weight.data, self.conv2[0].bias.data
  94. kernel, bias = self._fuse_bn_tensor(self.conv2[0], self.conv2[1])
  95. self.conv = self.conv2[0]
  96. self.conv.weight.data = torch.matmul(kernel.transpose(1, 3),
  97. self.conv1[0].weight.data.squeeze(3).squeeze(2)).transpose(1, 3)
  98. self.conv.bias.data = bias + (self.conv1[0].bias.data.view(1, -1, 1, 1) * kernel).sum(3).sum(2).sum(1)
  99. self.__delattr__('conv1')
  100. self.__delattr__('conv2')
  101. self.act.switch_to_deploy()
  102. self.deploy = True
  103. class VanillaNet(nn.Module):
  104. def __init__(self, in_chans=3, num_classes=1000, dims=[96, 192, 384, 768],
  105. drop_rate=0, act_num=3, strides=[2, 2, 2, 1], deploy=False, ada_pool=None, **kwargs):
  106. super().__init__()
  107. self.deploy = deploy
  108. if self.deploy:
  109. self.stem = nn.Sequential(
  110. nn.Conv2d(in_chans, dims[0], kernel_size=4, stride=4),
  111. activation(dims[0], act_num)
  112. )
  113. else:
  114. self.stem1 = nn.Sequential(
  115. nn.Conv2d(in_chans, dims[0], kernel_size=4, stride=4),
  116. nn.BatchNorm2d(dims[0], eps=1e-6),
  117. )
  118. self.stem2 = nn.Sequential(
  119. nn.Conv2d(dims[0], dims[0], kernel_size=1, stride=1),
  120. nn.BatchNorm2d(dims[0], eps=1e-6),
  121. activation(dims[0], act_num)
  122. )
  123. self.act_learn = 1
  124. self.stages = nn.ModuleList()
  125. for i in range(len(strides)):
  126. if not ada_pool:
  127. stage = Block(dim=dims[i], dim_out=dims[i + 1], act_num=act_num, stride=strides[i], deploy=deploy)
  128. else:
  129. stage = Block(dim=dims[i], dim_out=dims[i + 1], act_num=act_num, stride=strides[i], deploy=deploy,
  130. ada_pool=ada_pool[i])
  131. self.stages.append(stage)
  132. self.depth = len(strides)
  133. self.apply(self._init_weights)
  134. self.width_list = [i.size(1) for i in self.forward(torch.randn(1, 3, 640, 640))]
  135. def _init_weights(self, m):
  136. if isinstance(m, (nn.Conv2d, nn.Linear)):
  137. weight_init.trunc_normal_(m.weight, std=.02)
  138. nn.init.constant_(m.bias, 0)
  139. def change_act(self, m):
  140. for i in range(self.depth):
  141. self.stages[i].act_learn = m
  142. self.act_learn = m
  143. def forward(self, x):
  144. unique_tensors = {}
  145. if self.deploy:
  146. x = self.stem(x)
  147. else:
  148. x = self.stem1(x)
  149. x = torch.nn.functional.leaky_relu(x, self.act_learn)
  150. x = self.stem2(x)
  151. width, height = x.shape[2], x.shape[3]
  152. unique_tensors[(width, height)] = x
  153. for i in range(self.depth):
  154. x = self.stages[i](x)
  155. width, height = x.shape[2], x.shape[3]
  156. unique_tensors[(width, height)] = x
  157. result_list = list(unique_tensors.values())[-4:]
  158. return result_list
  159. def _fuse_bn_tensor(self, conv, bn):
  160. kernel = conv.weight
  161. bias = conv.bias
  162. running_mean = bn.running_mean
  163. running_var = bn.running_var
  164. gamma = bn.weight
  165. beta = bn.bias
  166. eps = bn.eps
  167. std = (running_var + eps).sqrt()
  168. t = (gamma / std).reshape(-1, 1, 1, 1)
  169. return kernel * t, beta + (bias - running_mean) * gamma / std
  170. def switch_to_deploy(self):
  171. if not self.deploy:
  172. self.stem2[2].switch_to_deploy()
  173. kernel, bias = self._fuse_bn_tensor(self.stem1[0], self.stem1[1])
  174. self.stem1[0].weight.data = kernel
  175. self.stem1[0].bias.data = bias
  176. kernel, bias = self._fuse_bn_tensor(self.stem2[0], self.stem2[1])
  177. self.stem1[0].weight.data = torch.einsum('oi,icjk->ocjk', kernel.squeeze(3).squeeze(2),
  178. self.stem1[0].weight.data)
  179. self.stem1[0].bias.data = bias + (self.stem1[0].bias.data.view(1, -1, 1, 1) * kernel).sum(3).sum(2).sum(1)
  180. self.stem = torch.nn.Sequential(*[self.stem1[0], self.stem2[2]])
  181. self.__delattr__('stem1')
  182. self.__delattr__('stem2')
  183. for i in range(self.depth):
  184. self.stages[i].switch_to_deploy()
  185. self.deploy = True
  186. def vanillanet_5(pretrained=False, in_22k=False, **kwargs):
  187. model = VanillaNet(dims=[128 * 4, 256 * 4, 512 * 4, 1024 * 4], strides=[2, 2, 2], **kwargs)
  188. return model
  189. def vanillanet_6(pretrained=False, in_22k=False, **kwargs):
  190. model = VanillaNet(dims=[128 * 4, 256 * 4, 512 * 4, 1024 * 4, 1024 * 4], strides=[2, 2, 2, 1], **kwargs)
  191. return model
  192. def vanillanet_7(pretrained=False, in_22k=False, **kwargs):
  193. model = VanillaNet(dims=[128 * 4, 128 * 4, 256 * 4, 512 * 4, 1024 * 4, 1024 * 4], strides=[1, 2, 2, 2, 1], **kwargs)
  194. return model
  195. def vanillanet_8(pretrained=False, in_22k=False, **kwargs):
  196. model = VanillaNet(dims=[128 * 4, 128 * 4, 256 * 4, 512 * 4, 512 * 4, 1024 * 4, 1024 * 4],
  197. strides=[1, 2, 2, 1, 2, 1], **kwargs)
  198. return model
  199. def vanillanet_9(pretrained=False, in_22k=False, **kwargs):
  200. model = VanillaNet(dims=[128 * 4, 128 * 4, 256 * 4, 512 * 4, 512 * 4, 512 * 4, 1024 * 4, 1024 * 4],
  201. strides=[1, 2, 2, 1, 1, 2, 1], **kwargs)
  202. return model
  203. def vanillanet_10(pretrained=False, in_22k=False, **kwargs):
  204. model = VanillaNet(
  205. dims=[128 * 4, 128 * 4, 256 * 4, 512 * 4, 512 * 4, 512 * 4, 512 * 4, 1024 * 4, 1024 * 4],
  206. strides=[1, 2, 2, 1, 1, 1, 2, 1],
  207. **kwargs)
  208. return model
  209. def vanillanet_11(pretrained=False, in_22k=False, **kwargs):
  210. model = VanillaNet(
  211. dims=[128 * 4, 128 * 4, 256 * 4, 512 * 4, 512 * 4, 512 * 4, 512 * 4, 512 * 4, 1024 * 4, 1024 * 4],
  212. strides=[1, 2, 2, 1, 1, 1, 1, 2, 1],
  213. **kwargs)
  214. return model
  215. def vanillanet_12(pretrained=False, in_22k=False, **kwargs):
  216. model = VanillaNet(
  217. dims=[128 * 4, 128 * 4, 256 * 4, 512 * 4, 512 * 4, 512 * 4, 512 * 4, 512 * 4, 512 * 4, 1024 * 4, 1024 * 4],
  218. strides=[1, 2, 2, 1, 1, 1, 1, 1, 2, 1],
  219. **kwargs)
  220. return model
  221. def vanillanet_13(pretrained=False, in_22k=False, **kwargs):
  222. model = VanillaNet(
  223. dims=[128 * 4, 128 * 4, 256 * 4, 512 * 4, 512 * 4, 512 * 4, 512 * 4, 512 * 4, 512 * 4, 512 * 4, 1024 * 4,
  224. 1024 * 4],
  225. strides=[1, 2, 2, 1, 1, 1, 1, 1, 1, 2, 1],
  226. **kwargs)
  227. return model
  228. def vanillanet_13_x1_5(pretrained=False, in_22k=False, **kwargs):
  229. model = VanillaNet(
  230. dims=[128 * 6, 128 * 6, 256 * 6, 512 * 6, 512 * 6, 512 * 6, 512 * 6, 512 * 6, 512 * 6, 512 * 6, 1024 * 6,
  231. 1024 * 6],
  232. strides=[1, 2, 2, 1, 1, 1, 1, 1, 1, 2, 1],
  233. **kwargs)
  234. return model
  235. def vanillanet_13_x1_5_ada_pool(pretrained=False, in_22k=False, **kwargs):
  236. model = VanillaNet(
  237. dims=[128 * 6, 128 * 6, 256 * 6, 512 * 6, 512 * 6, 512 * 6, 512 * 6, 512 * 6, 512 * 6, 512 * 6, 1024 * 6,
  238. 1024 * 6],
  239. strides=[1, 2, 2, 1, 1, 1, 1, 1, 1, 2, 1],
  240. ada_pool=[0, 38, 19, 0, 0, 0, 0, 0, 0, 10, 0],
  241. **kwargs)
  242. return model

2.2 修改教程

2.2.1 修改一

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


2.2.2 修改二

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


2.2.3 修改三

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

从今天开始以后的教程就都统一成这个样子了,因为我默认大家用了我群内的文件来进行修改!!


2.2.4 修改四

添加如下两行代码!!!


2.2.5 修改五

找到七百多行大概把具体看图片,按照图片来修改就行,添加红框内的部分,注意没有()只是函数名。

  1. elif m in {自行添加对应的模型即可,下面都是一样的}:
  2. m = m(*args)
  3. c2 = m.width_list # 返回通道列表
  4. backbone = True


2.2.6 修改六

下面的两个红框内都是需要改动的。

  1. if isinstance(c2, list):
  2. m_ = m
  3. m_.backbone = True
  4. else:
  5. m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
  6. t = str(m)[8:-2].replace('__main__.', '') # module type
  7. m.np = sum(x.numel() for x in m_.parameters()) # number params
  8. m_.i, m_.f, m_.type = i + 4 if backbone else i, f, t # attach index, 'from' index, type


2.2.7 修改七

如下的也需要修改,全部按照我的来。

代码如下把原先的代码替换了即可。

  1. if verbose:
  2. LOGGER.info(f'{i:>3}{str(f):>20}{n_:>3}{m.np:10.0f} {t:<45}{str(args):<30}') # print
  3. save.extend(x % (i + 4 if backbone else i) for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
  4. layers.append(m_)
  5. if i == 0:
  6. ch = []
  7. if isinstance(c2, list):
  8. ch.extend(c2)
  9. if len(c2) != 5:
  10. ch.insert(0, 0)
  11. else:
  12. ch.append(c2)


2.2.8 修改八

修改七和前面的都不太一样,需要修改前向传播中的一个部分, 已经离开了parse_model方法了。

可以在图片中开代码行数,没有离开task.py文件都是同一个文件。 同时这个部分有好几个前向传播都很相似,大家不要看错了, 是70多行左右的!!!,同时我后面提供了代码,大家直接复制粘贴即可,有时间我针对这里会出一个视频。

代码如下->

  1. def _predict_once(self, x, profile=False, visualize=False):
  2. """
  3. Perform a forward pass through the network.
  4. Args:
  5. x (torch.Tensor): The input tensor to the model.
  6. profile (bool): Print the computation time of each layer if True, defaults to False.
  7. visualize (bool): Save the feature maps of the model if True, defaults to False.
  8. Returns:
  9. (torch.Tensor): The last output of the model.
  10. """
  11. y, dt = [], [] # outputs
  12. for m in self.model:
  13. if m.f != -1: # if not from previous layer
  14. x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
  15. if profile:
  16. self._profile_one_layer(m, x, dt)
  17. if hasattr(m, 'backbone'):
  18. x = m(x)
  19. if len(x) != 5: # 0 - 5
  20. x.insert(0, None)
  21. for index, i in enumerate(x):
  22. if index in self.save:
  23. y.append(i)
  24. else:
  25. y.append(None)
  26. x = x[-1] # 最后一个输出传给下一层
  27. else:
  28. x = m(x) # run
  29. y.append(x if m.i in self.save else None) # save output
  30. if visualize:
  31. feature_visualization(x, m.type, m.i, save_dir=visualize)
  32. return x

到这里就完成了修改部分,但是这里面细节很多,大家千万要注意不要替换多余的代码,导致报错,也不要拉下任何一部,都会导致运行失败,而且报错很难排查!!!很难排查!!!


注意!!! 额外的修改!

关注我的其实都知道,我大部分的修改都是一样的,这个网络需要额外的修改一步,就是s一个参数,将下面的s改为640!!!即可完美运行!!


修改八

我们找到如下文件'ultralytics/utils/torch_utils.py'按照如下的图片进行修改,否则容易打印不出来计算量。


注意事项!!!

如果大家在验证的时候报错形状不匹配的错误可以固定 验证集 的图片尺寸,方法如下 ->

找到下面这个文件ultralytics/ models /yolo/detect/train.py然后其中有一个类是DetectionTrainer class中的build_dataset函数中的一个参数rect=mode == 'val'改为rect=False


三、HSFPN的核心代码

  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. __all__ = ['CA', 'multiply', 'Add']
  5. class Add(nn.Module):
  6. # Concatenate a list of tensors along dimension
  7. def __init__(self, ch=256):
  8. super().__init__()
  9. def forward(self, x):
  10. input1, input2 = x[0], x[1]
  11. x = input1 + input2
  12. return x
  13. class multiply(nn.Module):
  14. def __init__(self):
  15. super().__init__()
  16. def forward(self, x):
  17. x = x[0] * x[1]
  18. return x
  19. class CA(nn.Module):
  20. def __init__(self, in_planes, ratio = 4, flag=True):
  21. super(CA, self).__init__()
  22. self.avg_pool = nn.AdaptiveAvgPool2d(1)
  23. self.max_pool = nn.AdaptiveMaxPool2d(1)
  24. self.conv1 = nn.Conv2d(in_planes, in_planes // ratio, 1, bias=False)
  25. self.relu = nn.ReLU()
  26. self.conv2 = nn.Conv2d(in_planes // ratio, in_planes, 1, bias=False)
  27. self.flag = flag
  28. self.sigmoid = nn.Sigmoid()
  29. nn.init.xavier_uniform_(self.conv1.weight)
  30. nn.init.xavier_uniform_(self.conv2.weight)
  31. def forward(self, x):
  32. avg_out = self.conv2(self.relu(self.conv1(self.avg_pool(x))))
  33. max_out = self.conv2(self.relu(self.conv1(self.max_pool(x))))
  34. out = avg_out + max_out
  35. out = self.sigmoid(out) * x if self.flag else self.sigmoid(out)
  36. return out
  37. class FeatureSelectionModule(nn.Module):
  38. def __init__(self, in_chan, out_chan):
  39. super(FeatureSelectionModule, self).__init__()
  40. self.conv_atten = nn.Conv2d(in_chan, in_chan, kernel_size=1)
  41. self.group_norm1 = nn.GroupNorm(32, in_chan)
  42. self.sigmoid = nn.Sigmoid()
  43. self.conv = nn.Conv2d(in_chan, out_chan, kernel_size=1)
  44. self.group_norm2 = nn.GroupNorm(32, out_chan)
  45. nn.init.xavier_uniform_(self.conv_atten.weight)
  46. nn.init.xavier_uniform_(self.conv.weight)
  47. def forward(self, x):
  48. atten = self.sigmoid(self.group_norm1(self.conv_atten(F.avg_pool2d(x, x.size()[2:]))))
  49. feat = torch.mul(x, atten)
  50. x = x + feat
  51. feat = self.group_norm2(self.conv(x))
  52. return feat
  53. if __name__ == "__main__":
  54. # Generating Sample image
  55. image_size = (1, 64, 240, 240)
  56. image = torch.rand(*image_size)
  57. # Model
  58. mobilenet_v3 = FeatureSelectionModule(64, 64)
  59. out = mobilenet_v3(image)
  60. print(out.size())


四、手把手教你添加HS-FPN


4.1 修改一

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


4.2 修改二

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

​​​


4.3 修改三

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

​​​


4.4 修改四

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


4.5 修改五

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

  1. elif m in {'此处添加大家修改的对应机制即可'}:
  2. c2 = ch[f]
  3. args = [c2, *args]
  1. elif m is multiply:
  2. c2 = ch[f[0]]
  3. elif m is Add:
  4. c2 = ch[f[-1]]

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


五、融合后的yaml文件

5.1 yaml文件

训练信息:YOLO11-vanillanet-HSFPN summary: 265 layers, 3,128,418 parameters, 3,128,402 gradients, 12.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. # 下面 [-1, 1, vanillanet_5, [0.25]] 参数位置的0.25是通道放缩的系数, YOLOv11N是0.25 YOLOv11S是0.5 YOLOv11M是1. YOLOv11l是1 YOLOv111.5大家根据自己训练的YOLO版本设定即可.
  13. # 本文支持版本有 vanillanet_5, vanillanet_6, vanillanet_7, vanillanet_8, vanillanet_9, vanillanet_10, vanillanet_11, vanillanet_12, vanillanet_13, vanillanet_13_x1_5, vanillanet_13_x1_5_ada_pool
  14. # YOLO11n backbone
  15. backbone:
  16. # [from, repeats, module, args]
  17. - [-1, 1, vanillanet_5, [0.25]] # 0-4 P1/2 这里是四层大家不要被yaml文件限制住了思维,不会画图进群看视频.
  18. - [-1, 1, SPPF, [1024, 5]] # 5
  19. - [-1, 2, C2PSA, [1024]] # 6
  20. # YOLO11n head
  21. head:
  22. - [-1, 1, CA, []] # 11
  23. - [-1, 1, nn.Conv2d, [256, 1]] # 12
  24. - [-1, 2, C3k2, [256, False]] # 13 P5
  25. - [3, 1, CA, []]
  26. - [-1, 1, nn.Conv2d, [256, 1]] # 15
  27. - [8, 1, nn.ConvTranspose2d, [256, 3, 2, 1, 1]] # 16
  28. - [-1, 1, CA, [4, False]]
  29. - [[-1, 11], 1, multiply, []] # 18
  30. - [[-1, 12], 1, Add, []] # 19
  31. - [-1, 2, C3k2, [256, False]] # 20 P4
  32. - [2, 1, CA, []] # 21
  33. - [-1, 1, nn.Conv2d, [256, 1]] # 22
  34. - [12, 1, nn.ConvTranspose2d, [256, 3, 2, 1, 1]] # 23
  35. - [-1, 1, CA, [4, False]] # 24
  36. - [[-1, 18], 1, multiply, []] # 25
  37. - [[-1, 19], 1, Add, []] # 26
  38. - [-1, 2, C3k2, [256, True]] # 27 P3
  39. - [[23, 16, 9], 1, Detect, [nc]] # Det

5.2 运行文件

可以复制我的运行文件进行运行,

  1. import warnings
  2. warnings.filterwarnings('ignore')
  3. from ultralytics import YOLO
  4. if __name__ == '__main__':
  5. model = YOLO("替换你的yaml文件地址")
  6. # model.load('yolov8n.pt') # 不建议大家加载初始化权重尤其这种替换主干和Neck的改进机制
  7. model.train(data=r'你的数据集的地址',
  8. cache=False,
  9. imgsz=640,
  10. epochs=150,
  11. batch=4,
  12. close_mosaic=0,
  13. workers=0,
  14. device=0,
  15. optimizer='SGD'
  16. amp = False,
  17. )


5.3 运行记录


五、本文总结

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