学习资源站

YOLOv11改进-主干_Backbone篇-利用目标检测轻量化网络MobileNetV2替换Backbone(yolov11系列全系轻量化)

一、本文介绍

本文给大家带来的改进机制是 MobileNetV2 ,其是专为移动和嵌入式视觉应用设计的 轻量化网络 结构。其在MobilNetV1的基础上采用反转残差结构和线性瓶颈层。这种结构通过轻量级的深度卷积和线性卷积过滤特征,同时去除狭窄层中的非线性,以维持表征能力。 MobileNetV2在性能上和精度上都要比V1版本强很多 ,其在多种应用(如对象检测、细粒度分类、面部属性识别和大规模地理定位)中都展现了一定的有效性 ,(yolov11系列全系轻量化)



二、MobileNetV2的框架原理

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

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


2.1 MobileNetV2的基本原理

MobileNetV2是在MobileNetV1基础上提出来的,其不光具有V1的全部改进,还提出了采用反转残差结构和线性瓶颈层。这种结构通过轻量级的深度卷积和线性卷积过滤特征,同时去除狭窄层中的非线性,以维持表征能力。MobileNetV2通过这种设计提高了 性能 ,并在多种任务和基准测试上表现出色。此外,它提出了一种新的框架SSDLite,用于移动设备上的目标检测,并展示了如何构建移动语义分割模型Mobile DeepLabv3。这种方法允许输入/输出域与变换的表达力解耦,为进一步分析提供了方便的框架。

MobileNetV2的主要创新点包括:

1. 反转残差结构: 使用轻量级的深度卷积作为扩展层来提高特征过滤的效率。
2. 线性瓶颈层: 在狭窄的层中去除非线性激活函数,以保持网络的表征能力。
3. SSDLite框架: 用于移动设备上的高效目标检测,它是一种简化和优化的SSD框架。

2.1.1 反转残差结构

反转残差结构是MobileNetV2的关键特性 ,它采用轻量级的深度可分离卷积作为扩展层。这种结构首先使用1x1的卷积将输入特征图的通道数扩大,然后应用深度可分离卷积对这些扩展的特征图进行空间特征提取,最后再次通过1x1的卷积将通道数减少,恢复到原来的尺寸。这样的设计有效地提高了网络处理特征的效率,同时减少了参数数量和计算成本。通过这种方式,MobileNetV2能够在保持 模型 轻量的同时,提供足够的模型表现力,适用于移动和嵌入式设备上的高效计算。

上图展示了残差块和反转残差块之间的区别:

(a) 残差: 传统的残差块通过直接连接输入和输出来促进特征的传递,通常包含具有高通道数的层和ReLU激活函数。
(b) 反转残差块: 在反转残差块中,连接是在瓶颈层之间,即通道数较少的层,而且去除了非线性激活函数,以保持特征的表达力。这种设计通常首先用一个扩展层增加通道数,然后应用深度卷积处理特征,并且在最后一个线性层减少通道数。

2.1.2 线性瓶颈层

线性瓶颈层是MobileNetV2架构中的另一个关键特性。在这种结构中,传统的非线性激活函数被有意地从瓶颈层中去除。瓶颈层是指那些通道数较少的卷积层,它们位于扩展层和压缩层之间。这样做的目的是为了减少信息在通过狭窄层时的损失,因为非线性操作可能会破坏特征中的一些信息。通过保持这些层的线性,网络能够维持更丰富的特征表示,这对于提高模型的整体性能至关重要。

总结: 就是在一些卷积层里面把激活函数删除掉了,类似于v8中的Bottleneck模块,将其中的激活函数删除掉。

2.1.3 SSDLite框架

SSDLite是一个轻量级的目标检测框架,专为移动设备优化。它是SSD框架的简化版本,通过使用深度可分离卷积替换SSD中的标准卷积,显著减少了计算量和模型的大小。SSDLite继承了SSD的单次检测机制,使得模型在进行目标检测时既高效又准确。这种设计使SSDLite非常适合在资源受限的设备上进行实时目标检测任务。

