一、本文介绍
本文给大家带来的最新改进机制是Multi-scaleAttentionNetworkforSingleImageSuper-Resolution提出的 MAB 模块, 其旨在提升单图像超分辨率(SISR)任务中的特征提取能力。 与传统的RCAN(Residual Channel Attention Network)风格模块不同,MAB结合了MetaFormer结构,使得 特征提取 过程更具有效率和 适应性 。MAB包括两大核心模块:多尺度大核注意力 (MLKA) 和门控空间注意力单元 (GSAU)。总的来说,MAB通过多尺度和大核注意力机制的结合,以及门控空间注意力单元的引入,在高效特征提取的基础上提升了 超分辨率任务中 的图像细节恢复效果, 本文内容含多种二次创新C3k2,为我个人独家整理。
欢迎大家订阅我的专栏一起学习YOLO!
二、原理介绍
官方论文地址: 官方论文地址点击此处即可跳转
官方代码地址: 官方代码地址点击此处即可跳转
多尺度注意力块 (MAB)机制的主要内容:
1. 设计思路:
- MAB的设计受到了最新Transformer架构的启发,旨在提升单图像超分辨率(SISR)任务中的特征提取能力。与传统的RCAN(Residual Channel Attention Network)风格模块不同,MAB结合了MetaFormer结构,使得特征提取过程更具有效率和适应性。
2. 结构组成:
- MAB包括两大核心模块:多尺度大核注意力 (MLKA) 和门控空间注意力单元 (GSAU)。MLKA用于捕获不同尺度的相关性,GSAU则聚焦于通过空间门控机制来提升特征聚合能力,尤其是在空间信息的处理上更具优势。
3.操作流程:
- 在MAB中,输入特征首先通过层归一化(Layer Normalization,LN)处理,接着依次通过MLKA和GSAU模块进行特征增强。整个过程包括以下步骤:
- 使用MLKA模块以大核卷积捕获长距离依赖关系,同时通过多尺度和门控机制整合不同尺度的信息。
- 在GSAU模块中引入门控机制与空间注意力,从而在减少不必要的计算层(如线性层)的基础上聚合有效的空间上下文。
4. 优势与性能:
- MAB的MetaFormer结构相比传统的RCAN风格更高效,在保持性能的同时减小了模型计算量。实验结果表明,使用MetaFormer结构的MAB比RCAN结构在超分辨率任务中表现更好,尤其是在图像细节恢复和模型复杂度之间取得了良好的平衡。
5. 组件优化:
- MAB中的MLKA组件通过大核分解捕获长距离和局部信息,而GSAU组件通过门控机制进一步优化了空间信息的聚合,这些设计有效地减少了参数量并提升了模型在超分辨率任务中的表现。
总的来说,MAB通过多尺度和大核注意力机制的结合,以及门控空间注意力单元的引入,在高效特征提取的基础上提升了 超分辨率任务中 的图像细节恢复效果。
三、核心代码
核心代码的使用方式看章节四!
- # -*- coding: utf-8 -*-
- import math
- import torch
- import torch.nn as nn
- import torch.nn.functional as F
- from basicsr.utils.registry import ARCH_REGISTRY
- # LKA from VAN (https://github.com/Visual-Attention-Network)
- class LKA(nn.Module):
- def __init__(self, dim):
- super().__init__()
- self.conv0 = nn.Conv2d(dim, dim, 7, padding=7 // 2, groups=dim)
- self.conv_spatial = nn.Conv2d(dim, dim, 9, stride=1, padding=((9 // 2) * 4), groups=dim, dilation=4)
- self.conv1 = nn.Conv2d(dim, dim, 1)
- def forward(self, x):
- u = x.clone()
- attn = self.conv0(x)
- attn = self.conv_spatial(attn)
- attn = self.conv1(attn)
- return u * attn
- class Attention(nn.Module):
- def __init__(self, n_feats):
- super().__init__()
- self.norm = LayerNorm(n_feats, data_format='channels_first')
- self.scale = nn.Parameter(torch.zeros((1, n_feats, 1, 1)), requires_grad=True)
- self.proj_1 = nn.Conv2d(n_feats, n_feats, 1)
- self.spatial_gating_unit = LKA(n_feats)
- self.proj_2 = nn.Conv2d(n_feats, n_feats, 1)
- def forward(self, x):
- shorcut = x.clone()
- x = self.proj_1(self.norm(x))
- x = self.spatial_gating_unit(x)
- x = self.proj_2(x)
- x = x * self.scale + shorcut
- return x
- # ----------------------------------------------------------------------------------------------------------------
- class MLP(nn.Module):
- def __init__(self, n_feats):
- super().__init__()
- self.norm = LayerNorm(n_feats, data_format='channels_first')
- self.scale = nn.Parameter(torch.zeros((1, n_feats, 1, 1)), requires_grad=True)
- i_feats = 2 * n_feats
- self.fc1 = nn.Conv2d(n_feats, i_feats, 1, 1, 0)
- self.act = nn.GELU()
- self.fc2 = nn.Conv2d(i_feats, n_feats, 1, 1, 0)
- def forward(self, x):
- shortcut = x.clone()
- x = self.norm(x)
- x = self.fc1(x)
- x = self.act(x)
- x = self.fc2(x)
- return x * self.scale + shortcut
- class CFF(nn.Module):
- def __init__(self, n_feats, drop=0.0, k=2, squeeze_factor=15, attn='GLKA'):
- super().__init__()
- i_feats = n_feats * 2
- self.Conv1 = nn.Conv2d(n_feats, i_feats, 1, 1, 0)
- self.DWConv1 = nn.Sequential(
- nn.Conv2d(i_feats, i_feats, 7, 1, 7 // 2, groups=n_feats),
- nn.GELU())
- self.Conv2 = nn.Conv2d(i_feats, n_feats, 1, 1, 0)
- self.norm = LayerNorm(n_feats, data_format='channels_first')
- self.scale = nn.Parameter(torch.zeros((1, n_feats, 1, 1)), requires_grad=True)
- def forward(self, x):
- shortcut = x.clone()
- # Ghost Expand
- x = self.Conv1(self.norm(x))
- x = self.DWConv1(x)
- x = self.Conv2(x)
- return x * self.scale + shortcut
- class SimpleGate(nn.Module):
- def __init__(self, n_feats):
- super().__init__()
- i_feats = n_feats * 2
- self.Conv1 = nn.Conv2d(n_feats, i_feats, 1, 1, 0)
- # self.DWConv1 = nn.Conv2d(n_feats, n_feats, 7, 1, 7//2, groups= n_feats)
- self.Conv2 = nn.Conv2d(n_feats, n_feats, 1, 1, 0)
- self.norm = LayerNorm(n_feats, data_format='channels_first')
- self.scale = nn.Parameter(torch.zeros((1, n_feats, 1, 1)), requires_grad=True)
- def forward(self, x):
- shortcut = x.clone()
- # Ghost Expand
- x = self.Conv1(self.norm(x))
- a, x = torch.chunk(x, 2, dim=1)
- x = x * a # self.DWConv1(a)
- x = self.Conv2(x)
- return x * self.scale + shortcut
- # -----------------------------------------------------------------------------------------------------------------
- # RCAN-style
- class RCBv6(nn.Module):
- def __init__(
- self, n_feats, k, lk=7, res_scale=1.0, style='X', act=nn.SiLU(), deploy=False):
- super().__init__()
- self.LKA = nn.Sequential(
- nn.Conv2d(n_feats, n_feats, 5, 1, lk // 2, groups=n_feats),
- nn.Conv2d(n_feats, n_feats, 7, stride=1, padding=9, groups=n_feats, dilation=3),
- nn.Conv2d(n_feats, n_feats, 1, 1, 0),
- nn.Sigmoid())
- # self.LFE2 = LFEv3(n_feats, attn ='CA')
- self.LFE = nn.Sequential(
- nn.Conv2d(n_feats, n_feats, 3, 1, 1),
- nn.GELU(),
- nn.Conv2d(n_feats, n_feats, 3, 1, 1))
- def forward(self, x, pre_attn=None, RAA=None):
- shortcut = x.clone()
- x = self.LFE(x)
- x = self.LKA(x) * x
- return x + shortcut
- # -----------------------------------------------------------------------------------------------------------------
- class MLKA_Ablation(nn.Module):
- def __init__(self, n_feats, k=2, squeeze_factor=15):
- super().__init__()
- i_feats = 2 * n_feats
- self.n_feats = n_feats
- self.i_feats = i_feats
- self.norm = LayerNorm(n_feats, data_format='channels_first')
- self.scale = nn.Parameter(torch.zeros((1, n_feats, 1, 1)), requires_grad=True)
- k = 2
- # Multiscale Large Kernel Attention
- self.LKA7 = nn.Sequential(
- nn.Conv2d(n_feats // k, n_feats // k, 7, 1, 7 // 2, groups=n_feats // k),
- nn.Conv2d(n_feats // k, n_feats // k, 9, stride=1, padding=(9 // 2) * 4, groups=n_feats // k, dilation=4),
- nn.Conv2d(n_feats // k, n_feats // k, 1, 1, 0))
- self.LKA5 = nn.Sequential(
- nn.Conv2d(n_feats // k, n_feats // k, 5, 1, 5 // 2, groups=n_feats // k),
- nn.Conv2d(n_feats // k, n_feats // k, 7, stride=1, padding=(7 // 2) * 3, groups=n_feats // k, dilation=3),
- nn.Conv2d(n_feats // k, n_feats // k, 1, 1, 0))
- '''self.LKA3 = nn.Sequential(
- nn.Conv2d(n_feats//k, n_feats//k, 3, 1, 1, groups= n_feats//k),
- nn.Conv2d(n_feats//k, n_feats//k, 5, stride=1, padding=(5//2)*2, groups=n_feats//k, dilation=2),
- nn.Conv2d(n_feats//k, n_feats//k, 1, 1, 0))'''
- # self.X3 = nn.Conv2d(n_feats//k, n_feats//k, 3, 1, 1, groups= n_feats//k)
- self.X5 = nn.Conv2d(n_feats // k, n_feats // k, 5, 1, 5 // 2, groups=n_feats // k)
- self.X7 = nn.Conv2d(n_feats // k, n_feats // k, 7, 1, 7 // 2, groups=n_feats // k)
- self.proj_first = nn.Sequential(
- nn.Conv2d(n_feats, i_feats, 1, 1, 0))
- self.proj_last = nn.Sequential(
- nn.Conv2d(n_feats, n_feats, 1, 1, 0))
- def forward(self, x, pre_attn=None, RAA=None):
- shortcut = x.clone()
- x = self.norm(x)
- x = self.proj_first(x)
- a, x = torch.chunk(x, 2, dim=1)
- # u_1, u_2, u_3= torch.chunk(u, 3, dim=1)
- a_1, a_2 = torch.chunk(a, 2, dim=1)
- a = torch.cat([self.LKA7(a_1) * self.X7(a_1), self.LKA5(a_2) * self.X5(a_2)], dim=1)
- x = self.proj_last(x * a) * self.scale + shortcut
- return x
- # -----------------------------------------------------------------------------------------------------------------
- class LayerNorm(nn.Module):
- r""" LayerNorm that supports two data formats: channels_last (default) or channels_first.
- The ordering of the dimensions in the inputs. channels_last corresponds to inputs with
- shape (batch_size, height, width, channels) while channels_first corresponds to inputs
- with shape (batch_size, channels, height, width).
- """
- def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"):
- super().__init__()
- self.weight = nn.Parameter(torch.ones(normalized_shape))
- self.bias = nn.Parameter(torch.zeros(normalized_shape))
- self.eps = eps
- self.data_format = data_format
- if self.data_format not in ["channels_last", "channels_first"]:
- raise NotImplementedError
- self.normalized_shape = (normalized_shape,)
- def forward(self, x):
- if self.data_format == "channels_last":
- return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
- elif self.data_format == "channels_first":
- u = x.mean(1, keepdim=True)
- s = (x - u).pow(2).mean(1, keepdim=True)
- x = (x - u) / torch.sqrt(s + self.eps)
- x = self.weight[:, None, None] * x + self.bias[:, None, None]
- return x
- class SGAB(nn.Module):
- def __init__(self, n_feats, drop=0.0, k=2, squeeze_factor=15, attn='GLKA'):
- super().__init__()
- i_feats = n_feats * 2
- self.Conv1 = nn.Conv2d(n_feats, i_feats, 1, 1, 0)
- self.DWConv1 = nn.Conv2d(n_feats, n_feats, 7, 1, 7 // 2, groups=n_feats)
- self.Conv2 = nn.Conv2d(n_feats, n_feats, 1, 1, 0)
- self.norm = LayerNorm(n_feats, data_format='channels_first')
- self.scale = nn.Parameter(torch.zeros((1, n_feats, 1, 1)), requires_grad=True)
- def forward(self, x):
- shortcut = x.clone()
- # Ghost Expand
- x = self.Conv1(self.norm(x))
- a, x = torch.chunk(x, 2, dim=1)
- x = x * self.DWConv1(a)
- x = self.Conv2(x)
- return x * self.scale + shortcut
- class GroupGLKA(nn.Module):
- def __init__(self, n_feats, k=2, squeeze_factor=15):
- super().__init__()
- i_feats = 2 * n_feats
- self.n_feats = n_feats
- self.i_feats = i_feats
- self.norm = LayerNorm(n_feats, data_format='channels_first')
- self.scale = nn.Parameter(torch.zeros((1, n_feats, 1, 1)), requires_grad=True)
- # 分为两个分支,分别有 n_feats // 2 个通道
- split1 = n_feats // 2
- split2 = n_feats - split1 # 确保通道总数匹配
- # 定义两个不同尺度的卷积块,适应新的分支数量
- self.LKA7 = nn.Sequential(
- nn.Conv2d(split2, split2, 7, 1, padding=7 // 2, groups=split2),
- nn.Conv2d(split2, split2, 9, stride=1, padding=(9 // 2) * 4, groups=split2, dilation=4),
- nn.Conv2d(split2, split2, 1, 1, 0)
- )
- self.LKA5 = nn.Sequential(
- nn.Conv2d(split1, split1, 5, 1, padding=5 // 2, groups=split1),
- nn.Conv2d(split1, split1, 7, stride=1, padding=(7 // 2) * 3, groups=split1, dilation=3),
- nn.Conv2d(split1, split1, 1, 1, 0)
- )
- # 定义额外的卷积层,适应新的分支数量
- self.X5 = nn.Conv2d(split1, split1, 5, 1, padding=5 // 2, groups=split1)
- self.X7 = nn.Conv2d(split2, split2, 7, 1, padding=7 // 2, groups=split2)
- self.proj_first = nn.Sequential(
- nn.Conv2d(n_feats, i_feats, 1, 1, 0))
- self.proj_last = nn.Sequential(
- nn.Conv2d(n_feats, n_feats, 1, 1, 0))
- def forward(self, x, pre_attn=None, RAA=None):
- shortcut = x.clone()
- x = self.norm(x)
- x = self.proj_first(x)
- # 将特征分为两个部分,a 和 x
- a, x = torch.chunk(x, 2, dim=1)
- # 将 a 分为两个分支,分别应用不同尺度的卷积操作
- a_1, a_2 = torch.chunk(a, 2, dim=1)
- a = torch.cat([self.LKA5(a_1) * self.X5(a_1), self.LKA7(a_2) * self.X7(a_2)], dim=1)
- x = self.proj_last(x * a) * self.scale + shortcut
- return x
- # MAB
- class MAB(nn.Module):
- def __init__(
- self, n_feats):
- super().__init__()
- self.LKA = GroupGLKA(n_feats)
- self.LFE = SGAB(n_feats)
- def forward(self, x, pre_attn=None, RAA=None):
- # large kernel attention
- x = self.LKA(x)
- # local feature extraction
- x = self.LFE(x)
- return x
- class LKAT(nn.Module):
- def __init__(self, n_feats):
- super().__init__()
- # self.norm = LayerNorm(n_feats, data_format='channels_first')
- # self.scale = nn.Parameter(torch.zeros((1, n_feats, 1, 1)), requires_grad=True)
- self.conv0 = nn.Sequential(
- nn.Conv2d(n_feats, n_feats, 1, 1, 0),
- nn.GELU())
- self.att = nn.Sequential(
- nn.Conv2d(n_feats, n_feats, 7, 1, 7 // 2, groups=n_feats),
- nn.Conv2d(n_feats, n_feats, 9, stride=1, padding=(9 // 2) * 3, groups=n_feats, dilation=3),
- nn.Conv2d(n_feats, n_feats, 1, 1, 0))
- self.conv1 = nn.Conv2d(n_feats, n_feats, 1, 1, 0)
- def forward(self, x):
- x = self.conv0(x)
- x = x * self.att(x)
- x = self.conv1(x)
- return x
- class ResGroup(nn.Module):
- def __init__(self, n_resblocks, n_feats, res_scale=1.0):
- super(ResGroup, self).__init__()
- self.body = nn.ModuleList([
- MAB(n_feats) \
- for _ in range(n_resblocks)])
- self.body_t = LKAT(n_feats)
- def forward(self, x):
- res = x.clone()
- for i, block in enumerate(self.body):
- res = block(res)
- x = self.body_t(res) + x
- return x
- class MeanShift(nn.Conv2d):
- def __init__(
- self, rgb_range,
- rgb_mean=(0.4488, 0.4371, 0.4040), rgb_std=(1.0, 1.0, 1.0), sign=-1):
- super(MeanShift, self).__init__(3, 3, kernel_size=1)
- std = torch.Tensor(rgb_std)
- self.weight.data = torch.eye(3).view(3, 3, 1, 1) / std.view(3, 1, 1, 1)
- self.bias.data = sign * rgb_range * torch.Tensor(rgb_mean) / std
- for p in self.parameters():
- p.requires_grad = False
- @ARCH_REGISTRY.register()
- class MAN(nn.Module):
- def __init__(self, n_resblocks=36, n_resgroups=1, n_colors=3, n_feats=180, scale=2, res_scale=1.0):
- super(MAN, self).__init__()
- # res_scale = res_scale
- self.n_resgroups = n_resgroups
- self.sub_mean = MeanShift(1.0)
- self.head = nn.Conv2d(n_colors, n_feats, 3, 1, 1)
- # define body module
- self.body = nn.ModuleList([
- ResGroup(
- n_resblocks, n_feats, res_scale=res_scale)
- for i in range(n_resgroups)])
- if self.n_resgroups > 1:
- self.body_t = nn.Conv2d(n_feats, n_feats, 3, 1, 1)
- # define tail module
- self.tail = nn.Sequential(
- nn.Conv2d(n_feats, n_colors * (scale ** 2), 3, 1, 1),
- nn.PixelShuffle(scale)
- )
- self.add_mean = MeanShift(1.0, sign=1)
- def forward(self, x):
- x = self.sub_mean(x)
- x = self.head(x)
- res = x
- for i in self.body:
- res = i(res)
- if self.n_resgroups > 1:
- res = self.body_t(res) + x
- x = self.tail(res)
- x = self.add_mean(x)
- return x
- def visual_feature(self, x):
- fea = []
- x = self.head(x)
- res = x
- for i in self.body:
- temp = res
- res = i(res)
- fea.append(res)
- res = self.body_t(res) + x
- x = self.tail(res)
- return x, fea
- def load_state_dict(self, state_dict, strict=False):
- own_state = self.state_dict()
- for name, param in state_dict.items():
- if name in own_state:
- if isinstance(param, nn.Parameter):
- param = param.data
- try:
- own_state[name].copy_(param)
- except Exception:
- if name.find('tail') >= 0:
- print('Replace pre-trained upsampler to new one...')
- else:
- raise RuntimeError('While copying the parameter named {}, '
- 'whose dimensions in the model are {} and '
- 'whose dimensions in the checkpoint are {}.'
- .format(name, own_state[name].size(), param.size()))
- elif strict:
- if name.find('tail') == -1:
- raise KeyError('unexpected key "{}" in state_dict'
- .format(name))
- if strict:
- missing = set(own_state.keys()) - set(state_dict.keys())
- if len(missing) > 0:
- raise KeyError('missing keys in state_dict: "{}"'.format(missing))
- class Bottleneck(nn.Module):
- """Standard bottleneck."""
- def __init__(self, c1, c2, shortcut=True, g=1, k=(3, 3), e=0.5):
- """Initializes a standard bottleneck module with optional shortcut connection and configurable parameters."""
- super().__init__()
- c_ = int(c2 * e) # hidden channels
- self.cv1 = Conv(c1, c_, k[0], 1)
- self.cv2 = Conv(c_, c2, k[1], 1, g=g)
- self.add = shortcut and c1 == c2
- def forward(self, x):
- """Applies the YOLO FPN to input data."""
- return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
- class C2f(nn.Module):
- """Faster Implementation of CSP Bottleneck with 2 convolutions."""
- def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5):
- """Initializes a CSP bottleneck with 2 convolutions and n Bottleneck blocks for faster processing."""
- super().__init__()
- self.c = int(c2 * e) # hidden channels
- self.cv1 = Conv(c1, 2 * self.c, 1, 1)
- self.cv2 = Conv((2 + n) * self.c, c2, 1) # optional act=FReLU(c2)
- self.m = nn.ModuleList(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n))
- def forward(self, x):
- """Forward pass through C2f layer."""
- y = list(self.cv1(x).chunk(2, 1))
- y.extend(m(y[-1]) for m in self.m)
- return self.cv2(torch.cat(y, 1))
- def forward_split(self, x):
- """Forward pass using split() instead of chunk()."""
- y = list(self.cv1(x).split((self.c, self.c), 1))
- y.extend(m(y[-1]) for m in self.m)
- return self.cv2(torch.cat(y, 1))
- 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 C3(nn.Module):
- """CSP Bottleneck with 3 convolutions."""
- def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
- """Initialize the CSP Bottleneck with given channels, number, shortcut, groups, and expansion values."""
- super().__init__()
- c_ = int(c2 * e) # hidden channels
- self.cv1 = Conv(c1, c_, 1, 1)
- self.cv2 = Conv(c1, c_, 1, 1)
- self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2)
- self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, k=((1, 1), (3, 3)), e=1.0) for _ in range(n)))
- def forward(self, x):
- """Forward pass through the CSP bottleneck with 2 convolutions."""
- return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
- class C3k(C3):
- """C3k is a CSP bottleneck module with customizable kernel sizes for feature extraction in neural networks."""
- def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, k=3):
- """Initializes the C3k module with specified channels, number of layers, and configurations."""
- super().__init__(c1, c2, n, shortcut, g, e)
- c_ = int(c2 * e) # hidden channels
- # self.m = nn.Sequential(*(RepBottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
- self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
- class C3k_MAB(C3):
- """C3k is a CSP bottleneck module with customizable kernel sizes for feature extraction in neural networks."""
- def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, k=3):
- """Initializes the C3k module with specified channels, number of layers, and configurations."""
- super().__init__(c1, c2, n, shortcut, g, e)
- c_ = int(c2 * e) # hidden channels
- # self.m = nn.Sequential(*(RepBottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
- self.m = nn.Sequential(*(MAB(c_) for _ in range(n)))
- class C3k2_MAB1(C2f):
- """Faster Implementation of CSP Bottleneck with 2 convolutions."""
- def __init__(self, c1, c2, n=1, c3k=False, e=0.5, g=1, shortcut=True):
- """Initializes the C3k2 module, a faster CSP Bottleneck with 2 convolutions and optional C3k blocks."""
- super().__init__(c1, c2, n, shortcut, g, e)
- self.m = nn.ModuleList(
- C3k(self.c, self.c, 2, shortcut, g) if c3k else MAB(self.c) for _ in range(n)
- )
- class C3k2_MAB2(C2f):
- """Faster Implementation of CSP Bottleneck with 2 convolutions."""
- def __init__(self, c1, c2, n=1, c3k=False, e=0.5, g=1, shortcut=True):
- """Initializes the C3k2 module, a faster CSP Bottleneck with 2 convolutions and optional C3k blocks."""
- super().__init__(c1, c2, n, shortcut, g, e)
- self.m = nn.ModuleList(
- C3k_MAB(self.c, self.c, 2, shortcut, g) if c3k else MAB(self.c) for _ in range(n)
- )
- if __name__ == "__main__":
- # Generating Sample image
- image_size = (1, 36, 224, 224)
- image = torch.rand(*image_size)
- # Model
- model = MAB(36)
- 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-C3k2-MAB1 summary: 395 layers, 2,605,811 parameters, 2,605,795 gradients, 6.6 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_MAB1, [256, False, 0.25]]
- - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8
- - [-1, 2, C3k2_MAB1, [512, False, 0.25]]
- - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16
- - [-1, 2, C3k2_MAB1, [512, True]]
- - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32
- - [-1, 2, C3k2_MAB1, [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_MAB1, [512, False]] # 13
- - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
- - [[-1, 4], 1, Concat, [1]] # cat backbone P3
- - [-1, 2, C3k2_MAB1, [256, False]] # 16 (P3/8-small)
- - [-1, 1, Conv, [256, 3, 2]]
- - [[-1, 13], 1, Concat, [1]] # cat head P4
- - [-1, 2, C3k2_MAB1, [512, False]] # 19 (P4/16-medium)
- - [-1, 1, Conv, [512, 3, 2]]
- - [[-1, 10], 1, Concat, [1]] # cat head P5
- - [-1, 2, C3k2_MAB1, [1024, True]] # 22 (P5/32-large)
- - [[16, 19, 22], 1, Detect, [nc]] # Detect(P3, P4, P5)
5.2 yaml文件2
训练信息:YOLO11-C3k2-MAB2 summary: 485 layers, 2,458,163 parameters, 2,458,147 gradients, 6.5 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_MAB2, [256, False, 0.25]]
- - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8
- - [-1, 2, C3k2_MAB2, [512, False, 0.25]]
- - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16
- - [-1, 2, C3k2_MAB2, [512, True]]
- - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32
- - [-1, 2, C3k2_MAB2, [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_MAB2, [512, False]] # 13
- - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
- - [[-1, 4], 1, Concat, [1]] # cat backbone P3
- - [-1, 2, C3k2_MAB2, [256, False]] # 16 (P3/8-small)
- - [-1, 1, Conv, [256, 3, 2]]
- - [[-1, 13], 1, Concat, [1]] # cat head P4
- - [-1, 2, C3k2_MAB2, [512, False]] # 19 (P4/16-medium)
- - [-1, 1, Conv, [512, 3, 2]]
- - [[-1, 10], 1, Concat, [1]] # cat head P5
- - [-1, 2, C3k2_MAB2, [1024, True]] # 22 (P5/32-large)
- - [[16, 19, 22], 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分,后期我会根据各种最新的前沿顶会进行论文复现,也会对一些老的改进机制进行补充,如果大家觉得本文帮助到你了,订阅本专栏,关注后续更多的更新~