欢迎光临
我们一直在努力

YOLO系列算法改进 | 融合DML轻量级动态混合层改进C2PSA模块 | 提升超分辨率重建质量

1. DML (Dynamic Mixing Layer) 简介

动态混合层(Dynamic Mixing Layer, DML)是SRConvNet的核心组件之一,专为解决轻量级图像超分辨率(SISR)任务中局部多尺度特征捕捉与通道适应性增强两大痛点设计,旨在替代传统Vision Transformer(ViT)中局限于线性变换的前馈网络(FFN),同时融合卷积神经网络(ConvNet)的局部建模优势与动态权重的灵活性。

原始论文:https://link.springer.com/article/10.1007/s11263-024-02147-y

原始代码:https://github.com/lifengcs/SRConvNet

2. 设计目标

现有方法的局限

传统ViT的FFN仅通过“线性层+激活函数”实现特征变换,无法有效捕捉图像的局部空间依赖;后续改进方法(如卷积FFN、混合尺度卷积FFN)虽引入卷积增强局部性,但存在明显缺陷;

单尺度卷积:仅用固定尺寸卷积核(如3×3),难以覆盖不同尺度的图像细节(如边缘、纹理); 静态权重:卷积核权重训练后固定,无法根据输入特征的通道差异自适应调整,导致通道间适应性不足。 DML核心目标

1、多尺度局部信息聚合:通过多尺寸动态卷积,同时捕捉小尺度精细纹理与大尺度结构特征; 2、通道自适应增强:生成动态卷积权重,根据不同通道的特征分布调整核参数,提升模型对复杂场景的适配能力。

3. 具体改进步骤

🍀🍀步骤1:创建C2PSA_DML.py文件

在ultralytics/nn/modules/目录下,新建一个C2PSA_DML.py文件, 把下面代码拷贝进去:

C2PSA_DML.py代码

import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
import os

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

class LayerNorm(nn.Module):

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 FourierUnit(nn.Module):
def __init__(self, dim, groups=1, fft_norm='ortho'):
super().__init__()
self.groups = groups
self.fft_norm = fft_norm

self.conv_layer = nn.Conv2d(in_channels=dim * 2, out_channels=dim * 2, kernel_size=1, stride=1,
padding=0, groups=self.groups, bias=False)
self.act = nn.GELU()

def forward(self, x):
batch, c, h, w = x.size()
r_size = x.size()
dtype = x.dtype

ffted = torch.fft.rfft2(x.float(), norm='ortho') # (batch, c, h, w//2+1)

ffted = torch.stack([ffted.real, ffted.imag], dim=-1)

ffted = ffted.permute(0, 1, 4, 2, 3).contiguous()
ffted = ffted.view((batch, -1,) + ffted.size()[3:])
ffted = self.conv_layer(ffted.to(dtype)) # (batch, c*2, h, w//2+1)
ffted = self.act(ffted).float()

ffted = ffted.view((batch, -1, 2,) + ffted.size()[2:])
ffted = ffted.permute(0, 1, 3, 4, 2).contiguous()

ffted_complex = torch.complex(ffted[…, 0].float(), ffted[…, 1].float())
output = torch.fft.irfft2(ffted_complex, s=(h, w), norm='ortho')

return output.to(dtype)

class FConvMod(nn.Module):
def __init__(self, dim, num_heads):
super().__init__()
layer_scale_init_value = 1e-6
self.num_heads = num_heads
self.norm = LayerNorm(dim, eps=1e-6, data_format="channels_first")
self.a = FourierUnit(dim)
self.v = nn.Conv2d(dim, dim, 1)
self.act = nn.GELU()
self.layer_scale = nn.Parameter(layer_scale_init_value * torch.ones(num_heads), requires_grad=True)
self.CPE = nn.Conv2d(dim, dim, kernel_size=3, stride=1, padding=1, groups=dim)
self.proj = nn.Conv2d(dim, dim, 1)

