学习资源站

YOLOv11改进-主干_Backbone篇-利用目标检测移动端网络MobileNetV1替换Backbone(支持v11n,v11s,v11m)

一、本文介绍

本文给大家带来的改进机制是 MobileNetV1 ,其是专为移动和嵌入式视觉应用设计的 轻量化网络 结构。这些 模型 基于简化的架构,并利用深度可分离卷积构建轻量级深度 神经网络 ,其 引入了两个简单的全局超参数 ,用于在延迟和准确性之间进行有效的权衡。实验表明,MobileNets在资源和准确性的权衡方面表现出色,并在多种应用(如对象检测、细粒度分类、面部属性识别和大规模地理定位)中展现了其有效性, 这个模型非常适合轻量化的读者来使用,本文发布了MobileNetV1三个版本 分别对应YOLOv11n、s、m内容为我个人所创是我在官方基础上的修改


二、 MobileNetV1 的框架原理

官方论文地址: 论文地址点击即可跳转

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


MobileNetV1的论文《MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications》介绍了一种高效的模型集合,专为移动和嵌入式视觉应用设计。这些模型基于简化的架构,并利用深度可分离卷积构建轻量级深度神经网络,从而适应移动和 嵌入式设备 的计算和存储限制。这种架构包含两个步骤:深度卷积(Depthwise Convolution)用于单独处理每个输入通道,然后是逐点卷积(Pointwise Convolution),用于整合深度卷积的输出。通过这种分解,MobileNet显著减少了模型的大小和计算复杂度,同时保持了良好的性能。论文还引入了两个全局超参数,允许在网络大小、速度和准确性之间进行灵活的权衡。

MobileNet的主要创新点包括:

1. 深度可分离卷积: 该网络架构使用深度可分离卷积代替标准卷积,显著减少模型参数和计算量。
2. 宽度乘数: 提供了一个超参数来调节网络的宽度,从而使得模型可以根据需要进行缩放,适应不 同的性能和资源要求。
3. 分辨率乘数:
允许调整输入图像的分辨率,进一步减少计算量。
其中第二点和第三点,在代码中很清楚的就能看到如下图红框的所示,分别对应第二点和第三点。

深度可分离卷积如下图所示

这张图片描绘了深度可分离卷积的概念,其中标准的卷积滤波器(a)被分解为两个独立的层:深度卷积(b)和逐点卷积(c)。在深度卷积中,每个输入通道独立应用一个滤波器,而逐点卷积则使用1x1的卷积核来组合深度卷积的输出。这种分解方法显著减少了计算量,因为它将卷积操作分为两个更简单的步骤:一个是应用于每个通道的滤波(深度卷积),另一个是这些滤波输出的组合(逐点卷积)。


三、MobileNetV1的核心代码

