一、本文介绍
本文给大家带来的最新改进机制是 二次创新 的机制,二次创新是我们发表论文中关键的一环,为什么这么说,从去年的三月份开始对于图像领域的论文发表其实是变难的了,在那之前大家可能搭搭积木的情况下就可以简单的发表一篇论文,但是从去年开始单纯的搭积木其实发表论文变得越来越难,所以这个时候就需要二次创新,以此来迷惑审稿人,彰显大家的工作量,所以二次创新是非常重要的一点,因为二次创新出来的模块其实基本上就可以算作一个全新的模块了, 本文内容经过YOLOv8专栏很多读者反应效果很好, 同时本文含如何二次创新的思路。
欢迎大家订阅我的专栏一起学习YOLO!
二、如何进行二次创新
这里给大家介绍以下如何进行二次创新。
我的视频中说过二次创新主要分为两种,本文介绍的是另外一种。
组合为: 一种全新的结构 + 其他模块(可以是 卷积 ,也可以是注意力机制,也可以是重参数化模块)
iRMB主要提出了一种倒置残差的结构,然后其中涉及到一种 Transformer 注意力机制 ,因为创新注意力机制是十分困难的事情大家都是炼丹师所以这肯定不现实,但是借鉴其中的结构还是一个比较容易的事情,所以我们借鉴了iRMB其中倒置残差结构结合一种即插即用的EMA注意力机制 (也可以替换其它的注意力机制) ,形成一个新的模块iEMA也是一种创新对于写论文来说,总比你单用iRMB或者EMA要好对吧?最起码工作量的方面我们是堆叠上去了。
三、iEMA的核心代码
使用方式看章节四!
- import math
- import torch
- import torch.nn as nn
- from functools import partial
- from einops import rearrange
- from timm.models._efficientnet_blocks import SqueezeExcite
- from timm.models.layers import DropPath
- __all__ = ['iEMA', 'C2PSAiEMA']
- class EMA(nn.Module):
- def __init__(self, channels, factor=32):
- super(EMA, self).__init__()
- self.groups = factor
- assert channels // self.groups > 0
- self.softmax = nn.Softmax(-1)
- self.agp = nn.AdaptiveAvgPool2d((1, 1))
- self.pool_h = nn.AdaptiveAvgPool2d((None, 1))
- self.pool_w = nn.AdaptiveAvgPool2d((1, None))
- self.gn = nn.GroupNorm(channels // self.groups, channels // self.groups)
- self.conv1x1 = nn.Conv2d(channels // self.groups, channels // self.groups, kernel_size=1, stride=1, padding=0)
- self.conv3x3 = nn.Conv2d(channels // self.groups, channels // self.groups, kernel_size=3, stride=1, padding=1)
- def forward(self, x):
- b, c, h, w = x.size()
- group_x = x.reshape(b * self.groups, -1, h, w) # b*g,c//g,h,w
- x_h = self.pool_h(group_x)
- x_w = self.pool_w(group_x).permute(0, 1, 3, 2)
- hw = self.conv1x1(torch.cat([x_h, x_w], dim=2))
- x_h, x_w = torch.split(hw, [h, w], dim=2)
- x1 = self.gn(group_x * x_h.sigmoid() * x_w.permute(0, 1, 3, 2).sigmoid())
- x2 = self.conv3x3(group_x)
- x11 = self.softmax(self.agp(x1).reshape(b * self.groups, -1, 1).permute(0, 2, 1))
- x12 = x2.reshape(b * self.groups, c // self.groups, -1) # b*g, c//g, hw
- x21 = self.softmax(self.agp(x2).reshape(b * self.groups, -1, 1).permute(0, 2, 1))
- x22 = x1.reshape(b * self.groups, c // self.groups, -1) # b*g, c//g, hw
- weights = (torch.matmul(x11, x12) + torch.matmul(x21, x22)).reshape(b * self.groups, 1, h, w)
- return (group_x * weights.sigmoid()).reshape(b, c, h, w)
- inplace = True
- class LayerNorm2d(nn.Module):
- def __init__(self, normalized_shape, eps=1e-6, elementwise_affine=True):
- super().__init__()
- self.norm = nn.LayerNorm(normalized_shape, eps, elementwise_affine)
- def forward(self, x):
- x = rearrange(x, 'b c h w -> b h w c').contiguous()
- x = self.norm(x)
- x = rearrange(x, 'b h w c -> b c h w').contiguous()
- return x
- def get_norm(norm_layer='in_1d'):
- eps = 1e-6
- norm_dict = {
- 'none': nn.Identity,
- 'in_1d': partial(nn.InstanceNorm1d, eps=eps),
- 'in_2d': partial(nn.InstanceNorm2d, eps=eps),
- 'in_3d': partial(nn.InstanceNorm3d, eps=eps),
- 'bn_1d': partial(nn.BatchNorm1d, eps=eps),
- 'bn_2d': partial(nn.BatchNorm2d, eps=eps),
- # 'bn_2d': partial(nn.SyncBatchNorm, eps=eps),
- 'bn_3d': partial(nn.BatchNorm3d, eps=eps),
- 'gn': partial(nn.GroupNorm, eps=eps),
- 'ln_1d': partial(nn.LayerNorm, eps=eps),
- 'ln_2d': partial(LayerNorm2d, eps=eps),
- }
- return norm_dict[norm_layer]
- def get_act(act_layer='relu'):
- act_dict = {
- 'none': nn.Identity,
- 'relu': nn.ReLU,
- 'relu6': nn.ReLU6,
- 'silu': nn.SiLU
- }
- return act_dict[act_layer]
- class ConvNormAct(nn.Module):
- def __init__(self, dim_in, dim_out, kernel_size, stride=1, dilation=1, groups=1, bias=False,
- skip=False, norm_layer='bn_2d', act_layer='relu', inplace=True, drop_path_rate=0.):
- super(ConvNormAct, self).__init__()
- self.has_skip = skip and dim_in == dim_out
- padding = math.ceil((kernel_size - stride) / 2)
- self.conv = nn.Conv2d(dim_in, dim_out, kernel_size, stride, padding, dilation, groups, bias)
- self.norm = get_norm(norm_layer)(dim_out)
- self.act = get_act(act_layer)(inplace=inplace)
- self.drop_path = DropPath(drop_path_rate) if drop_path_rate else nn.Identity()
- def forward(self, x):
- shortcut = x
- x = self.conv(x)
- x = self.norm(x)
- x = self.act(x)
- if self.has_skip:
- x = self.drop_path(x) + shortcut
- return x
- class iEMA(nn.Module):
- def __init__(self, dim_in, norm_in=True, has_skip=True, exp_ratio=1.0, norm_layer='bn_2d',
- act_layer='relu', v_proj=True, dw_ks=3, stride=1, dilation=1, se_ratio=0.0,
- attn_s=True, qkv_bias=False, drop=0., drop_path=0.):
- super().__init__()
- dim_out = dim_in
- self.norm = get_norm(norm_layer)(dim_in) if norm_in else nn.Identity()
- dim_mid = int(dim_in * exp_ratio)
- self.has_skip = (dim_in == dim_out and stride == 1) and has_skip
- self.attn_s = attn_s
- if self.attn_s:
- self.ema = EMA(dim_in)
- else:
- if v_proj:
- self.v = ConvNormAct(dim_in, dim_mid, kernel_size=1, bias=qkv_bias, norm_layer='none',
- act_layer=act_layer, inplace=inplace)
- else:
- self.v = nn.Identity()
- self.conv_local = ConvNormAct(dim_mid, dim_mid, kernel_size=dw_ks, stride=stride, dilation=dilation,
- groups=dim_mid, norm_layer='bn_2d', act_layer='silu', inplace=inplace)
- self.se = SqueezeExcite(dim_mid, rd_ratio=se_ratio, act_layer=get_act(act_layer)) if se_ratio > 0.0 else nn.Identity()
- self.proj_drop = nn.Dropout(drop)
- self.proj = ConvNormAct(dim_mid, dim_out, kernel_size=1, norm_layer='none', act_layer='none', inplace=inplace)
- self.drop_path = DropPath(drop_path) if drop_path else nn.Identity()
- def forward(self, x):
- shortcut = x
- x = self.norm(x)
- if self.attn_s:
- x = self.ema(x)
- else:
- x = self.v(x)
- x = x + self.se(self.conv_local(x)) if self.has_skip else self.se(self.conv_local(x))
- x = self.proj_drop(x)
- x = self.proj(x)
- x = (shortcut + self.drop_path(x)) if self.has_skip else x
- return x
- def autopad(k, p=None, d=1): # kernel, padding, dilation
- """Pad to 'same' shape outputs."""
- if d > 1:
- k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size
- if p is None:
- p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
- return p
- class Conv(nn.Module):
- """Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation)."""
- default_act = nn.SiLU() # default activation
- def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
- """Initialize Conv layer with given arguments including activation."""
- super().__init__()
- self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
- self.bn = nn.BatchNorm2d(c2)
- self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
- def forward(self, x):
- """Apply convolution, batch normalization and activation to input tensor."""
- return self.act(self.bn(self.conv(x)))
- def forward_fuse(self, x):
- """Perform transposed convolution of 2D data."""
- return self.act(self.conv(x))
- class PSABlock(nn.Module):
- """
- PSABlock class implementing a Position-Sensitive Attention block for neural networks.
- This class encapsulates the functionality for applying multi-head attention and feed-forward neural network layers
- with optional shortcut connections.
- Attributes:
- attn (Attention): Multi-head attention module.
- ffn (nn.Sequential): Feed-forward neural network module.
- add (bool): Flag indicating whether to add shortcut connections.
- Methods:
- forward: Performs a forward pass through the PSABlock, applying attention and feed-forward layers.
- Examples:
- Create a PSABlock and perform a forward pass
- """
- def __init__(self, c, attn_ratio=0.5, num_heads=4, shortcut=True) -> None:
- """Initializes the PSABlock with attention and feed-forward layers for enhanced feature extraction."""
- super().__init__()
- self.attn = iEMA(c)
- self.ffn = nn.Sequential(Conv(c, c * 2, 1), Conv(c * 2, c, 1, act=False))
- self.add = shortcut
- def forward(self, x):
- """Executes a forward pass through PSABlock, applying attention and feed-forward layers to the input tensor."""
- x = x + self.attn(x) if self.add else self.attn(x)
- x = x + self.ffn(x) if self.add else self.ffn(x)
- return x
- class C2PSAiEMA(nn.Module):
- """
- C2PSA module with attention mechanism for enhanced feature extraction and processing.
- This module implements a convolutional block with attention mechanisms to enhance feature extraction and processing
- capabilities. It includes a series of PSABlock modules for self-attention and feed-forward operations.
- Attributes:
- c (int): Number of hidden channels.
- cv1 (Conv): 1x1 convolution layer to reduce the number of input channels to 2*c.
- cv2 (Conv): 1x1 convolution layer to reduce the number of output channels to c.
- m (nn.Sequential): Sequential container of PSABlock modules for attention and feed-forward operations.
- Methods:
- forward: Performs a forward pass through the C2PSA module, applying attention and feed-forward operations.
- Notes:
- This module essentially is the same as PSA module, but refactored to allow stacking more PSABlock modules.
- Examples:
- """
- def __init__(self, c1, c2, n=1, e=0.5):
- """Initializes the C2PSA module with specified input/output channels, number of layers, and expansion ratio."""
- super().__init__()
- assert c1 == c2
- self.c = int(c1 * e)
- self.cv1 = Conv(c1, 2 * self.c, 1, 1)
- self.cv2 = Conv(2 * self.c, c1, 1)
- self.m = nn.Sequential(*(PSABlock(self.c, attn_ratio=0.5, num_heads=self.c // 64) for _ in range(n)))
- def forward(self, x):
- """Processes the input tensor 'x' through a series of PSA blocks and returns the transformed tensor."""
- a, b = self.cv1(x).split((self.c, self.c), dim=1)
- b = self.m(b)
- return self.cv2(torch.cat((a, b), 1))
- if __name__ == "__main__":
- # Generating Sample image
- image_size = (1, 64, 640, 640)
- image = torch.rand(*image_size)
- # Model
- model = C2PSAiEMA(64, 64)
- out = model(image)
- print(out.size())
四、添加教程
4.1 修改一
第一还是建立文件,我们找到如下 ultralytics /nn文件夹下建立一个目录名字呢就是'Addmodules'文件夹( 用群内的文件的话已经有了无需新建) !然后在其内部建立一个新的py文件将核心代码复制粘贴进去即可。
4.2 修改二
第二步我们在该目录下创建一个新的py文件名字为'__init__.py'( 用群内的文件的话已经有了无需新建) ,然后在其内部导入我们的检测头如下图所示。
4.3 修改三
第三步我门中到如下文件'ultralytics/nn/tasks.py'进行导入和注册我们的模块( 用群内的文件的话已经有了无需重新导入直接开始第四步即可) !
4.4 修改四
按照我的添加在parse_model里添加即可。
到此就修改完成了,大家可以复制下面的yaml文件运行。
五、正式训练
5.1 yaml文件1
训练信息:YOLO11-C2PSA-iEMA summary: 330 layers, 2,556,931 parameters, 2,556,915 gradients, 6.4 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
- # YOLO11n backbone
- backbone:
- # [from, repeats, module, args]
- - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2
- - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4
- - [-1, 2, C3k2, [256, False, 0.25]]
- - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8
- - [-1, 2, C3k2, [512, False, 0.25]]
- - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16
- - [-1, 2, C3k2, [512, True]]
- - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32
- - [-1, 2, C3k2, [1024, True]]
- - [-1, 1, SPPF, [1024, 5]] # 9
- - [-1, 2, C2PSAiEMA, [1024]] # 10
- # YOLO11n head
- head:
- - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
- - [[-1, 6], 1, Concat, [1]] # cat backbone P4
- - [-1, 2, C3k2, [512, False]] # 13
- - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
- - [[-1, 4], 1, Concat, [1]] # cat backbone P3
- - [-1, 2, C3k2, [256, False]] # 16 (P3/8-small)
- - [-1, 1, Conv, [256, 3, 2]]
- - [[-1, 13], 1, Concat, [1]] # cat head P4
- - [-1, 2, C3k2, [512, False]] # 19 (P4/16-medium)
- - [-1, 1, Conv, [512, 3, 2]]
- - [[-1, 10], 1, Concat, [1]] # cat head P5
- - [-1, 2, C3k2, [1024, True]] # 22 (P5/32-large)
- - [[16, 19, 22], 1, Detect, [nc]] # Detect(P3, P4, P5)
5.2 yaml文件2
训练信息:YOLO11-iEMA summary: 388 layers, 2,682,771 parameters, 2,682,755 gradients, 6.7 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
- # YOLO11n backbone
- backbone:
- # [from, repeats, module, args]
- - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2
- - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4
- - [-1, 2, C3k2, [256, False, 0.25]]
- - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8
- - [-1, 2, C3k2, [512, False, 0.25]]
- - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16
- - [-1, 2, C3k2, [512, True]]
- - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32
- - [-1, 2, C3k2, [1024, True]]
- - [-1, 1, SPPF, [1024, 5]] # 9
- - [-1, 2, C2PSA, [1024]] # 10
- # YOLO11n head
- head:
- - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
- - [[-1, 6], 1, Concat, [1]] # cat backbone P4
- - [-1, 2, C3k2, [512, False]] # 13
- - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
- - [[-1, 4], 1, Concat, [1]] # cat backbone P3
- - [-1, 2, C3k2, [256, False]] # 16 (P3/8-small)
- - [-1, 1, iEMA, []] # 17 (P3/8-small) 小目标检测层输出位置增加注意力机制
- - [-1, 1, Conv, [256, 3, 2]]
- - [[-1, 13], 1, Concat, [1]] # cat head P4
- - [-1, 2, C3k2, [512, False]] # 20 (P4/16-medium)
- - [-1, 1, iEMA, []] # 21 (P4/16-medium) 中目标检测层输出位置增加注意力机制
- - [-1, 1, Conv, [512, 3, 2]]
- - [[-1, 10], 1, Concat, [1]] # cat head P5
- - [-1, 2, C3k2, [1024, True]] # 24 (P5/32-large)
- - [-1, 1, iEMA, []] # 25 (P5/32-large) 大目标检测层输出位置增加注意力机制
- # 注意力机制我这里其实是添加了三个但是实际一般生效就只添加一个就可以了,所以大家可以自行注释来尝试, 上面三个仅建议大家保留一个, 但是from位置要对齐.
- # 具体在那一层用注意力机制可以根据自己的数据集场景进行选择。
- # 如果你自己配置注意力位置注意from[17, 21, 25]位置要对应上对应的检测层!
- - [[17, 21, 25], 1, Detect, [nc]] # Detect(P3, P4, P5)
5.3 训练代码
大家可以创建一个py文件将我给的代码复制粘贴进去,配置好自己的文件路径即可运行。
- import warnings
- warnings.filterwarnings('ignore')
- from ultralytics import YOLO
- if __name__ == '__main__':
- model = YOLO('模型配置文件')
- # 如何切换模型版本, 上面的ymal文件可以改为 yolov8s.yaml就是使用的v8s,
- # 类似某个改进的yaml文件名称为yolov8-XXX.yaml那么如果想使用其它版本就把上面的名称改为yolov8l-XXX.yaml即可(改的是上面YOLO中间的名字不是配置文件的)!
- # model.load('yolov8n.pt') # 是否加载预训练权重,科研不建议大家加载否则很难提升精度
- model.train(data=r"C:\Users\Administrator\PycharmProjects\yolov5-master\yolov5-master\Construction Site Safety.v30-raw-images_latestversion.yolov8\data.yaml",
- # 如果大家任务是其它的'ultralytics/cfg/default.yaml'找到这里修改task可以改成detect, segment, classify, pose
- cache=False,
- imgsz=640,
- epochs=150,
- single_cls=False, # 是否是单类别检测
- batch=16,
- close_mosaic=0,
- workers=0,
- device='0',
- optimizer='SGD', # using SGD
- # resume='runs/train/exp21/weights/last.pt', # 如过想续训就设置last.pt的地址
- amp=True, # 如果出现训练损失为Nan可以关闭amp
- project='runs/train',
- name='exp',
- )
5.4 训练过程截图
五、本文总结
到此本文的正式分享内容就结束了,在这里给大家推荐我的YOLOv11改进有效涨点专栏,本专栏目前为新开的平均质量分98分,后期我会根据各种最新的前沿顶会进行论文复现,也会对一些老的改进机制进行补充,如果大家觉得本文帮助到你了,订阅本专栏,关注后续更多的更新~