def forward(self, x):
B, C, H, W = x.shape
N = H * W
shortcut = x
pos_embed = self.CPE(x)
x = self.norm(x)
a = self.a(x)
v = self.v(x)
a = rearrange(a, 'b (head c) h w -> b head c (h w)', head=self.num_heads)
v = rearrange(v, 'b (head c) h w -> b head c (h w)', head=self.num_heads)
a_all = torch.split(a, math.ceil(N // 4), dim=-1)
v_all = torch.split(v, math.ceil(N // 4), dim=-1)
attns = []
for a, v in zip(a_all, v_all):
attn = a * v
attn = self.layer_scale.unsqueeze(-1).unsqueeze(-1) * attn
attns.append(attn)
x = torch.cat(attns, dim=-1)
x = F.softmax(x, dim=-1)
x = rearrange(x, 'b head c (h w) -> b (head c) h w', head=self.num_heads, h=H, w=W)
x = x + pos_embed
x = self.proj(x)
out = x + shortcut

return out

class KernelAggregation(nn.Module):
def __init__(self, dim, kernel_size, groups, num_kernels, bias=True, init_weight=True):
super().__init__()
self.groups = groups
self.bias = bias
self.num_kernels = num_kernels
self.kernel_size = kernel_size
self.dim = dim
self.weight = nn.Parameter(torch.randn(num_kernels, dim, dim // groups, kernel_size, kernel_size),
requires_grad=True)
if bias:
self.bias = nn.Parameter(torch.zeros(num_kernels, dim))
else:
self.bias = None

if init_weight:
self._initialize_weights()

def _initialize_weights(self):
for i in range(self.num_kernels):
nn.init.kaiming_uniform_(self.weight[i])

def forward(self, x, attention):
B, C, H, W = x.shape
x = x.contiguous().view(1, B * self.dim, H, W)

weight = self.weight.contiguous().view(self.num_kernels, -1)
weight = torch.mm(attention, weight).contiguous().view(B * self.dim, self.dim // self.groups,
self.kernel_size, self.kernel_size)
if self.bias is not None:
bias = torch.mm(attention, self.bias).contiguous().view(-1)
x = F.conv2d(x, weight=weight, bias=bias, stride=1, padding=self.kernel_size // 2,
groups=self.groups * B)
else:
x = F.conv2d(x, weight=weight, bias=None, stride=1, padding=self.kernel_size // 2,
groups=self.groups * B)
x = x.contiguous().view(B, self.dim, x.shape[-2], x.shape[-1])

return x

class KernelAttention(nn.Module):
def __init__(self, dim, reduction=8, num_kernels=8):
super().__init__()
if dim != 3:
mid_channels = dim // reduction
else:
mid_channels = num_kernels
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.conv1 = nn.Conv2d(dim, mid_channels, 1)
self.act = nn.GELU()
self.conv2 = nn.Conv2d(mid_channels, num_kernels, 1)
self.sigmoid = nn.Sigmoid()

def forward(self, x):
x = self.avg_pool(x)
x = self.conv1(x)
x = self.act(x)
x = self.conv2(x)
x = x.view(x.shape[0], -1)
x = self.sigmoid(x)
return x

class DynamicKernelAggregation(nn.Module):
def __init__(self, dim, kernel_size, groups=1, num_kernels=4):
super().__init__()
assert dim % groups == 0
self.attention = KernelAttention(dim, num_kernels=num_kernels)
self.aggregation = KernelAggregation(dim, kernel_size=kernel_size, groups=groups, num_kernels=num_kernels)

def forward(self, x):
attention = x
attention = self.attention(attention)
x = self.aggregation(x, attention)
return x

class DyConv(nn.Module):
def __init__(self, dim, kernel_size, groups, num_kernels=1):
super().__init__()
if num_kernels > 1:
self.conv = DynamicKernelAggregation(dim, kernel_size=kernel_size, groups=groups,
num_kernels=num_kernels)
else:
self.conv = nn.Conv2d(dim, dim, kernel_size=kernel_size, groups=groups)

def forward(self, x):
x = self.conv(x)
return x

class MixFFN(nn.Module):
def __init__(self, dim, num_kernels=16):
super().__init__()
self.proj_in = nn.Conv2d(dim, dim * 2, 1)
self.conv1 = DyConv(dim, kernel_size=5, groups=dim, num_kernels=num_kernels)
self.conv2 = DyConv(dim, kernel_size=7, groups=dim, num_kernels=num_kernels)
self.proj_out = nn.Conv2d(dim * 2, dim, 1)
self.norm = LayerNorm(dim, eps=1e-6, data_format="channels_first")
self.act = nn.GELU()

def forward(self, x):
shortcut = x
x = self.norm(x)
x = self.act(self.proj_in(x))
x1, x2 = torch.chunk(x, 2, dim=1)
x1 = self.act(self.conv1(x1)).unsqueeze(dim=2)
x2 = self.act(self.conv2(x2)).unsqueeze(dim=2)
x = torch.cat([x1, x2], dim=2)
x = rearrange(x, 'b c g h w -> b (c g) h w')
x = self.proj_out(x)
x = x + shortcut
return x

class FMABlock(nn.Module):
def __init__(self, dim, num_heads=8, num_kernels=16):
super().__init__()
self.attention = FConvMod(dim, num_heads)
self.ffn = MixFFN(dim, num_kernels)

def forward(self, x):
x = self.attention(x)
x = self.ffn(x)

return x

class Attention(nn.Module):
"""
Attention module that performs self-attention on the input tensor.

Args:
dim (int): The input tensor dimension.
num_heads (int): The number of attention heads.
attn_ratio (float): The ratio of the attention key dimension to the head dimension.

Attributes:
num_heads (int): The number of attention heads.
head_dim (int): The dimension of each attention head.
key_dim (int): The dimension of the attention key.
scale (float): The scaling factor for the attention scores.
qkv (Conv): Convolutional layer for computing the query, key, and value.
proj (Conv): Convolutional layer for projecting the attended values.
pe (Conv): Convolutional layer for positional encoding.
"""

def __init__(self, dim, num_heads=8, attn_ratio=0.5):
"""Initializes multi-head attention module with query, key, and value convolutions and positional encoding."""
super().__init__()
self.num_heads = num_heads
self.head_dim = dim // num_heads
self.key_dim = int(self.head_dim * attn_ratio)
self.scale = self.key_dim**-0.5
nh_kd = self.key_dim * num_heads
h = dim + nh_kd * 2
self.qkv = Conv(dim, h, 1, act=False)
self.proj = Conv(dim, dim, 1, act=False)
self.pe = Conv(dim, dim, 3, 1, g=dim, act=False)

def forward(self, x):
"""
Forward pass of the Attention module.

Args:
x (torch.Tensor): The input tensor.

Returns:
(torch.Tensor): The output tensor after self-attention.
"""
B, C, H, W = x.shape
N = H * W
qkv = self.qkv(x)
q, k, v = qkv.view(B, self.num_heads, self.key_dim * 2 + self.head_dim, N).split(
[self.key_dim, self.key_dim, self.head_dim], dim=2
)

attn = (q.transpose(-2, -1) @ k) * self.scale
attn = attn.softmax(dim=-1)
x = (v @ attn.transpose(-2, -1)).view(B, C, H, W) + self.pe(v.reshape(B, C, H, W))
x = self.proj(x)
return x

def autopad(k, p=None, d=1):
"""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]
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):
default_act = nn.SiLU()

def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
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):
c = self.conv(x)
c = self.bn(c)
c = self.act(c)
return c
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 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 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 C3k2(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(self.c, self.c, shortcut, g) for _ in range(n)
)

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(*(Bottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
class C2PSA(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): 1×1 convolution layer to reduce the number of input channels to 2*c.
cv2 (Conv): 1×1 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:
>>> c2psa = C2PSA(c1=256, c2=256, n=3, e=0.5)
>>> input_tensor = torch.randn(1, 256, 64, 64)
>>> output_tensor = c2psa(input_tensor)
"""

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))

class PSABlock(nn.Module):

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 = Attention(c, attn_ratio=attn_ratio, num_heads=num_heads)
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 LinearAttention(nn.Module):
def __init__(self, dim, num_heads):
super().__init__()
self.dim = dim
self.num_heads = num_heads

self.qkv = nn.Linear(dim, 3 * dim, bias=False)
self.proj = nn.Linear(dim, dim)

def forward(self, x):
b, c, h, w = x.shape

x = x.view(b, c, h * w).permute(0, 2, 1) # (b, h*w, c)

qkv = self.qkv(x).reshape(b, h * w, 3, self.num_heads, self.dim // self.num_heads).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2]

key = F.softmax(k, dim=-1)
query = F.softmax(q, dim=-2)
context = key.transpose(-2, -1) @ v
x = (query @ context).reshape(b, h * w, c)

x = self.proj(x)

x = x.permute(0, 2, 1).view(b, c, h, w)

return x

class DepthwiseConv(nn.Module):
def __init__(self, in_channels, kernel_size):
super(DepthwiseConv, self).__init__()
self.depthwise = nn.Conv2d(in_channels, in_channels, kernel_size=kernel_size, groups=in_channels,
padding=kernel_size // 2)
self.relu = nn.ReLU()

def forward(self, x):
residual = x
x = self.depthwise(x)
x = x + residual
x = self.relu(x)
return x

class PSABlock_DML(PSABlock):
def __init__(self, c, attn_ratio=0.5, num_heads=4, shortcut=True) -> None:
super().__init__(c, attn_ratio, num_heads, shortcut)

self.ffn = MixFFN(c, 16)

class C2PSA_DML(C2PSA):
def __init__(self, c1, c2, n=1, e=0.5):
super().__init__(c1, c2, n, e)

self.m = nn.Sequential(*(PSABlock_DML(self.c, attn_ratio=0.5, num_heads=self.c // 64) for _ in range(n)))

🍀🍀步骤2:__init__.py文件修改

将C2PSA_DML.py文件中的C2PSA_DML模块添加到ultralytics\\nn\\modules\\__init__.py文件中:1)from .custom_modules import HWD  导入HWD模块;2)__all__全局部分添加

🍀🍀步骤3:tasks.py文件修改

先在ultralytics/nn/tasks.py代码最前端from ultralytics.nn.modules import 导入一下C2PSA_DML模块

from ultralytics.nn.modules.C2PSA_DML import C2PSA_DML

然后,tasks.py文件中找到parse_model函数(ctrl+f 可以直接搜索parse_model位置)导入C2PSA_DML模块:

🍀🍀步骤4:创建YAML配置文件

以YOLOv11为例,创建yolo11-C2PSA-DML.yaml配置文件,代码如下:

# Ultralytics 🚀 AGPL-3.0 License – https://ultralytics.com/license

# Ultralytics YOLO11 object detection model with P3/8 – P5/32 outputs
# Model docs: https://docs.ultralytics.com/models/yolo11
# Task docs: 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: 181 layers, 2624080 parameters, 2624064 gradients, 6.6 GFLOPs
s: [0.50, 0.50, 1024] # summary: 181 layers, 9458752 parameters, 9458736 gradients, 21.7 GFLOPs
m: [0.50, 1.00, 512] # summary: 231 layers, 20114688 parameters, 20114672 gradients, 68.5 GFLOPs
l: [1.00, 1.00, 512] # summary: 357 layers, 25372160 parameters, 25372144 gradients, 87.6 GFLOPs
x: [1.00, 1.50, 512] # summary: 357 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_DML, [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:新建train.py文件训练模型

import warnings
warnings.filterwarnings('ignore')
from ultralytics import YOLO

if __name__ == '__main__':
model = YOLO('ultralytics/cfg/models/11/yolo11-C2PSA-DML.yaml') # 导入yaml配置文件
# model.load('yolo11n.pt') # loading pretrain weights
model.train(data='dataset/data.yaml',
cache=False,
imgsz=640,
epochs=300,
batch=32,
close_mosaic=0,
workers=4, # Windows下出现莫名其妙卡主的情况可以尝试把workers设置为0
# device='0',
optimizer='SGD', # using SGD
# patience=0, # set 0 to close earlystop.
# resume=True, # 断点续训,YOLO初始化时选择last.pt
# amp=False, # close amp
# fraction=0.2,
project='runs/train',
name='yolo11-C2PSA-DML',
)

赞(0)
未经允许不得转载:171主机测评 » YOLO系列算法改进 | 融合DML轻量级动态混合层改进C2PSA模块 | 提升超分辨率重建质量
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址