一、本文内容
本文给大家带来的最新改进内容是 ShuffleNetV2融合CCFM ,这是一种为移动设备设计的高效 CNN 架构。其在ShuffleNetV1的基础上强调除了FLOPs之外,还应考虑速度、内存访问成本和平台特性。(我在YOLOv11n上修改该主干 降低了GFLOPs , 参数量也有大幅度下降,其 非常适合轻量化的读者来使用,同时精度也有一定程度的上涨 )。本文通过介绍其主要框架原理,然后教你如何添加该网络结构到网络 模型 中。
| 此版本训练信息:YOLO11-shuffleNetV2-CCFM summary: 412 layers, 930,178 parameters, 930,162 gradients, 3.1 GFLOPs |
| 基础版本:YOLO11 summary: 319 layers, 2,591,010 parameters, 2,590,994 gradients, 6.4 GFLOPs |
二、ShuffleNetV2框架原理
官方论文地址: 官方论文地址
官方代码地址: 官方代码地址
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)合并特征。
三、ShuffleNetV2核心代码
下面的代码是整个ShuffleNetV1的核心代码,其中有个版本,对应的GFLOPs也不相同,使用方式看章节四。
- import torch
- import torch.nn as nn
- __all__ = [
- "shufflenetv2_05", "shufflenetv2_10", "shufflenetv2_15", "shufflenetv2_20",
- ]
- def conv_bn(inp, oup, stride):
- return nn.Sequential(
- nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
- nn.BatchNorm2d(oup),
- nn.ReLU(inplace=True)
- )
- def conv_1x1_bn(inp, oup):
- return nn.Sequential(
- nn.Conv2d(inp, oup, 1, 1, 0, bias=False),
- nn.BatchNorm2d(oup),
- nn.ReLU(inplace=True)
- )
- def channel_shuffle(x, groups):
- batchsize, num_channels, height, width = x.data.size()
- channels_per_group = num_channels // groups
- # reshape
- x = x.view(batchsize, groups,
- channels_per_group, height, width)
- x = torch.transpose(x, 1, 2).contiguous()
- # flatten
- x = x.view(batchsize, -1, height, width)
- return x
- class InvertedResidual(nn.Module):
- def __init__(self, inp, oup, stride, benchmodel):
- super(InvertedResidual, self).__init__()
- self.benchmodel = benchmodel
- self.stride = stride
- assert stride in [1, 2]
- oup_inc = oup // 2
- if self.benchmodel == 1:
- # assert inp == oup_inc
- self.banch2 = nn.Sequential(
- # pw
- nn.Conv2d(oup_inc, oup_inc, 1, 1, 0, bias=False),
- nn.BatchNorm2d(oup_inc),
- nn.ReLU(inplace=True),
- # dw
- nn.Conv2d(oup_inc, oup_inc, 3, stride, 1, groups=oup_inc, bias=False),
- nn.BatchNorm2d(oup_inc),
- # pw-linear
- nn.Conv2d(oup_inc, oup_inc, 1, 1, 0, bias=False),
- nn.BatchNorm2d(oup_inc),
- nn.ReLU(inplace=True),
- )
- else:
- self.banch1 = nn.Sequential(
- # dw
- nn.Conv2d(inp, inp, 3, stride, 1, groups=inp, bias=False),
- nn.BatchNorm2d(inp),
- # pw-linear
- nn.Conv2d(inp, oup_inc, 1, 1, 0, bias=False),
- nn.BatchNorm2d(oup_inc),
- nn.ReLU(inplace=True),
- )
- self.banch2 = nn.Sequential(
- # pw
- nn.Conv2d(inp, oup_inc, 1, 1, 0, bias=False),
- nn.BatchNorm2d(oup_inc),
- nn.ReLU(inplace=True),
- # dw
- nn.Conv2d(oup_inc, oup_inc, 3, stride, 1, groups=oup_inc, bias=False),
- nn.BatchNorm2d(oup_inc),
- # pw-linear
- nn.Conv2d(oup_inc, oup_inc, 1, 1, 0, bias=False),
- nn.BatchNorm2d(oup_inc),
- nn.ReLU(inplace=True),
- )
- @staticmethod
- def _concat(x, out):
- # concatenate along channel axis
- return torch.cat((x, out), 1)
- def forward(self, x):
- if 1 == self.benchmodel:
- x1 = x[:, :(x.shape[1] // 2), :, :]
- x2 = x[:, (x.shape[1] // 2):, :, :]
- out = self._concat(x1, self.banch2(x2))
- elif 2 == self.benchmodel:
- out = self._concat(self.banch1(x), self.banch2(x))
- return channel_shuffle(out, 2)
- class ShuffleNetV2(nn.Module):
- def __init__(self, n_class=1000, input_size=224, width_mult=1.):
- super(ShuffleNetV2, self).__init__()
- assert input_size % 32 == 0
- self.stage_repeats = [8, 4, 4]
- # index 0 is invalid and should never be called.
- # only used for indexing convenience.
- if width_mult == 0.5:
- self.stage_out_channels = [-1, 24, 48, 96, 192, 1024]
- elif width_mult == 1.0:
- self.stage_out_channels = [-1, 24, 116, 232, 464, 1024]
- elif width_mult == 1.5:
- self.stage_out_channels = [-1, 24, 176, 352, 704, 1024]
- elif width_mult == 2.0:
- self.stage_out_channels = [-1, 24, 224, 488, 976, 2048]
- else:
- raise ValueError(
- """groups is not supported for
- 1x1 Grouped Convolutions""")
- # building first layer
- input_channel = self.stage_out_channels[1]
- self.conv1 = conv_bn(3, input_channel, 2)
- self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
- self.features = []
- # building inverted residual blocks
- for idxstage in range(len(self.stage_repeats)):
- numrepeat = self.stage_repeats[idxstage]
- output_channel = self.stage_out_channels[idxstage + 2]
- for i in range(numrepeat):
- if i == 0:
- # inp, oup, stride, benchmodel):
- self.features.append(InvertedResidual(input_channel, output_channel, 2, 2))
- else:
- self.features.append(InvertedResidual(input_channel, output_channel, 1, 1))
- input_channel = output_channel
- # make it nn.Sequential
- self.features = nn.Sequential(*self.features)
- self.index = self.stage_out_channels[2: 2 + len(self.stage_repeats)]
- self.width_list = [i.size(1) for i in self.forward(torch.randn(1, 3, 640, 640))]
- def forward(self, x):
- x = self.conv1(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 shufflenetv2_05(width_mult=0.5):
- model = ShuffleNetV2(width_mult=width_mult)
- return model
- def shufflenetv2_10(width_mult=1.0):
- model = ShuffleNetV2(width_mult=width_mult)
- return model
- def shufflenetv2_15(width_mult=1.5):
- model = ShuffleNetV2(width_mult=width_mult)
- return model
- def shufflenetv2_20(width_mult=2.0):
- model = ShuffleNetV2(width_mult=width_mult)
- return model
- if __name__ == "__main__":
- # Generating Sample image
- image_size = (1, 3, 640, 640)
- image = torch.rand(*image_size)
- # Model
- mobilenet_v1 = shufflenetv2_20()
- out = mobilenet_v1(image)
- for i in range(len(out)):
- print(out[i].size())
四、手把手教你添加 ShuffleNetV2网络结构
这个主干的网络结构添加起来算是所有的改进机制里最麻烦的了,因为有一些网略结构可以用yaml文件搭建出来,有一些网络结构其中的一些细节根本没有办法用yaml文件去搭建,用yaml文件去搭建会损失一些细节部分(而且一个网络结构设计很多细节的结构修改方式都不一样,一个一个去修改大家难免会出错),所以这里让网络直接返回整个网络,然后修改部分 yolo代码以后就都以这种形式添加了,以后我提出的网络模型基本上都会通过这种方式修改,我也会进行一些模型细节改进。创新出新的网络结构大家直接拿来用就可以的。 下面开始添加教程->
(同时每一个后面都有代码,大家拿来复制粘贴替换即可,但是要看好了不要复制粘贴替换多了)
4.1 修改一
我们复制网络结构代码到“ ultralytics /nn”目录下创建一个py文件复制粘贴进去 ,我这里起的名字是ShuffleNetV2。
4.2 修改二
第二步我们在该目录下创建一个新的py文件名字为'__init__.py'( 用群内的文件的话已经有了无需新建) ,然后在其内部导入我们的检测头如下图所示。
4.3 修改三
第三步我门中到如下文件'ultralytics/nn/tasks.py'进行导入和注册我们的模块( 用群内的文件的话已经有了无需重新导入直接开始第四步即可) !
从今天开始以后的教程就都统一成这个样子了,因为我默认大家用了我群内的文件来进行修改!!
4.4 修改四
添加如下两行代码!!!
4.5 修改五
找到七百多行大概把具体看图片,按照图片来修改就行,添加红框内的部分,注意没有()只是 函数 名,我这里只添加了部分的版本,大家有兴趣这个ShuffleNetV2还有更多的版本可以添加,看我给的代码函数头即可。
- elif m in {自行添加对应的模型即可,下面都是一样的}:
- m = m()
- 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 修改七
如下的也需要修改,全部按照我的来。
代码如下把原先的代码替换了即可。
- 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文件都是同一个文件。 同时这个部分有好几个前向传播都很相似,大家不要看错了, 是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
到这里就完成了修改部分,但是这里面细节很多,大家千万要注意不要替换多余的代码,导致报错,也不要拉下任何一部,都会导致运行失败,而且报错很难排查!!!很难排查!!!
4.9 修改九
我们找到如下文件'ultralytics/utils/torch_utils.py'按照如下的图片进行修改,否则容易打印不出来计算量。
五、CCFM-ShuffleNetV2的yaml文件
复制如下yaml文件进行运行!!!
此版本训练信息:YOLO11-shuffleNetV2-CCFM summary: 412 layers, 930,178 parameters, 930,162 gradients, 3.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. '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
- # 共四个版本 "shufflenetv2_05", "shufflenetv2_10", "shufflenetv2_15", "shufflenetv2_20"
- # YOLO11n backbone
- backbone:
- # [from, repeats, module, args]
- - [-1, 1, shufflenetv2_05, []] # 0-4 P1/2
- # - [-1, 1, shufflenetv2_10, []] # 0-4 P1/2
- # - [-1, 1, shufflenetv2_15, []] # 0-4 P1/2
- # - [-1, 1, shufflenetv2_20, []] # 0-4 P1/2
- - [-1, 1, SPPF, [1024, 5]] # 5
- - [-1, 2, C2PSA, [1024]] # 6
- # YOLOv11.0n head
- head:
- - [-1, 1, Conv, [256, 1, 1]] # 7, Y5, lateral_convs.0
- - [-1, 1, nn.Upsample, [None, 2, 'nearest']]
- - [3, 1, Conv, [256, 1, 1, None, 1, 1, False]] # 9 input_proj.1
- - [[-2, -1], 1, Concat, [1]]
- - [-1, 2, C3k2, [256, False]] # 11, fpn_blocks.0
- - [-1, 1, Conv, [256, 1, 1]] # 12, Y4, lateral_convs.1
- - [-1, 1, nn.Upsample, [None, 2, 'nearest']]
- - [2, 1, Conv, [256, 1, 1, None, 1, 1, False]] # 14 input_proj.0
- - [[-2, -1], 1, Concat, [1]] # cat backbone P4
- - [-1, 2, C3k2, [256, False]] # X3 (16), fpn_blocks.1
- - [-1, 1, Conv, [256, 3, 2]] # 17, downsample_convs.0
- - [[-1, 12], 1, Concat, [1]] # cat Y4
- - [-1, 2, C3k2, [256, False]] # F4 (19), pan_blocks.0
- - [-1, 1, SCDown, [256, 3, 2]] # 20, downsample_convs.1
- - [[-1, 7], 1, Concat, [1]] # cat Y5
- - [-1, 2, C3k2, [256, True]] # F5 (22), pan_blocks.1
- - [[16, 19, 22], 1, Detect, [nc]] # Detect(P3, P4, P5)
六、成功运行记录
下面是成功运行的截图,已经完成了有1个epochs的训练,图片太大截不全第2个epochs了。
七、本文总结
到此本文的正式分享内容就结束了,在这里给大家推荐我的YOLOv11改进有效涨点专栏,本专栏目前为新开的平均质量分98分,后期我会根据各种最新的前沿顶会进行论文复现,也会对一些老的改进机制进行补充, 目前本专栏免费阅读(暂时,大家尽早关注不迷路~), 如果大家觉得本文帮助到你了,订阅本专栏,关注后续更多的更新~