yolov26改进 | 主干/Backbone篇 | 轻量级移动端网络ShuffleNetv1(附代码+修改教程)
开始讲解之前推荐一下我的专栏本专栏的内容支持(分类、检测、分割、追踪、关键点检测),专栏目前为限时折扣欢迎大家订阅本专栏本专栏每周更新5-7篇最新机制更有包含我所有改进的文件和交流群提供给大家本人定期在群内分享发表论文方法和经验。一、本文内容本文给大家带来的改进内容是将ShuffleNetV1 轻量化主干网络融合到 YOLOv26 中主要面向移动端部署、嵌入式设备、低算力平台和实时检测场景进行优化。ShuffleNetV1 本身是一种专门为移动设备设计的高效 CNN 架构它的核心优势在于通过逐点分组卷积降低通道间计算开销再利用通道混洗 Channel Shuffle解决分组卷积带来的信息交流不足问题从而在减少计算量的同时尽量保持特征表达能力。将其替换到 YOLOv26 主干后可以让模型在特征提取阶段更加轻量减少大量不必要的卷积计算更适合部署到边缘设备、无人机、工控设备、移动检测终端等对速度和算力要求比较高的场景。简单来说这个改进相当于给 YOLOv26 换了一个更加省算力的“轻量骨架”在保证检测能力的同时让模型跑得更快、计算压力更小。需要注意的是ShuffleNetV1 在降低GFLOPs方面效果比较明显但由于结构替换和通道设计的原因参数量可能会有一定上涨这也正好可以作为论文中分析轻量化结构取舍的一个点。整体来看该改进的卖点在于结构经典、原理清楚、轻量化方向明确、适合工程部署非常适合用于YOLOv26n 等小模型改进、实时目标检测、移动端检测和低功耗场景检测。本文将从ShuffleNetV1 的主要框架原理出发讲解其逐点分组卷积和通道混洗机制并进一步演示如何将该网络结构添加到 YOLOv26 模型中方便大家在自己的数据集上进行实验对比用来丰富论文改进点和体现模型轻量化优化效果。专栏链接YOLOv26有效涨点专栏包含Conv、注意力机制、主干/Backbone、损失函数、优化器、后处理等改进机制目录一、本文内容二、ShuffleNetV1框架原理​编辑三、ShuffleNetV1核心代码四、手把手教你添加ShuffleNetV1网络结构4.1 修改一4.2 修改二4.3 修改三4.4 修改四4.5 修改五4.6 修改六4.7 修改七4.8 修改八4.9 修改九五、ShuffleNetV1的yaml文件六、成功运行记录七、本文总结二、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也不相同使用方式看章节四。# Copyright 2022 Dakewe Biotech Corporation. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the License); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an AS IS BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from typing import Any, List, Optional import torch from torch import Tensor from torch import nn __all__ [ ShuffleNetV1, shufflenet_v1_x0_5, shufflenet_v1_x1_0, shufflenet_v1_x1_5, shufflenet_v1_x2_0, ] class ShuffleNetV1(nn.Module): def __init__( self, repeats_times: List[int], stages_out_channels: List[int], groups: int 8, num_classes: int 1000, ) - None: super(ShuffleNetV1, self).__init__() in_channels stages_out_channels[0] self.first_conv nn.Sequential( nn.Conv2d(3, in_channels, (3, 3), (2, 2), (1, 1), biasFalse), nn.BatchNorm2d(in_channels), nn.ReLU(True), ) self.maxpool nn.MaxPool2d((3, 3), (2, 2), (1, 1)) features [] for state_repeats_times_index in range(len(repeats_times)): out_channels stages_out_channels[state_repeats_times_index 1] for i in range(repeats_times[state_repeats_times_index]): stride 2 if i 0 else 1 first_group state_repeats_times_index 0 and i 0 features.append( ShuffleNetV1Unit( in_channels, out_channels, stride, groups, first_group, ) ) in_channels out_channels self.features nn.Sequential(*features) self.globalpool nn.AvgPool2d((7, 7)) self.classifier nn.Sequential( nn.Linear(stages_out_channels[-1], num_classes, biasFalse), ) # Initialize neural network weights self._initialize_weights() self.index stages_out_channels[-3:] self.width_list [i.size(1) for i in self.forward(torch.randn(1, 3, 640, 640))] def forward(self, x: Tensor) - list[Optional[Any]]: x self.first_conv(x) x self.maxpool(x) results [None, None, None, None] for index, model in enumerate(self.features): x model(x) # results.append(x) if index 0: results[index] x if x.size(1) in self.index: position self.index.index(x.size(1)) # Find the position in the index list results[position 1] x return results def _initialize_weights(self) - None: for name, module in self.named_modules(): if isinstance(module, nn.Conv2d): if first in name: nn.init.normal_(module.weight, 0, 0.01) else: nn.init.normal_(module.weight, 0, 1.0 / module.weight.shape[1]) if module.bias is not None: nn.init.constant_(module.bias, 0) elif isinstance(module, nn.BatchNorm2d): nn.init.constant_(module.weight, 1) if module.bias is not None: nn.init.constant_(module.bias, 0.0001) nn.init.constant_(module.running_mean, 0) elif isinstance(module, nn.BatchNorm1d): nn.init.constant_(module.weight, 1) if module.bias is not None: nn.init.constant_(module.bias, 0.0001) nn.init.constant_(module.running_mean, 0) elif isinstance(module, nn.Linear): nn.init.normal_(module.weight, 0, 0.01) if module.bias is not None: nn.init.constant_(module.bias, 0) class ShuffleNetV1Unit(nn.Module): def __init__( self, in_channels: int, out_channels: int, stride: int, groups: int, first_groups: bool False, ) - None: super(ShuffleNetV1Unit, self).__init__() self.stride stride self.groups groups self.first_groups first_groups hidden_channels out_channels // 4 if stride 2: out_channels - in_channels self.branch_proj nn.AvgPool2d((3, 3), (2, 2), (1, 1)) self.branch_main_1 nn.Sequential( # pw nn.Conv2d(in_channels, hidden_channels, (1, 1), (1, 1), (0, 0), groups1 if first_groups else groups, biasFalse), nn.BatchNorm2d(hidden_channels), nn.ReLU(True), # dw nn.Conv2d(hidden_channels, hidden_channels, (3, 3), (stride, stride), (1, 1), groupshidden_channels, biasFalse), nn.BatchNorm2d(hidden_channels), ) self.branch_main_2 nn.Sequential( # pw-linear nn.Conv2d(hidden_channels, out_channels, (1, 1), (1, 1), (0, 0), groupsgroups, biasFalse), nn.BatchNorm2d(out_channels), ) self.relu nn.ReLU(True) def channel_shuffle(self, x): batch_size, channels, height, width x.data.size() assert channels % self.groups 0 group_channels channels // self.groups out x.reshape(batch_size, group_channels, self.groups, height, width) out out.permute(0, 2, 1, 3, 4) out out.reshape(batch_size, channels, height, width) return out def forward(self, x: Tensor) - Tensor: identify x out self.branch_main_1(x) out self.channel_shuffle(out) out self.branch_main_2(out) if self.stride 2: branch_proj self.branch_proj(x) out self.relu(out) out torch.cat([branch_proj, out], 1) return out else: out torch.add(out, identify) out self.relu(out) return out def shufflenet_v1_x0_5(**kwargs: Any) - ShuffleNetV1: model ShuffleNetV1([4, 8, 4], [16, 192, 384, 768], 8, **kwargs) return model def shufflenet_v1_x1_0(**kwargs: Any) - ShuffleNetV1: model ShuffleNetV1([4, 8, 4], [24, 384, 768, 1536], 8, **kwargs) return model def shufflenet_v1_x1_5(**kwargs: Any) - ShuffleNetV1: model ShuffleNetV1([4, 8, 4], [24, 576, 1152, 2304], 8, **kwargs) return model def shufflenet_v1_x2_0(**kwargs: Any) - ShuffleNetV1: model ShuffleNetV1([4, 8, 4], [48, 768, 1536, 3072], 8, **kwargs) return model if __name__ __main__: # Generating Sample image image_size (1, 3, 640, 640) image torch.rand(*image_size) # Model model shufflenet_v1_x0_5() out model(image) 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 修改五找到1600多行大概把具体看图片按照图片来修改就行添加红框内的部分注意没有()只是函数名我这里只添加了部分的版本大家有兴趣这个ShuffleNetV1还有更多的版本可以添加看我给的代码函数头即可。​elif m in {自行添加对应的模型即可下面都是一样的}: m m() c2 m.width_list # 返回通道列表 backbone True4.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, type4.7 修改七如下的也需要修改全部按照我的来。​代码如下把原先的代码替换了即可。if verbose: LOGGER.info(f{i:3}{str(f):20}{n_:3}{m.np:10.0f} {t:45}{str(args):30}) # print 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 layers.append(m_) if i 0: ch [] if isinstance(c2, list): ch.extend(c2) if len(c2) ! 5: ch.insert(0, 0) else: ch.append(c2)4.8 修改八修改七和前面的都不太一样需要修改前向传播中的一个部分 已经离开了parse_model方法了。可以在图片中看代码行数没有离开task.py文件都是同一个文件。 同时这个部分有好几个前向传播都很相似大家不要看错了是160多行左右的不同仓库版本可能有些差异同时我后面提供了代码大家直接复制粘贴即可不会修改联系博主获取视频教程。​​代码如下-def _predict_once(self, x, profileFalse, visualizeFalse, embedNone): 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. visualize (bool): Save the feature maps of the model if True. embed (list, optional): A list of layer indices to return embeddings from. Returns: (torch.Tensor): The last output of the model. y, dt, embeddings [], [], [] # outputs embed frozenset(embed) if embed is not None else {-1} max_idx max(embed) 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_dirvisualize) 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_idx: return torch.unbind(torch.cat(embeddings, 1), dim0) return x4.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# 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. modelyolo11n.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 # 共四个版本 shufflenet_v1_x0_5, shufflenet_v1_x1_0, shufflenet_v1_x1_5, shufflenet_v1_x2_0 # YOLO11n backbone backbone: # [from, repeats, module, args] - [-1, 1, shufflenet_v1_x0_5, []] # 0-4 P1/2 - [-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)六、成功运行记录下面是成功运行的截图已经完成了有1个epochs的训练图片太大截不全第2个epochs了。​七、本文总结到此本文的正式分享内容就结束了在这里给大家推荐我的YOLOv26改进有效涨点专栏本专栏目前为新开的平均质量分98分后期我会根据各种最新的前沿顶会进行论文复现也会对一些老的改进机制进行补充目前本专栏免费阅读(暂时大家尽早关注不迷路~)如果大家觉得本文帮助到你了订阅本专栏关注后续更多的更新~专栏链接YOLOv26有效涨点专栏包含Conv、注意力机制、主干/Backbone、损失函数、优化器、后处理等改进机制​​

相关新闻