下面的代码是整个MobileNetV1的核心代码,大家如果想学习可以和上面的框架原理对比着看一看估计会有一定的收获,使用方式看章节四。

  1. import torch
  2. from torch import nn
  3. __all__ = ['MobileNetV1']
  4. class DepthwiseSepConvBlock(nn.Module):
  5. def __init__(
  6. self,
  7. in_channels: int,
  8. out_channels: int,
  9. stride: int = 1,
  10. use_relu6: bool = True,
  11. ):
  12. """Constructs Depthwise seperable with pointwise convolution with relu and batchnorm respectively.
  13. Args:
  14. in_channels (int): input channels for depthwise convolution
  15. out_channels (int): output channels for pointwise convolution
  16. stride (int, optional): stride paramemeter for depthwise convolution. Defaults to 1.
  17. use_relu6 (bool, optional): whether to use standard ReLU or ReLU6 for depthwise separable convolution block. Defaults to True.
  18. """
  19. super().__init__()
  20. # Depthwise conv
  21. self.depthwise_conv = nn.Conv2d(
  22. in_channels,
  23. in_channels,
  24. (3, 3),
  25. stride=stride,
  26. padding=1,
  27. groups=in_channels,
  28. )
  29. self.bn1 = nn.BatchNorm2d(in_channels)
  30. self.relu1 = nn.ReLU6() if use_relu6 else nn.ReLU()
  31. # Pointwise conv
  32. self.pointwise_conv = nn.Conv2d(in_channels, out_channels, (1, 1))
  33. self.bn2 = nn.BatchNorm2d(out_channels)
  34. self.relu2 = nn.ReLU6() if use_relu6 else nn.ReLU()
  35. def forward(self, x):
  36. """Perform forward pass."""
  37. x = self.depthwise_conv(x)
  38. x = self.bn1(x)
  39. x = self.relu1(x)
  40. x = self.pointwise_conv(x)
  41. x = self.bn2(x)
  42. x = self.relu2(x)
  43. return x
  44. class MobileNetV1(nn.Module):
  45. def __init__(
  46. self,
  47. input_channel: int = 3,
  48. depth_multiplier: float = 1.0,
  49. use_relu6: bool = True,
  50. ):
  51. """Constructs MobileNetV1 architecture
  52. Args:
  53. n_classes (int, optional): count of output neuron in last layer. Defaults to 1000.
  54. input_channel (int, optional): input channels in first conv layer. Defaults to 3.
  55. depth_multiplier (float, optional): network width multiplier ( width scaling ). Suggested Values - 0.25, 0.5, 0.75, 1.. Defaults to 1.0.
  56. use_relu6 (bool, optional): whether to use standard ReLU or ReLU6 for depthwise separable convolution block. Defaults to True.
  57. """
  58. super().__init__()
  59. # The configuration of MobileNetV1
  60. # input channels, output channels, stride
  61. config = (
  62. (32, 64, 1),
  63. (64, 128, 2),
  64. (128, 128, 1),
  65. (128, 256, 2),
  66. (256, 256, 1),
  67. (256, 512, 2),
  68. (512, 512, 1),
  69. (512, 512, 1),
  70. (512, 512, 1),
  71. (512, 512, 1),
  72. (512, 512, 1),
  73. (512, 1024, 2),
  74. (1024, 1024, 1),
  75. )
  76. self.model = nn.Sequential(
  77. nn.Conv2d(
  78. input_channel, int(32 * depth_multiplier), (3, 3), stride=2, padding=1
  79. )
  80. )
  81. # Adding depthwise block in the model from the config
  82. for in_channels, out_channels, stride in config:
  83. self.model.append(
  84. DepthwiseSepConvBlock(
  85. int(in_channels * depth_multiplier), # input channels
  86. int(out_channels * depth_multiplier), # output channels
  87. stride,
  88. use_relu6=use_relu6,
  89. )
  90. )
  91. self.index = [128, 256, 512, 1024]
  92. self.width_list = [i.size(1) for i in self.forward(torch.randn(1, 3, 640, 640))]
  93. def forward(self, x):
  94. """Perform forward pass."""
  95. results = [None, None, None, None]
  96. for model in self.model:
  97. x = model(x)
  98. if x.size(1) in self.index:
  99. position = self.index.index(x.size(1)) # Find the position in the index list
  100. results[position] = x
  101. return results
  102. if __name__ == "__main__":
  103. # Generating Sample image
  104. image_size = (1, 3, 224, 224)
  105. image = torch.rand(*image_size)
  106. # Model
  107. mobilenet_v1 = MobileNetV1(depth_multiplier=1)
  108. out = mobilenet_v1(image)
  109. print(out)


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

4.1 修改一

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


4.2 修改二

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


4.3 修改三

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

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


4.4 修改四

添加如下两行代码!!!

​​


4.5 修改五

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

  1. elif m in {自行添加对应的模型即可,下面都是一样的}:
  2. m = m(*args)
  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 修改七

修改七和前面的都不太一样,需要修改前向传播中的一个部分, 已经离开了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

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


注意!!! 额外的修改!

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


打印计算量问题解决方案

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

​​


注意事项!!!

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

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


五、MobileNetV1的yaml文件

5.1 yaml文件

训练信息:YOLO11-MobileNetV1 summary: 302 layers, 1,851,375 parameters, 1,851,359 gradients, 4.4 GFLOPs

# 这里需要注意的是比如你用的YOLOv11s那么你就用本文机制的s版本.

  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. # 我提供了三个版本分别是对应YOLOv8n v8s v8m。 MobileNetV1_n, MobileNetV1_s, MobileNetV1_m
  13. # YOLO11n backbone
  14. backbone:
  15. # [from, repeats, module, args]
  16. - [-1, 1, MobileNetV1_n, []] # 0-4 P1/2 这里是四层大家不要被yaml文件限制住了思维,不会画图进群看视频.
  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)


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

六、成功运行记录

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


七、本文总结

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

​​​