上图展示了可分离卷积块的演变。其中:

(a) 展示了常规的卷积。
(b) 展示了可分离卷积块,这种块首先使用深度卷积分别处理每个输入通道,然后用一个1x1的卷积组合这些特征。
(c) 展示了带有线性瓶颈的可分离卷积,它在瓶颈层中移除了非线性激活函数,以保持特征的表达力。
(d) 展示了带有扩展层的瓶颈结构,它使用一个扩展层放大特征空间,然后再用深度卷积和1x1卷积进行处理。

对角线阴影的纹理表示不包含非线性的层,最后的浅色层表示下一个块的开始。请注意,当堆叠时,2d和2c是等效的块。


三、MobileNetV2的核心代码

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

  1. import torch
  2. from torch import nn
  3. __all__ = ['MobileNetV2_n', 'MobileNetV2_s', 'MobileNetV2_m']
  4. class ConvNormReLUBlock(nn.Module):
  5. def __init__(
  6. self,
  7. in_channels: int,
  8. out_channels: int,
  9. kernel_size: list,
  10. stride: int = 1,
  11. padding: int = 0,
  12. groups: int = 1,
  13. bias: bool = False,
  14. activation: bool = nn.ReLU6,
  15. ):
  16. """Constructs a block containing a combination of convolution, batchnorm and relu
  17. Args:
  18. in_channels (int): input channels
  19. out_channels (int): output channels
  20. kernel_size (list): kernel size parameter for convolution
  21. stride (int, optional): stride parameter for convolution. Defaults to 1.
  22. padding (int, optional): padding parameter for convolution. Defaults to 0.
  23. groups (int, optional): number of blocked connections from input channel to output channel for convolution. Defaults to 1.
  24. bias (bool, optional): whether to enable bias in convolution. Defaults to False.
  25. activation (bool, optional): activation function to use. Defaults to nn.ReLU6.
  26. """
  27. super().__init__()
  28. self.conv = nn.Conv2d(
  29. in_channels,
  30. out_channels,
  31. kernel_size,
  32. stride=stride,
  33. padding=padding,
  34. groups=groups,
  35. bias=bias,
  36. )
  37. self.bn = nn.BatchNorm2d(out_channels)
  38. self.activation = activation()
  39. def forward(self, x):
  40. """Perform forward pass."""
  41. x = self.conv(x)
  42. x = self.bn(x)
  43. x = self.activation(x)
  44. return x
  45. class InverseResidualBlock(nn.Module):
  46. def __init__(
  47. self,
  48. in_channels: int,
  49. out_channels: int,
  50. expansion_factor: int = 6,
  51. stride: int = 1,
  52. ):
  53. """Constructs a inverse residual block with depthwise seperable convolution
  54. Args:
  55. in_channels (int): input channels
  56. out_channels (int): output channels
  57. expansion_factor (int, optional): Calculating the input & output channel for depthwise convolution by multiplying the expansion factor with input channels. Defaults to 6.
  58. stride (int, optional): stride paramemeter for depthwise convolution. Defaults to 1.
  59. CSDN:Snu77
  60. """
  61. super().__init__()
  62. hidden_channels = in_channels * expansion_factor
  63. self.residual = in_channels == out_channels and stride == 1
  64. self.conv1 = (
  65. ConvNormReLUBlock(in_channels, hidden_channels, (1, 1))
  66. if in_channels != hidden_channels
  67. else nn.Identity() # If it's not the first layer, then we need to add a 1x1 convolutional layer to expand the number of channels
  68. )
  69. self.depthwise_conv = ConvNormReLUBlock(
  70. hidden_channels,
  71. hidden_channels,
  72. (3, 3),
  73. stride=stride,
  74. padding=1,
  75. groups=hidden_channels,
  76. )
  77. self.conv2 = ConvNormReLUBlock(
  78. hidden_channels, out_channels, (1, 1), activation=nn.Identity
  79. )
  80. def forward(self, x):
  81. """Perform forward pass."""
  82. identity = x
  83. x = self.conv1(x)
  84. x = self.depthwise_conv(x)
  85. x = self.conv2(x)
  86. if self.residual:
  87. x = torch.add(x, identity)
  88. return x
  89. class MobileNetV2(nn.Module):
  90. def __init__(
  91. self,
  92. input_channel: int = 3,
  93. depth_multiplier: float = 1,
  94. ):
  95. """Constructs MobileNetV2 architecture
  96. Args:
  97. n_classes (int, optional): output neuron in last layer. Defaults to 1000.
  98. input_channel (int, optional): input channels in first conv layer. Defaults to 3.
  99. dropout (float, optional): dropout in last layer. Defaults to 0.2.
  100. """
  101. super().__init__()
  102. # The configuration of MobileNetV2
  103. # input channels, expansion factor, output channels, repeat, stride,
  104. config = (
  105. (32, 1, 16, 1, 1),
  106. (16, 6, 24, 2, 2),
  107. (24, 6, 32, 3, 2),
  108. (32, 6, 64, 4, 2),
  109. (64, 6, 96, 3, 1),
  110. (96, 6, 160, 3, 2),
  111. (160, 6, 320, 1, 1),
  112. )
  113. layers = [
  114. ConvNormReLUBlock(input_channel, int(32 * depth_multiplier), (3, 3), stride=2, padding=1)
  115. ]
  116. # 遍历配置并添加 InverseResidualBlock 层
  117. for in_channels, expansion_factor, out_channels, repeat, stride in config: # repeat不放缩了已经足够轻量化了
  118. for _ in range(repeat):
  119. layers.append(
  120. InverseResidualBlock(
  121. in_channels=int(in_channels * depth_multiplier),
  122. out_channels=int(out_channels * depth_multiplier),
  123. expansion_factor=expansion_factor,
  124. stride=stride,
  125. )
  126. )
  127. in_channels = out_channels # 更新输入通道
  128. stride = 1 # 重复层的 stride 设为 1
  129. # 将层列表转换为 nn.Sequential
  130. self.model = nn.Sequential(*layers)
  131. self.width_list = [i.size(1) for i in self.forward(torch.randn(1, 3, 640, 640))]
  132. def forward(self, x):
  133. """Perform forward pass."""
  134. unique_tensors = {}
  135. for model in self.model:
  136. x = model(x)
  137. width, height = x.shape[2], x.shape[3]
  138. unique_tensors[(width, height)] = x
  139. result_list = list(unique_tensors.values())[-4:]
  140. return result_list
  141. def MobileNetV2_n(width_mult=0.5):
  142. model = MobileNetV2(depth_multiplier=0.25)
  143. return model
  144. def MobileNetV2_s(width_mult=1.0):
  145. model = MobileNetV2(depth_multiplier=0.5)
  146. return model
  147. def MobileNetV2_m(width_mult=1.5):
  148. model = MobileNetV2(depth_multiplier=1)
  149. return model
  150. if __name__ == "__main__":
  151. # Generating Sample image
  152. image_size = (1, 3, 224, 224)
  153. image = torch.rand(*image_size)
  154. # Model
  155. mobilenet_v2 = MobileNetV2()
  156. out = mobilenet_v2(image)
  157. for i in range(len(out)):
  158. print(out[i].size())


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

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


五、MobileNetV2的yaml文件

5.1 yaml文件

训练信息:YOLO11-MobileNetV2 summary: 432 layers, 1,630,183 parameters, 1,630,167 gradients, 3.9 GFLOPs

我提供了三个版本分别是对应YOLOv8n v8s v8m。 MobileNetV2_n, MobileNetV2_s, MobileNetV2_m
  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。 MobileNetV2_n, MobileNetV2_s, MobileNetV2_m
  13. # YOLO11n backbone
  14. backbone:
  15. # [from, repeats, module, args]
  16. - [-1, 1, MobileNetV2_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分,后期我会根据各种最新的前沿顶会进行论文复现,也会对一些老的改进机制进行补充 如果大家觉得本文帮助到你了,订阅本专栏,关注后续更多的更新~

​​​