一、本文介绍
本文给大家带来的最新改进机制是利用 2024 最新的线性 可变形卷积 LDConv 替换YOLOv11的传统 下采样 操作(值得一提的是这个作者和RFAConv是同一个作者),介绍了一种新型的卷积操作——线性可变形卷积(LDConv)。LDConv 旨在解决标准卷积操作的局限性,标准卷积在固定形状和大小的局部窗口中进行采样,难以动态适应不同物体的形状。可变形卷积(Deformable Conv)虽然允许灵活的采样位置,但其参数数量随着卷积核大小呈平方增长,计算效率较低。 LDConv 提供了比可变形卷积更大的灵活性 , 允许卷积核的参数数量呈线性增长,从而克服了可变形卷积参数数量平方增长的问题 , 该方法可以起到轻量化的作用 。
欢迎大家订阅我的专栏一起学习YOLO!
二、原理介绍
官方论文地址: 官方论文地址点击此处即可跳转
官方代码地址: 官方代码地址点击此处即可跳转
这篇文章题为《LDConv: 用于改进卷积神经网络的线性可变形卷积》 ,介绍了一种新型的 卷积操作 ——线性可变形卷积(LDConv)。LDConv 旨在解决标准卷积操作的局限性,标准卷积在固定形状和大小的局部窗口中进行采样,难以动态适应不同物体的形状。可变形卷积(Deformable Conv)虽然允许灵活的采样位置,但其参数数量随着卷积核大小呈平方增长,计算效率较低。
主要内容与原理:
1. 标准卷积的局限性:传统的 卷积神经网络 (CNN)使用固定的方形卷积核,无法动态调整以适应变化的目标形状,这限制了网络从不同空间位置捕捉信息的能力。2. 可变形卷积(Deformable Conv):可变形卷积通过引入偏移量来调整采样网格,使得卷积核能够灵活地适应物体的形状。然而,其参数数量依然随卷积核的增大而平方增长,计算效率较低。
3. LDConv的引入:
- LDConv 提供了比可变形卷积更大的灵活性,允许卷积核的参数数量呈线性增长,从而克服了可变形卷积参数数量平方增长的问题。
- 它引入了一种坐标生成 算法 ,可以为任意大小的卷积核生成不同的初始采样位置。
- 通过偏移量动态调整采样形状,使卷积核能够更精确地适应目标形状,从而提高特征提取效率。4.主要贡献:
- LDConv 为参数数量和卷积核大小提供了更多的灵活性,能够在网络开销和性能之间实现更好的平衡。
- 它可用于目标检测等 计算机视觉 任务,实验证明其在COCO2017、VOC 和 VisDrone-DET2021 数据集上表现优越。5. 目标检测实验:在多个数据集上的实验表明,LDConv 在目标检测任务中提升了CNN的性能,尤其是在处理大目标时,得益于其灵活的采样形状调整能力。
6. 应用与灵活性:
- LDConv 可以替换传统的卷积操作,提升网络性能的同时,不显著增加计算成本。
- 该方法是一种即插即用的卷积操作,能轻松集成到现有 模型 中,并提高在各种任务中的表现 (本文用于替换YOLOv8中的Conv) 。
- LDConv 还可以用于其他模块(如 FasterBlock 和 GSBottleneck),进一步提高网络效率并减少参数增长 (二次创新) 。该论文强调,LDConv 通过灵活调整卷积核的形状和大小,提供了比现有方法(如标准卷积和可变形卷积)更好的计算效率和网络性能的平衡。
三、核心代码
代码的使用方式看章节四!
- import math
- import torch
- import torch.nn as nn
- from einops import rearrange
- __all__ = ['LDConv', 'C3k2_LDConv1', 'C3k2_LDConv2']
- class LDConv(nn.Module):
- def __init__(self, inc, outc, num_param, stride=1, bias=None):
- super(LDConv, self).__init__()
- self.num_param = num_param
- self.stride = stride
- self.conv = nn.Sequential(nn.Conv2d(inc, outc, kernel_size=(num_param, 1), stride=(num_param, 1), bias=bias),
- nn.BatchNorm2d(outc),
- nn.SiLU()) # the conv adds the BN and SiLU to compare original Conv in YOLOv5.
- self.p_conv = nn.Conv2d(inc, 2 * num_param, kernel_size=3, padding=1, stride=stride)
- nn.init.constant_(self.p_conv.weight, 0)
- self.p_conv.register_full_backward_hook(self._set_lr)
- @staticmethod
- def _set_lr(module, grad_input, grad_output):
- grad_input = (grad_input[i] * 0.1 for i in range(len(grad_input)))
- grad_output = (grad_output[i] * 0.1 for i in range(len(grad_output)))
- def forward(self, x):
- # N is num_param.
- offset = self.p_conv(x)
- dtype = offset.data.type()
- N = offset.size(1) // 2
- # (b, 2N, h, w)
- p = self._get_p(offset, dtype)
- # (b, h, w, 2N)
- p = p.contiguous().permute(0, 2, 3, 1)
- q_lt = p.detach().floor()
- q_rb = q_lt + 1
- q_lt = torch.cat([torch.clamp(q_lt[..., :N], 0, x.size(2) - 1), torch.clamp(q_lt[..., N:], 0, x.size(3) - 1)],
- dim=-1).long()
- q_rb = torch.cat([torch.clamp(q_rb[..., :N], 0, x.size(2) - 1), torch.clamp(q_rb[..., N:], 0, x.size(3) - 1)],
- dim=-1).long()
- q_lb = torch.cat([q_lt[..., :N], q_rb[..., N:]], dim=-1)
- q_rt = torch.cat([q_rb[..., :N], q_lt[..., N:]], dim=-1)
- # clip p
- p = torch.cat([torch.clamp(p[..., :N], 0, x.size(2) - 1), torch.clamp(p[..., N:], 0, x.size(3) - 1)], dim=-1)
- # bilinear kernel (b, h, w, N)
- g_lt = (1 + (q_lt[..., :N].type_as(p) - p[..., :N])) * (1 + (q_lt[..., N:].type_as(p) - p[..., N:]))
- g_rb = (1 - (q_rb[..., :N].type_as(p) - p[..., :N])) * (1 - (q_rb[..., N:].type_as(p) - p[..., N:]))
- g_lb = (1 + (q_lb[..., :N].type_as(p) - p[..., :N])) * (1 - (q_lb[..., N:].type_as(p) - p[..., N:]))
- g_rt = (1 - (q_rt[..., :N].type_as(p) - p[..., :N])) * (1 + (q_rt[..., N:].type_as(p) - p[..., N:]))
- # resampling the features based on the modified coordinates.
- x_q_lt = self._get_x_q(x, q_lt, N)
- x_q_rb = self._get_x_q(x, q_rb, N)
- x_q_lb = self._get_x_q(x, q_lb, N)
- x_q_rt = self._get_x_q(x, q_rt, N)
- # bilinear
- x_offset = g_lt.unsqueeze(dim=1) * x_q_lt + \
- g_rb.unsqueeze(dim=1) * x_q_rb + \
- g_lb.unsqueeze(dim=1) * x_q_lb + \
- g_rt.unsqueeze(dim=1) * x_q_rt
- x_offset = self._reshape_x_offset(x_offset, self.num_param)
- out = self.conv(x_offset)
- return out
- # generating the inital sampled shapes for the LDConv with different sizes.
- def _get_p_n(self, N, dtype):
- base_int = round(math.sqrt(self.num_param))
- row_number = self.num_param // base_int
- mod_number = self.num_param % base_int
- p_n_x, p_n_y = torch.meshgrid(
- torch.arange(0, row_number),
- torch.arange(0, base_int))
- p_n_x = torch.flatten(p_n_x)
- p_n_y = torch.flatten(p_n_y)
- if mod_number > 0:
- mod_p_n_x, mod_p_n_y = torch.meshgrid(
- torch.arange(row_number, row_number + 1),
- torch.arange(0, mod_number))
- mod_p_n_x = torch.flatten(mod_p_n_x)
- mod_p_n_y = torch.flatten(mod_p_n_y)
- p_n_x, p_n_y = torch.cat((p_n_x, mod_p_n_x)), torch.cat((p_n_y, mod_p_n_y))
- p_n = torch.cat([p_n_x, p_n_y], 0)
- p_n = p_n.view(1, 2 * N, 1, 1).type(dtype)
- return p_n
- # no zero-padding
- def _get_p_0(self, h, w, N, dtype):
- p_0_x, p_0_y = torch.meshgrid(
- torch.arange(0, h * self.stride, self.stride),
- torch.arange(0, w * self.stride, self.stride))
- p_0_x = torch.flatten(p_0_x).view(1, 1, h, w).repeat(1, N, 1, 1)
- p_0_y = torch.flatten(p_0_y).view(1, 1, h, w).repeat(1, N, 1, 1)
- p_0 = torch.cat([p_0_x, p_0_y], 1).type(dtype)
- return p_0
- def _get_p(self, offset, dtype):
- N, h, w = offset.size(1) // 2, offset.size(2), offset.size(3)
- # (1, 2N, 1, 1)
- p_n = self._get_p_n(N, dtype)
- # (1, 2N, h, w)
- p_0 = self._get_p_0(h, w, N, dtype)
- p = p_0 + p_n + offset
- return p
- def _get_x_q(self, x, q, N):
- b, h, w, _ = q.size()
- padded_w = x.size(3)
- c = x.size(1)
- # (b, c, h*w)
- x = x.contiguous().view(b, c, -1)
- # (b, h, w, N)
- index = q[..., :N] * padded_w + q[..., N:] # offset_x*w + offset_y
- # (b, c, h*w*N)
- index = index.contiguous().unsqueeze(dim=1).expand(-1, c, -1, -1, -1).contiguous().view(b, c, -1)
- x_offset = x.gather(dim=-1, index=index).contiguous().view(b, c, h, w, N)
- return x_offset
- # Stacking resampled features in the row direction.
- @staticmethod
- def _reshape_x_offset(x_offset, num_param):
- b, c, h, w, n = x_offset.size()
- # using Conv3d
- # x_offset = x_offset.permute(0,1,4,2,3), then Conv3d(c,c_out, kernel_size =(num_param,1,1),stride=(num_param,1,1),bias= False)
- # using 1 × 1 Conv
- # x_offset = x_offset.permute(0,1,4,2,3), then, x_offset.view(b,c×num_param,h,w) finally, Conv2d(c×num_param,c_out, kernel_size =1,stride=1,bias= False)
- # using the column conv as follow, then, Conv2d(inc, outc, kernel_size=(num_param, 1), stride=(num_param, 1), bias=bias)
- x_offset = rearrange(x_offset, 'b c h w n -> b c (h n) w')
- return x_offset
- 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 Bottleneck_LDConv(nn.Module):
- # Standard bottleneck with DCN
- def __init__(self, c1, c2, shortcut=True, g=1, k=(3, 3), e=0.5): # ch_in, ch_out, shortcut, groups, kernels, expand
- super().__init__()
- c_ = int(c2 * e) # hidden channels
- self.cv1 = Conv(c1, c_, k[0], 1)
- self.cv2 = LDConv(c_, c2, 3)
- self.add = shortcut and c1 == c2
- def forward(self, x):
- return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(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 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))
- 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 C3kLDConv(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_LDConv(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
- class C3k2_LDConv1(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 Bottleneck_LDConv(self.c, self.c, shortcut, g) for _ in range(n)
- )
- class C3k2_LDConv2(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(
- C3kLDConv(self.c, self.c, 2, shortcut, g) if c3k else Bottleneck(self.c, self.c, shortcut, g) for _ in range(n)
- )
- if __name__ == "__main__":
- # Generating Sample image
- image_size = (1, 64, 224, 224)
- image = torch.rand(*image_size)
- # Model
- model = C3k2_LDConv2(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 修改四
找到文件到如下文件'ultralytics/nn/tasks.py',在其中的parse_model方法中添加即可。
到此就修改完成了,大家可以复制下面的yaml文件运行。
五、正式训练
5.1 yaml文件1
训练信息:YOLO11-LDConv summary: 337 layers, 2,427,141 parameters, 2,427,125 gradients, 6.2 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, LDConv, [128, 6, 2]] # 1-P2/4
- - [-1, 2, C3k2, [256, False, 0.25]]
- - [-1, 1, LDConv, [256, 6, 2]] # 3-P3/8
- - [-1, 2, C3k2, [512, False, 0.25]]
- - [-1, 1, LDConv, [512, 6, 2]] # 5-P4/16
- - [-1, 2, C3k2, [512, True]]
- - [-1, 1, LDConv, [1024, 6, 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, LDConv, [256, 6, 2]]
- - [[-1, 13], 1, Concat, [1]] # cat head P4
- - [-1, 2, C3k2, [512, False]] # 19 (P4/16-medium)
- - [-1, 1, LDConv, [512, 6, 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-C3k2-LDConv-1 summary: 335 layers, 2,566,923 parameters, 2,566,907 gradients, 6.3 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_LDConv1, [256, False, 0.25]]
- - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8
- - [-1, 2, C3k2_LDConv1, [512, False, 0.25]]
- - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16
- - [-1, 2, C3k2_LDConv1, [512, True]]
- - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32
- - [-1, 2, C3k2_LDConv1, [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_LDConv1, [512, False]] # 13
- - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
- - [[-1, 4], 1, Concat, [1]] # cat backbone P3
- - [-1, 2, C3k2_LDConv1, [256, False]] # 16 (P3/8-small)
- - [-1, 1, Conv, [256, 3, 2]]
- - [[-1, 13], 1, Concat, [1]] # cat head P4
- - [-1, 2, C3k2_LDConv1, [512, False]] # 19 (P4/16-medium)
- - [-1, 1, Conv, [512, 3, 2]]
- - [[-1, 10], 1, Concat, [1]] # cat head P5
- - [-1, 2, C3k2_LDConv1, [1024, True]] # 22 (P5/32-large)
- - [[16, 19, 22], 1, Detect, [nc]] # Detect(P3, P4, P5)
5.3 yaml文件3
训练信息:YOLO11-C3k2-LDConv-2 summary: 338 layers, 2,499,489 parameters, 2,499,473 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_LDConv2, [256, False, 0.25]]
- - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8
- - [-1, 2, C3k2_LDConv2, [512, False, 0.25]]
- - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16
- - [-1, 2, C3k2_LDConv2, [512, True]]
- - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32
- - [-1, 2, C3k2_LDConv2, [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_LDConv2, [512, False]] # 13
- - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
- - [[-1, 4], 1, Concat, [1]] # cat backbone P3
- - [-1, 2, C3k2_LDConv2, [256, False]] # 16 (P3/8-small)
- - [-1, 1, Conv, [256, 3, 2]]
- - [[-1, 13], 1, Concat, [1]] # cat head P4
- - [-1, 2, C3k2_LDConv2, [512, False]] # 19 (P4/16-medium)
- - [-1, 1, Conv, [512, 3, 2]]
- - [[-1, 10], 1, Concat, [1]] # cat head P5
- - [-1, 2, C3k2_LDConv2, [1024, True]] # 22 (P5/32-large)
- - [[16, 19, 22], 1, Detect, [nc]] # Detect(P3, P4, P5)
5.4 训练代码
大家可以创建一个py文件将我给的代码复制粘贴进去,配置好自己的文件路径即可运行。
- import warnings
- warnings.filterwarnings('ignore')
- from ultralytics import YOLO
- if __name__ == '__main__':
- model = YOLO('yolov8-MLLA.yaml')
- # 如何切换模型版本, 上面的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=False, # 如果出现训练损失为Nan可以关闭amp
- project='runs/train',
- name='exp',
- )
5.5 训练过程截图
五、本文总结
到此本文的正式分享内容就结束了,在这里给大家推荐我的YOLOv11改进有效涨点专栏,本专栏目前为新开的平均质量分98分,后期我会根据各种最新的前沿顶会进行论文复现,也会对一些老的改进机制进行补充,如果大家觉得本文帮助到你了,订阅本专栏,关注后续更多的更新~