学习资源站

YOLOv11改进-主干_Backbone篇-轻量级移动端网络ShuffleNetV1(附代码加修改教程)

一、本文内容

本文给大家带来的改进内容是 ShuffleNetV1 ,这是一种为 移动设备 设计的高效CNN架构。它通过使用点群卷积和通道混洗等操作,减少了计算成本,同时保持了准确性,通过这些技术,ShuffleNet在降低计算复杂度的同时,也优化了内存使用,使其更适合低功耗的移动设备(我在YOLOv11n上修改该主干 计算量仅为5.1GFLOPs ,但是参数量还是有一定上涨。本文通过介绍其主要框架原理,然后教你如何添加该网络结构到网络 模型 中。



二、ShuffleNetV1框架原理

官方论文地址: 官方论文地址

官方代码地址: 官方代码地址


ShuffleNet的创新机制为 点群卷积和通道混:使用了新的操作点群卷积(pointwise group convolution)和通道混洗(channel shuffle),以减少计算成本,同时保持网络精度

您上传的图片展示的是ShuffleNet架构中的通道混洗机制。这一机制通过两个堆叠的 分组卷积 (GConv)来实现:

图示(a): 展示了两个具有相同分组数量的堆叠卷积层。每个输出通道仅与同一组内的输入通道相 关联。
图示(b):
在不使用通道混洗的情况下,展示了在GConv1之后,GConv2从不同分组获取数据时输入和输出通道是如何完全相关联的。
图示(c: 提供了与(b)相同的实现,但使用了通道混洗来允许跨组通信,从而使网络内更有效和强大的特征学习成为可能。

上面的图片描述了ShuffleNet架构中的ShuffleNet单元。这些单元是网络中的基本构建块,具体包括:

图示(a): 一个基本的瓶颈单元,使用了深度可分离卷积(DWConv)和一个简单的加法(Add)来融合特征。
图示(b): 在标准瓶颈单元的基础上,引入了点群卷积(GConv)和通道混洗操作,以增强特征的表达能力。
图示(c): 适用于空间下采样的ShuffleNet单元,使用步长为2的平均池化(AVG Pool)和深度可分离卷积,再通过通道混洗和点群卷积进一步处理特征,最后通过连接操作(Concat)合并特征。


三、ShuffleNetV1核心代码

下面的代码是整个ShuffleNetV1的核心代码,其中有个版本,对应的GFLOPs也不相同,使用方式看章节四。

  1. # Copyright 2022 Dakewe Biotech Corporation. All Rights Reserved.
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software
  9. # distributed under the License is distributed on an "AS IS" BASIS,
  10. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. # See the License for the specific language governing permissions and
  12. # limitations under the License.
  13. # ==============================================================================
  14. from typing import Any, List, Optional
  15. import torch
  16. from torch import Tensor
  17. from torch import nn
  18. __all__ = [
  19. "ShuffleNetV1",
  20. "shufflenet_v1_x0_5", "shufflenet_v1_x1_0", "shufflenet_v1_x1_5", "shufflenet_v1_x2_0",
  21. ]
  22. class ShuffleNetV1(nn.Module):
  23. def __init__(
  24. self,
  25. repeats_times: List[int],
  26. stages_out_channels: List[int],
  27. groups: int = 8,
  28. num_classes: int = 1000,
  29. ) -> None:
  30. super(ShuffleNetV1, self).__init__()
  31. in_channels = stages_out_channels[0]
  32. self.first_conv = nn.Sequential(
  33. nn.Conv2d(3, in_channels, (3, 3), (2, 2), (1, 1), bias=False),
  34. nn.BatchNorm2d(in_channels),
  35. nn.ReLU(True),
  36. )
  37. self.maxpool = nn.MaxPool2d((3, 3), (2, 2), (1, 1))
  38. features = []
  39. for state_repeats_times_index in range(len(repeats_times)):
  40. out_channels = stages_out_channels[state_repeats_times_index + 1]
  41. for i in range(repeats_times[state_repeats_times_index]):
  42. stride = 2 if i == 0 else 1
  43. first_group = state_repeats_times_index == 0 and i == 0
  44. features.append(
  45. ShuffleNetV1Unit(
  46. in_channels,
  47. out_channels,
  48. stride,
  49. groups,
  50. first_group,
  51. )
  52. )
  53. in_channels = out_channels
  54. self.features = nn.Sequential(*features)
  55. self.globalpool = nn.AvgPool2d((7, 7))
  56. self.classifier = nn.Sequential(
  57. nn.Linear(stages_out_channels[-1], num_classes, bias=False),
  58. )
  59. # Initialize neural network weights
  60. self._initialize_weights()
  61. self.index = stages_out_channels[-3:]
  62. self.width_list = [i.size(1) for i in self.forward(torch.randn(1, 3, 640, 640))]
  63. def forward(self, x: Tensor) -> list[Optional[Any]]:
  64. x = self.first_conv(x)
  65. x = self.maxpool(x)
  66. results = [None, None, None, None]
  67. for index, model in enumerate(self.features):
  68. x = model(x)
  69. # results.append(x)
  70. if index == 0:
  71. results[index] = x
  72. if x.size(1) in self.index:
  73. position = self.index.index(x.size(1)) # Find the position in the index list
  74. results[position + 1] = x
  75. return results
  76. def _initialize_weights(self) -> None:
  77. for name, module in self.named_modules():
  78. if isinstance(module, nn.Conv2d):
  79. if 'first' in name:
  80. nn.init.normal_(module.weight, 0, 0.01)
  81. else:
  82. nn.init.normal_(module.weight, 0, 1.0 / module.weight.shape[1])
  83. if module.bias is not None:
  84. nn.init.constant_(module.bias, 0)
  85. elif isinstance(module, nn.BatchNorm2d):
  86. nn.init.constant_(module.weight, 1)
  87. if module.bias is not None:
  88. nn.init.constant_(module.bias, 0.0001)
  89. nn.init.constant_(module.running_mean, 0)
  90. elif isinstance(module, nn.BatchNorm1d):
  91. nn.init.constant_(module.weight, 1)
  92. if module.bias is not None:
  93. nn.init.constant_(module.bias, 0.0001)
  94. nn.init.constant_(module.running_mean, 0)
  95. elif isinstance(module, nn.Linear):
  96. nn.init.normal_(module.weight, 0, 0.01)
  97. if module.bias is not None:
  98. nn.init.constant_(module.bias, 0)
  99. class ShuffleNetV1Unit(nn.Module):
  100. def __init__(
  101. self,
  102. in_channels: int,
  103. out_channels: int,
  104. stride: int,
  105. groups: int,
  106. first_groups: bool = False,
  107. ) -> None:
  108. super(ShuffleNetV1Unit, self).__init__()
  109. self.stride = stride
  110. self.groups = groups
  111. self.first_groups = first_groups
  112. hidden_channels = out_channels // 4
  113. if stride == 2:
  114. out_channels -= in_channels
  115. self.branch_proj = nn.AvgPool2d((3, 3), (2, 2), (1, 1))
  116. self.branch_main_1 = nn.Sequential(
  117. # pw
  118. nn.Conv2d(in_channels, hidden_channels, (1, 1), (1, 1), (0, 0), groups=1 if first_groups else groups,
  119. bias=False),
  120. nn.BatchNorm2d(hidden_channels),
  121. nn.ReLU(True),
  122. # dw
  123. nn.Conv2d(hidden_channels, hidden_channels, (3, 3), (stride, stride), (1, 1), groups=hidden_channels,
  124. bias=False),
  125. nn.BatchNorm2d(hidden_channels),
  126. )
  127. self.branch_main_2 = nn.Sequential(
  128. # pw-linear
  129. nn.Conv2d(hidden_channels, out_channels, (1, 1), (1, 1), (0, 0), groups=groups, bias=False),
  130. nn.BatchNorm2d(out_channels),
  131. )
  132. self.relu = nn.ReLU(True)
  133. def channel_shuffle(self, x):
  134. batch_size, channels, height, width = x.data.size()
  135. assert channels % self.groups == 0
  136. group_channels = channels // self.groups
  137. out = x.reshape(batch_size, group_channels, self.groups, height, width)
  138. out = out.permute(0, 2, 1, 3, 4)
  139. out = out.reshape(batch_size, channels, height, width)
  140. return out
  141. def forward(self, x: Tensor) -> Tensor:
  142. identify = x
  143. out = self.branch_main_1(x)
  144. out = self.channel_shuffle(out)
  145. out = self.branch_main_2(out)
  146. if self.stride == 2:
  147. branch_proj = self.branch_proj(x)
  148. out = self.relu(out)
  149. out = torch.cat([branch_proj, out], 1)
  150. return out
  151. else:
  152. out = torch.add(out, identify)
  153. out = self.relu(out)
  154. return out
  155. def shufflenet_v1_x0_5(**kwargs: Any) -> ShuffleNetV1:
  156. model = ShuffleNetV1([4, 8, 4], [16, 192, 384, 768], 8, **kwargs)
  157. return model
  158. def shufflenet_v1_x1_0(**kwargs: Any) -> ShuffleNetV1:
  159. model = ShuffleNetV1([4, 8, 4], [24, 384, 768, 1536], 8, **kwargs)
  160. return model
  161. def shufflenet_v1_x1_5(**kwargs: Any) -> ShuffleNetV1:
  162. model = ShuffleNetV1([4, 8, 4], [24, 576, 1152, 2304], 8, **kwargs)
  163. return model
  164. def shufflenet_v1_x2_0(**kwargs: Any) -> ShuffleNetV1:
  165. model = ShuffleNetV1([4, 8, 4], [48, 768, 1536, 3072], 8, **kwargs)
  166. return model
  167. if __name__ == "__main__":
  168. # Generating Sample image
  169. image_size = (1, 3, 640, 640)
  170. image = torch.rand(*image_size)
  171. # Model
  172. model = shufflenet_v1_x0_5()
  173. out = model(image)
  174. print(out)


四、手把手教你添加ShuffleNetV1网络结构

这个主干的网络结构添加起来算是所有的改进机制里最麻烦的了,因为有一些网略结构可以用yaml文件搭建出来,有一些网络结构其中的一些细节根本没有办法用yaml文件去搭建,用yaml文件去搭建会损失一些细节部分(而且一个网络结构设计很多细节的结构修改方式都不一样,一个一个去修改大家难免会出错),所以这里让网络直接返回整个网络,然后修改部分 yolo代码以后就都以这种形式添加了,以后我提出的网络模型基本上都会通过这种方式修改,我也会进行一些模型细节改进。创新出新的网络结构大家直接拿来用就可以的。 下面开始添加教程->

(同时每一个后面都有代码,大家拿来复制粘贴替换即可,但是要看好了不要复制粘贴替换多了)


4.1 修改一

我们复制网络结构代码到“ ultralytics /nn”目录下创建一个py文件复制粘贴进去 ,我这里起的名字是ShuffleNetV1。


4.2 修改二

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


4.3 修改三

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

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


4.4 修改四

添加如下两行代码!!!


4.5 修改五

找到七百多行大概把具体看图片,按照图片来修改就行,添加红框内的部分,注意没有()只是 函数 名,我这里只添加了部分的版本,大家有兴趣这个ShuffleNetV1还有更多的版本可以添加,看我给的代码函数头即可。

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


4.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


4.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)


4.8 修改八

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

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

​​

代码如下->

  1. def _predict_once(self, x, profile=False, visualize=False, embed=None):
  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. embed (list, optional): A list of feature vectors/embeddings to return.
  9. Returns:
  10. (torch.Tensor): The last output of the model.
  11. """
  12. y, dt, embeddings = [], [], [] # outputs
  13. for m in self.model:
  14. if m.f != -1: # if not from previous layer
  15. 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
  16. if profile:
  17. self._profile_one_layer(m, x, dt)
  18. if hasattr(m, 'backbone'):
  19. x = m(x)
  20. if len(x) != 5: # 0 - 5
  21. x.insert(0, None)
  22. for index, i in enumerate(x):
  23. if index in self.save:
  24. y.append(i)
  25. else:
  26. y.append(None)
  27. x = x[-1] # 最后一个输出传给下一层
  28. else:
  29. x = m(x) # run
  30. y.append(x if m.i in self.save else None) # save output
  31. if visualize:
  32. feature_visualization(x, m.type, m.i, save_dir=visualize)
  33. if embed and m.i in embed:
  34. embeddings.append(nn.functional.adaptive_avg_pool2d(x, (1, 1)).squeeze(-1).squeeze(-1)) # flatten
  35. if m.i == max(embed):
  36. return torch.unbind(torch.cat(embeddings, 1), dim=0)
  37. return x

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


4.9 修改九

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


五、ShuffleNetV1的yaml文件

复制如下yaml文件进行运行!!!

此版本训练信息:YOLO11-shuffleNetV1 summary: 397 layers, 3,215,691 parameters, 3,215,675 gradients, 5.1 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. # 共四个版本 "shufflenet_v1_x0_5", "shufflenet_v1_x1_0", "shufflenet_v1_x1_5", "shufflenet_v1_x2_0"
  13. # YOLO11n backbone
  14. backbone:
  15. # [from, repeats, module, args]
  16. - [-1, 1, shufflenet_v1_x0_5, []] # 0-4 P1/2
  17. - [-1, 1, SPPF, [1024, 5]] # 5
  18. - [-1, 2, C2PSA, [1024]] # 6
  19. # YOLO11n head
  20. head:
  21. - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
  22. - [[-1, 3], 1, Concat, [1]] # cat backbone P4
  23. - [-1, 2, C3k2, [512, False]] # 9
  24. - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
  25. - [[-1, 2], 1, Concat, [1]] # cat backbone P3
  26. - [-1, 2, C3k2, [256, False]] # 12 (P3/8-small)
  27. - [-1, 1, Conv, [256, 3, 2]]
  28. - [[-1, 9], 1, Concat, [1]] # cat head P4
  29. - [-1, 2, C3k2, [512, False]] # 15 (P4/16-medium)
  30. - [-1, 1, Conv, [512, 3, 2]]
  31. - [[-1, 6], 1, Concat, [1]] # cat head P5
  32. - [-1, 2, C3k2, [1024, True]] # 18 (P5/32-large)
  33. - [[12, 15, 18], 1, Detect, [nc]] # Detect(P3, P4, P5)


六、成功运行记录

下面是成功运行的截图,已经完成了有1个epochs的训练,图片太大截不全第2个epochs了。


七、本文总结

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

​​