一、本文介绍
本文给大家带来的改进机制是 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的核心代码,大家如果想学习可以和上面的框架原理对比着看一看估计会有一定的收获,使用方式看章节四。
- import torch
- from torch import nn
- __all__ = ['MobileNetV1']
- class DepthwiseSepConvBlock(nn.Module):
- def __init__(
- self,
- in_channels: int,
- out_channels: int,
- stride: int = 1,
- use_relu6: bool = True,
- ):
- """Constructs Depthwise seperable with pointwise convolution with relu and batchnorm respectively.
- Args:
- in_channels (int): input channels for depthwise convolution
- out_channels (int): output channels for pointwise convolution
- stride (int, optional): stride paramemeter for depthwise convolution. Defaults to 1.
- use_relu6 (bool, optional): whether to use standard ReLU or ReLU6 for depthwise separable convolution block. Defaults to True.
- """
- super().__init__()
- # Depthwise conv
- self.depthwise_conv = nn.Conv2d(
- in_channels,
- in_channels,
- (3, 3),
- stride=stride,
- padding=1,
- groups=in_channels,
- )
- self.bn1 = nn.BatchNorm2d(in_channels)
- self.relu1 = nn.ReLU6() if use_relu6 else nn.ReLU()
- # Pointwise conv
- self.pointwise_conv = nn.Conv2d(in_channels, out_channels, (1, 1))
- self.bn2 = nn.BatchNorm2d(out_channels)
- self.relu2 = nn.ReLU6() if use_relu6 else nn.ReLU()
- def forward(self, x):
- """Perform forward pass."""
- x = self.depthwise_conv(x)
- x = self.bn1(x)
- x = self.relu1(x)
- x = self.pointwise_conv(x)
- x = self.bn2(x)
- x = self.relu2(x)
- return x
- class MobileNetV1(nn.Module):
- def __init__(
- self,
- input_channel: int = 3,
- depth_multiplier: float = 1.0,
- use_relu6: bool = True,
- ):
- """Constructs MobileNetV1 architecture
- Args:
- n_classes (int, optional): count of output neuron in last layer. Defaults to 1000.
- input_channel (int, optional): input channels in first conv layer. Defaults to 3.
- depth_multiplier (float, optional): network width multiplier ( width scaling ). Suggested Values - 0.25, 0.5, 0.75, 1.. Defaults to 1.0.
- use_relu6 (bool, optional): whether to use standard ReLU or ReLU6 for depthwise separable convolution block. Defaults to True.
- """
- super().__init__()
- # The configuration of MobileNetV1
- # input channels, output channels, stride
- config = (
- (32, 64, 1),
- (64, 128, 2),
- (128, 128, 1),
- (128, 256, 2),
- (256, 256, 1),
- (256, 512, 2),
- (512, 512, 1),
- (512, 512, 1),
- (512, 512, 1),
- (512, 512, 1),
- (512, 512, 1),
- (512, 1024, 2),
- (1024, 1024, 1),
- )
- self.model = nn.Sequential(
- nn.Conv2d(
- input_channel, int(32 * depth_multiplier), (3, 3), stride=2, padding=1
- )
- )
- # Adding depthwise block in the model from the config
- for in_channels, out_channels, stride in config:
- self.model.append(
- DepthwiseSepConvBlock(
- int(in_channels * depth_multiplier), # input channels
- int(out_channels * depth_multiplier), # output channels
- stride,
- use_relu6=use_relu6,
- )
- )
- self.index = [128, 256, 512, 1024]
- self.width_list = [i.size(1) for i in self.forward(torch.randn(1, 3, 640, 640))]
- def forward(self, x):
- """Perform forward pass."""
- results = [None, None, None, None]
- for model in self.model:
- x = model(x)
- if x.size(1) in self.index:
- position = self.index.index(x.size(1)) # Find the position in the index list
- results[position] = x
- return results
- if __name__ == "__main__":
- # Generating Sample image
- image_size = (1, 3, 224, 224)
- image = torch.rand(*image_size)
- # Model
- mobilenet_v1 = MobileNetV1(depth_multiplier=1)
- out = mobilenet_v1(image)
- print(out)
四、手把手教你添加MobileNetV1网络结构
4.1 修改一
第一步还是建立文件,我们找到如下ultralytics/nn文件夹下建立一个目录名字呢就是'Addmodules'文件夹( 用群内的文件的话已经有了无需新建) !然后在其内部建立一个新的py文件将核心代码复制粘贴进去即可
4.2 修改二
第二步我们在该目录下创建一个新的py文件名字为'__init__.py'( 用群内的文件的话已经有了无需新建) ,然后在其内部导入我们的检测头如下图所示。
4.3 修改三
第三步我门中到如下文件'ultralytics/nn/tasks.py'进行导入和注册我们的模块( 用群内的文件的话已经有了无需重新导入直接开始第四步即可) !
从今天开始以后的教程就都统一成这个样子了,因为我默认大家用了我群内的文件来进行修改!!
4.4 修改四
添加如下两行代码!!!
4.5 修改五
找到七百多行大概把具体看图片,按照图片来修改就行,添加红框内的部分,注意没有()只是 函数 名。
- elif m in {自行添加对应的模型即可,下面都是一样的}:
- m = m(*args)
- c2 = m.width_list # 返回通道列表
- backbone = True
4.6 修改六
下面的两个红框内都是需要改动的。
- if isinstance(c2, list):
- m_ = m
- m_.backbone = True
- else:
- m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
- t = str(m)[8:-2].replace('__main__.', '') # module type
- m.np = sum(x.numel() for x in m_.parameters()) # number params
- 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多行左右的!!!,同时我后面提供了代码,大家直接复制粘贴即可,有时间我针对这里会出一个视频。
代码如下->
- def _predict_once(self, x, profile=False, visualize=False, embed=None):
- """
- Perform a forward pass through the network.
- Args:
- x (torch.Tensor): The input tensor to the model.
- profile (bool): Print the computation time of each layer if True, defaults to False.
- visualize (bool): Save the feature maps of the model if True, defaults to False.
- embed (list, optional): A list of feature vectors/embeddings to return.
- Returns:
- (torch.Tensor): The last output of the model.
- """
- y, dt, embeddings = [], [], [] # outputs
- for m in self.model:
- if m.f != -1: # if not from previous layer
- 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
- if profile:
- self._profile_one_layer(m, x, dt)
- if hasattr(m, 'backbone'):
- x = m(x)
- if len(x) != 5: # 0 - 5
- x.insert(0, None)
- for index, i in enumerate(x):
- if index in self.save:
- y.append(i)
- else:
- y.append(None)
- x = x[-1] # 最后一个输出传给下一层
- else:
- x = m(x) # run
- y.append(x if m.i in self.save else None) # save output
- if visualize:
- feature_visualization(x, m.type, m.i, save_dir=visualize)
- if embed and m.i in embed:
- embeddings.append(nn.functional.adaptive_avg_pool2d(x, (1, 1)).squeeze(-1).squeeze(-1)) # flatten
- if m.i == max(embed):
- return torch.unbind(torch.cat(embeddings, 1), dim=0)
- 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版本.
- # Ultralytics YOLO 🚀, AGPL-3.0 license
- # YOLO11 object detection model with P3-P5 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect
- # Parameters
- nc: 80 # number of classes
- scales: # model compound scaling constants, i.e. 'model=yolo11n.yaml' will call yolo11.yaml with scale 'n'
- # [depth, width, max_channels]
- n: [0.50, 0.25, 1024] # summary: 319 layers, 2624080 parameters, 2624064 gradients, 6.6 GFLOPs
- s: [0.50, 0.50, 1024] # summary: 319 layers, 9458752 parameters, 9458736 gradients, 21.7 GFLOPs
- m: [0.50, 1.00, 512] # summary: 409 layers, 20114688 parameters, 20114672 gradients, 68.5 GFLOPs
- l: [1.00, 1.00, 512] # summary: 631 layers, 25372160 parameters, 25372144 gradients, 87.6 GFLOPs
- x: [1.00, 1.50, 512] # summary: 631 layers, 56966176 parameters, 56966160 gradients, 196.0 GFLOPs
- # 我提供了三个版本分别是对应YOLOv8n v8s v8m。 MobileNetV1_n, MobileNetV1_s, MobileNetV1_m
- # YOLO11n backbone
- backbone:
- # [from, repeats, module, args]
- - [-1, 1, MobileNetV1_n, []] # 0-4 P1/2 这里是四层大家不要被yaml文件限制住了思维,不会画图进群看视频.
- - [-1, 1, SPPF, [1024, 5]] # 5
- - [-1, 2, C2PSA, [1024]] # 6
- # YOLO11n head
- head:
- - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
- - [[-1, 3], 1, Concat, [1]] # cat backbone P4
- - [-1, 2, C3k2, [512, False]] # 9
- - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
- - [[-1, 2], 1, Concat, [1]] # cat backbone P3
- - [-1, 2, C3k2, [256, False]] # 12 (P3/8-small)
- - [-1, 1, Conv, [256, 3, 2]]
- - [[-1, 9], 1, Concat, [1]] # cat head P4
- - [-1, 2, C3k2, [512, False]] # 15 (P4/16-medium)
- - [-1, 1, Conv, [512, 3, 2]]
- - [[-1, 6], 1, Concat, [1]] # cat head P5
- - [-1, 2, C3k2, [1024, True]] # 18 (P5/32-large)
- - [[12, 15, 18], 1, Detect, [nc]] # Detect(P3, P4, P5)
5.2 训练文件的代码
可以复制我的运行文件进行运行。
- import warnings
- warnings.filterwarnings('ignore')
- from ultralytics import YOLO
- if __name__ == '__main__':
- model = YOLO("替换你的yaml文件地址")
- model.load('yolov8n.pt')
- model.train(data=r'你的数据集的地址',
- cache=False,
- imgsz=640,
- epochs=150,
- batch=4,
- close_mosaic=0,
- workers=0,
- device=0,
- optimizer='SGD'
- amp=False,
- )
六、成功运行记录
下面是成功运行的截图,已经完成了有1个epochs的训练,图片太大截不全第2个epochs了。
七、本文总结
到此本文的正式分享内容就结束了,在这里给大家推荐我的YOLOv11改进有效涨点专栏,本专栏目前为新开的平均质量分98分,后期我会根据各种最新的前沿顶会进行论文复现,也会对一些老的改进机制进行补充 , 如果大家觉得本文帮助到你了,订阅本专栏,关注后续更多的更新~