学习资源站

YOLOv11改进-Conv_卷积篇-2024最新高效的超分辨率特征提取模块MAB二次创新C3k2助力yolov11有效涨点(全网独家创新)

一、本文介绍

本文给大家带来的最新改进机制是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通过多尺度和大核注意力机制的结合,以及门控空间注意力单元的引入,在高效特征提取的基础上提升了 超分辨率任务中 的图像细节恢复效果。


三、核心代码

核心代码的使用方式看章节四!

  1. # -*- coding: utf-8 -*-
  2. import math
  3. import torch
  4. import torch.nn as nn
  5. import torch.nn.functional as F
  6. from basicsr.utils.registry import ARCH_REGISTRY
  7. # LKA from VAN (https://github.com/Visual-Attention-Network)
  8. class LKA(nn.Module):
  9. def __init__(self, dim):
  10. super().__init__()
  11. self.conv0 = nn.Conv2d(dim, dim, 7, padding=7 // 2, groups=dim)
  12. self.conv_spatial = nn.Conv2d(dim, dim, 9, stride=1, padding=((9 // 2) * 4), groups=dim, dilation=4)
  13. self.conv1 = nn.Conv2d(dim, dim, 1)
  14. def forward(self, x):
  15. u = x.clone()
  16. attn = self.conv0(x)
  17. attn = self.conv_spatial(attn)
  18. attn = self.conv1(attn)
  19. return u * attn
  20. class Attention(nn.Module):
  21. def __init__(self, n_feats):
  22. super().__init__()
  23. self.norm = LayerNorm(n_feats, data_format='channels_first')
  24. self.scale = nn.Parameter(torch.zeros((1, n_feats, 1, 1)), requires_grad=True)
  25. self.proj_1 = nn.Conv2d(n_feats, n_feats, 1)
  26. self.spatial_gating_unit = LKA(n_feats)
  27. self.proj_2 = nn.Conv2d(n_feats, n_feats, 1)
  28. def forward(self, x):
  29. shorcut = x.clone()
  30. x = self.proj_1(self.norm(x))
  31. x = self.spatial_gating_unit(x)
  32. x = self.proj_2(x)
  33. x = x * self.scale + shorcut
  34. return x
  35. # ----------------------------------------------------------------------------------------------------------------
  36. class MLP(nn.Module):
  37. def __init__(self, n_feats):
  38. super().__init__()
  39. self.norm = LayerNorm(n_feats, data_format='channels_first')
  40. self.scale = nn.Parameter(torch.zeros((1, n_feats, 1, 1)), requires_grad=True)
  41. i_feats = 2 * n_feats
  42. self.fc1 = nn.Conv2d(n_feats, i_feats, 1, 1, 0)
  43. self.act = nn.GELU()
  44. self.fc2 = nn.Conv2d(i_feats, n_feats, 1, 1, 0)
  45. def forward(self, x):
  46. shortcut = x.clone()
  47. x = self.norm(x)
  48. x = self.fc1(x)
  49. x = self.act(x)
  50. x = self.fc2(x)
  51. return x * self.scale + shortcut
  52. class CFF(nn.Module):
  53. def __init__(self, n_feats, drop=0.0, k=2, squeeze_factor=15, attn='GLKA'):
  54. super().__init__()
  55. i_feats = n_feats * 2
  56. self.Conv1 = nn.Conv2d(n_feats, i_feats, 1, 1, 0)
  57. self.DWConv1 = nn.Sequential(
  58. nn.Conv2d(i_feats, i_feats, 7, 1, 7 // 2, groups=n_feats),
  59. nn.GELU())
  60. self.Conv2 = nn.Conv2d(i_feats, n_feats, 1, 1, 0)
  61. self.norm = LayerNorm(n_feats, data_format='channels_first')
  62. self.scale = nn.Parameter(torch.zeros((1, n_feats, 1, 1)), requires_grad=True)
  63. def forward(self, x):
  64. shortcut = x.clone()
  65. # Ghost Expand
  66. x = self.Conv1(self.norm(x))
  67. x = self.DWConv1(x)
  68. x = self.Conv2(x)
  69. return x * self.scale + shortcut
  70. class SimpleGate(nn.Module):
  71. def __init__(self, n_feats):
  72. super().__init__()
  73. i_feats = n_feats * 2
  74. self.Conv1 = nn.Conv2d(n_feats, i_feats, 1, 1, 0)
  75. # self.DWConv1 = nn.Conv2d(n_feats, n_feats, 7, 1, 7//2, groups= n_feats)
  76. self.Conv2 = nn.Conv2d(n_feats, n_feats, 1, 1, 0)
  77. self.norm = LayerNorm(n_feats, data_format='channels_first')
  78. self.scale = nn.Parameter(torch.zeros((1, n_feats, 1, 1)), requires_grad=True)
  79. def forward(self, x):
  80. shortcut = x.clone()
  81. # Ghost Expand
  82. x = self.Conv1(self.norm(x))
  83. a, x = torch.chunk(x, 2, dim=1)
  84. x = x * a # self.DWConv1(a)
  85. x = self.Conv2(x)
  86. return x * self.scale + shortcut
  87. # -----------------------------------------------------------------------------------------------------------------
  88. # RCAN-style
  89. class RCBv6(nn.Module):
  90. def __init__(
  91. self, n_feats, k, lk=7, res_scale=1.0, style='X', act=nn.SiLU(), deploy=False):
  92. super().__init__()
  93. self.LKA = nn.Sequential(
  94. nn.Conv2d(n_feats, n_feats, 5, 1, lk // 2, groups=n_feats),
  95. nn.Conv2d(n_feats, n_feats, 7, stride=1, padding=9, groups=n_feats, dilation=3),
  96. nn.Conv2d(n_feats, n_feats, 1, 1, 0),
  97. nn.Sigmoid())
  98. # self.LFE2 = LFEv3(n_feats, attn ='CA')
  99. self.LFE = nn.Sequential(
  100. nn.Conv2d(n_feats, n_feats, 3, 1, 1),
  101. nn.GELU(),
  102. nn.Conv2d(n_feats, n_feats, 3, 1, 1))
  103. def forward(self, x, pre_attn=None, RAA=None):
  104. shortcut = x.clone()
  105. x = self.LFE(x)
  106. x = self.LKA(x) * x
  107. return x + shortcut
  108. # -----------------------------------------------------------------------------------------------------------------
  109. class MLKA_Ablation(nn.Module):
  110. def __init__(self, n_feats, k=2, squeeze_factor=15):
  111. super().__init__()
  112. i_feats = 2 * n_feats
  113. self.n_feats = n_feats
  114. self.i_feats = i_feats
  115. self.norm = LayerNorm(n_feats, data_format='channels_first')
  116. self.scale = nn.Parameter(torch.zeros((1, n_feats, 1, 1)), requires_grad=True)
  117. k = 2
  118. # Multiscale Large Kernel Attention
  119. self.LKA7 = nn.Sequential(
  120. nn.Conv2d(n_feats // k, n_feats // k, 7, 1, 7 // 2, groups=n_feats // k),
  121. nn.Conv2d(n_feats // k, n_feats // k, 9, stride=1, padding=(9 // 2) * 4, groups=n_feats // k, dilation=4),
  122. nn.Conv2d(n_feats // k, n_feats // k, 1, 1, 0))
  123. self.LKA5 = nn.Sequential(
  124. nn.Conv2d(n_feats // k, n_feats // k, 5, 1, 5 // 2, groups=n_feats // k),
  125. nn.Conv2d(n_feats // k, n_feats // k, 7, stride=1, padding=(7 // 2) * 3, groups=n_feats // k, dilation=3),
  126. nn.Conv2d(n_feats // k, n_feats // k, 1, 1, 0))
  127. '''self.LKA3 = nn.Sequential(
  128. nn.Conv2d(n_feats//k, n_feats//k, 3, 1, 1, groups= n_feats//k),
  129. nn.Conv2d(n_feats//k, n_feats//k, 5, stride=1, padding=(5//2)*2, groups=n_feats//k, dilation=2),
  130. nn.Conv2d(n_feats//k, n_feats//k, 1, 1, 0))'''
  131. # self.X3 = nn.Conv2d(n_feats//k, n_feats//k, 3, 1, 1, groups= n_feats//k)
  132. self.X5 = nn.Conv2d(n_feats // k, n_feats // k, 5, 1, 5 // 2, groups=n_feats // k)
  133. self.X7 = nn.Conv2d(n_feats // k, n_feats // k, 7, 1, 7 // 2, groups=n_feats // k)
  134. self.proj_first = nn.Sequential(
  135. nn.Conv2d(n_feats, i_feats, 1, 1, 0))
  136. self.proj_last = nn.Sequential(
  137. nn.Conv2d(n_feats, n_feats, 1, 1, 0))
  138. def forward(self, x, pre_attn=None, RAA=None):
  139. shortcut = x.clone()
  140. x = self.norm(x)
  141. x = self.proj_first(x)
  142. a, x = torch.chunk(x, 2, dim=1)
  143. # u_1, u_2, u_3= torch.chunk(u, 3, dim=1)
  144. a_1, a_2 = torch.chunk(a, 2, dim=1)
  145. a = torch.cat([self.LKA7(a_1) * self.X7(a_1), self.LKA5(a_2) * self.X5(a_2)], dim=1)
  146. x = self.proj_last(x * a) * self.scale + shortcut
  147. return x
  148. # -----------------------------------------------------------------------------------------------------------------
  149. class LayerNorm(nn.Module):
  150. r""" LayerNorm that supports two data formats: channels_last (default) or channels_first.
  151. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with
  152. shape (batch_size, height, width, channels) while channels_first corresponds to inputs
  153. with shape (batch_size, channels, height, width).
  154. """
  155. def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"):
  156. super().__init__()
  157. self.weight = nn.Parameter(torch.ones(normalized_shape))
  158. self.bias = nn.Parameter(torch.zeros(normalized_shape))
  159. self.eps = eps
  160. self.data_format = data_format
  161. if self.data_format not in ["channels_last", "channels_first"]:
  162. raise NotImplementedError
  163. self.normalized_shape = (normalized_shape,)
  164. def forward(self, x):
  165. if self.data_format == "channels_last":
  166. return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
  167. elif self.data_format == "channels_first":
  168. u = x.mean(1, keepdim=True)
  169. s = (x - u).pow(2).mean(1, keepdim=True)
  170. x = (x - u) / torch.sqrt(s + self.eps)
  171. x = self.weight[:, None, None] * x + self.bias[:, None, None]
  172. return x
  173. class SGAB(nn.Module):
  174. def __init__(self, n_feats, drop=0.0, k=2, squeeze_factor=15, attn='GLKA'):
  175. super().__init__()
  176. i_feats = n_feats * 2
  177. self.Conv1 = nn.Conv2d(n_feats, i_feats, 1, 1, 0)
  178. self.DWConv1 = nn.Conv2d(n_feats, n_feats, 7, 1, 7 // 2, groups=n_feats)
  179. self.Conv2 = nn.Conv2d(n_feats, n_feats, 1, 1, 0)
  180. self.norm = LayerNorm(n_feats, data_format='channels_first')
  181. self.scale = nn.Parameter(torch.zeros((1, n_feats, 1, 1)), requires_grad=True)
  182. def forward(self, x):
  183. shortcut = x.clone()
  184. # Ghost Expand
  185. x = self.Conv1(self.norm(x))
  186. a, x = torch.chunk(x, 2, dim=1)
  187. x = x * self.DWConv1(a)
  188. x = self.Conv2(x)
  189. return x * self.scale + shortcut
  190. class GroupGLKA(nn.Module):
  191. def __init__(self, n_feats, k=2, squeeze_factor=15):
  192. super().__init__()
  193. i_feats = 2 * n_feats
  194. self.n_feats = n_feats
  195. self.i_feats = i_feats
  196. self.norm = LayerNorm(n_feats, data_format='channels_first')
  197. self.scale = nn.Parameter(torch.zeros((1, n_feats, 1, 1)), requires_grad=True)
  198. # 分为两个分支,分别有 n_feats // 2 个通道
  199. split1 = n_feats // 2
  200. split2 = n_feats - split1 # 确保通道总数匹配
  201. # 定义两个不同尺度的卷积块,适应新的分支数量
  202. self.LKA7 = nn.Sequential(
  203. nn.Conv2d(split2, split2, 7, 1, padding=7 // 2, groups=split2),
  204. nn.Conv2d(split2, split2, 9, stride=1, padding=(9 // 2) * 4, groups=split2, dilation=4),
  205. nn.Conv2d(split2, split2, 1, 1, 0)
  206. )
  207. self.LKA5 = nn.Sequential(
  208. nn.Conv2d(split1, split1, 5, 1, padding=5 // 2, groups=split1),
  209. nn.Conv2d(split1, split1, 7, stride=1, padding=(7 // 2) * 3, groups=split1, dilation=3),
  210. nn.Conv2d(split1, split1, 1, 1, 0)
  211. )
  212. # 定义额外的卷积层,适应新的分支数量
  213. self.X5 = nn.Conv2d(split1, split1, 5, 1, padding=5 // 2, groups=split1)
  214. self.X7 = nn.Conv2d(split2, split2, 7, 1, padding=7 // 2, groups=split2)
  215. self.proj_first = nn.Sequential(
  216. nn.Conv2d(n_feats, i_feats, 1, 1, 0))
  217. self.proj_last = nn.Sequential(
  218. nn.Conv2d(n_feats, n_feats, 1, 1, 0))
  219. def forward(self, x, pre_attn=None, RAA=None):
  220. shortcut = x.clone()
  221. x = self.norm(x)
  222. x = self.proj_first(x)
  223. # 将特征分为两个部分,a 和 x
  224. a, x = torch.chunk(x, 2, dim=1)
  225. # 将 a 分为两个分支,分别应用不同尺度的卷积操作
  226. a_1, a_2 = torch.chunk(a, 2, dim=1)
  227. a = torch.cat([self.LKA5(a_1) * self.X5(a_1), self.LKA7(a_2) * self.X7(a_2)], dim=1)
  228. x = self.proj_last(x * a) * self.scale + shortcut
  229. return x
  230. # MAB
  231. class MAB(nn.Module):
  232. def __init__(
  233. self, n_feats):
  234. super().__init__()
  235. self.LKA = GroupGLKA(n_feats)
  236. self.LFE = SGAB(n_feats)
  237. def forward(self, x, pre_attn=None, RAA=None):
  238. # large kernel attention
  239. x = self.LKA(x)
  240. # local feature extraction
  241. x = self.LFE(x)
  242. return x
  243. class LKAT(nn.Module):
  244. def __init__(self, n_feats):
  245. super().__init__()
  246. # self.norm = LayerNorm(n_feats, data_format='channels_first')
  247. # self.scale = nn.Parameter(torch.zeros((1, n_feats, 1, 1)), requires_grad=True)
  248. self.conv0 = nn.Sequential(
  249. nn.Conv2d(n_feats, n_feats, 1, 1, 0),
  250. nn.GELU())
  251. self.att = nn.Sequential(
  252. nn.Conv2d(n_feats, n_feats, 7, 1, 7 // 2, groups=n_feats),
  253. nn.Conv2d(n_feats, n_feats, 9, stride=1, padding=(9 // 2) * 3, groups=n_feats, dilation=3),
  254. nn.Conv2d(n_feats, n_feats, 1, 1, 0))
  255. self.conv1 = nn.Conv2d(n_feats, n_feats, 1, 1, 0)
  256. def forward(self, x):
  257. x = self.conv0(x)
  258. x = x * self.att(x)
  259. x = self.conv1(x)
  260. return x
  261. class ResGroup(nn.Module):
  262. def __init__(self, n_resblocks, n_feats, res_scale=1.0):
  263. super(ResGroup, self).__init__()
  264. self.body = nn.ModuleList([
  265. MAB(n_feats) \
  266. for _ in range(n_resblocks)])
  267. self.body_t = LKAT(n_feats)
  268. def forward(self, x):
  269. res = x.clone()
  270. for i, block in enumerate(self.body):
  271. res = block(res)
  272. x = self.body_t(res) + x
  273. return x
  274. class MeanShift(nn.Conv2d):
  275. def __init__(
  276. self, rgb_range,
  277. rgb_mean=(0.4488, 0.4371, 0.4040), rgb_std=(1.0, 1.0, 1.0), sign=-1):
  278. super(MeanShift, self).__init__(3, 3, kernel_size=1)
  279. std = torch.Tensor(rgb_std)
  280. self.weight.data = torch.eye(3).view(3, 3, 1, 1) / std.view(3, 1, 1, 1)
  281. self.bias.data = sign * rgb_range * torch.Tensor(rgb_mean) / std
  282. for p in self.parameters():
  283. p.requires_grad = False
  284. @ARCH_REGISTRY.register()
  285. class MAN(nn.Module):
  286. def __init__(self, n_resblocks=36, n_resgroups=1, n_colors=3, n_feats=180, scale=2, res_scale=1.0):
  287. super(MAN, self).__init__()
  288. # res_scale = res_scale
  289. self.n_resgroups = n_resgroups
  290. self.sub_mean = MeanShift(1.0)
  291. self.head = nn.Conv2d(n_colors, n_feats, 3, 1, 1)
  292. # define body module
  293. self.body = nn.ModuleList([
  294. ResGroup(
  295. n_resblocks, n_feats, res_scale=res_scale)
  296. for i in range(n_resgroups)])
  297. if self.n_resgroups > 1:
  298. self.body_t = nn.Conv2d(n_feats, n_feats, 3, 1, 1)
  299. # define tail module
  300. self.tail = nn.Sequential(
  301. nn.Conv2d(n_feats, n_colors * (scale ** 2), 3, 1, 1),
  302. nn.PixelShuffle(scale)
  303. )
  304. self.add_mean = MeanShift(1.0, sign=1)
  305. def forward(self, x):
  306. x = self.sub_mean(x)
  307. x = self.head(x)
  308. res = x
  309. for i in self.body:
  310. res = i(res)
  311. if self.n_resgroups > 1:
  312. res = self.body_t(res) + x
  313. x = self.tail(res)
  314. x = self.add_mean(x)
  315. return x
  316. def visual_feature(self, x):
  317. fea = []
  318. x = self.head(x)
  319. res = x
  320. for i in self.body:
  321. temp = res
  322. res = i(res)
  323. fea.append(res)
  324. res = self.body_t(res) + x
  325. x = self.tail(res)
  326. return x, fea
  327. def load_state_dict(self, state_dict, strict=False):
  328. own_state = self.state_dict()
  329. for name, param in state_dict.items():
  330. if name in own_state:
  331. if isinstance(param, nn.Parameter):
  332. param = param.data
  333. try:
  334. own_state[name].copy_(param)
  335. except Exception:
  336. if name.find('tail') >= 0:
  337. print('Replace pre-trained upsampler to new one...')
  338. else:
  339. raise RuntimeError('While copying the parameter named {}, '
  340. 'whose dimensions in the model are {} and '
  341. 'whose dimensions in the checkpoint are {}.'
  342. .format(name, own_state[name].size(), param.size()))
  343. elif strict:
  344. if name.find('tail') == -1:
  345. raise KeyError('unexpected key "{}" in state_dict'
  346. .format(name))
  347. if strict:
  348. missing = set(own_state.keys()) - set(state_dict.keys())
  349. if len(missing) > 0:
  350. raise KeyError('missing keys in state_dict: "{}"'.format(missing))
  351. class Bottleneck(nn.Module):
  352. """Standard bottleneck."""
  353. def __init__(self, c1, c2, shortcut=True, g=1, k=(3, 3), e=0.5):
  354. """Initializes a standard bottleneck module with optional shortcut connection and configurable parameters."""
  355. super().__init__()
  356. c_ = int(c2 * e) # hidden channels
  357. self.cv1 = Conv(c1, c_, k[0], 1)
  358. self.cv2 = Conv(c_, c2, k[1], 1, g=g)
  359. self.add = shortcut and c1 == c2
  360. def forward(self, x):
  361. """Applies the YOLO FPN to input data."""
  362. return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
  363. class C2f(nn.Module):
  364. """Faster Implementation of CSP Bottleneck with 2 convolutions."""
  365. def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5):
  366. """Initializes a CSP bottleneck with 2 convolutions and n Bottleneck blocks for faster processing."""
  367. super().__init__()
  368. self.c = int(c2 * e) # hidden channels
  369. self.cv1 = Conv(c1, 2 * self.c, 1, 1)
  370. self.cv2 = Conv((2 + n) * self.c, c2, 1) # optional act=FReLU(c2)
  371. self.m = nn.ModuleList(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n))
  372. def forward(self, x):
  373. """Forward pass through C2f layer."""
  374. y = list(self.cv1(x).chunk(2, 1))
  375. y.extend(m(y[-1]) for m in self.m)
  376. return self.cv2(torch.cat(y, 1))
  377. def forward_split(self, x):
  378. """Forward pass using split() instead of chunk()."""
  379. y = list(self.cv1(x).split((self.c, self.c), 1))
  380. y.extend(m(y[-1]) for m in self.m)
  381. return self.cv2(torch.cat(y, 1))
  382. def autopad(k, p=None, d=1): # kernel, padding, dilation
  383. """Pad to 'same' shape outputs."""
  384. if d > 1:
  385. k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k] # actual kernel-size
  386. if p is None:
  387. p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
  388. return p
  389. class Conv(nn.Module):
  390. """Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation)."""
  391. default_act = nn.SiLU() # default activation
  392. def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
  393. """Initialize Conv layer with given arguments including activation."""
  394. super().__init__()
  395. self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
  396. self.bn = nn.BatchNorm2d(c2)
  397. self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()
  398. def forward(self, x):
  399. """Apply convolution, batch normalization and activation to input tensor."""
  400. return self.act(self.bn(self.conv(x)))
  401. def forward_fuse(self, x):
  402. """Perform transposed convolution of 2D data."""
  403. return self.act(self.conv(x))
  404. class C3(nn.Module):
  405. """CSP Bottleneck with 3 convolutions."""
  406. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
  407. """Initialize the CSP Bottleneck with given channels, number, shortcut, groups, and expansion values."""
  408. super().__init__()
  409. c_ = int(c2 * e) # hidden channels
  410. self.cv1 = Conv(c1, c_, 1, 1)
  411. self.cv2 = Conv(c1, c_, 1, 1)
  412. self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2)
  413. self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, k=((1, 1), (3, 3)), e=1.0) for _ in range(n)))
  414. def forward(self, x):
  415. """Forward pass through the CSP bottleneck with 2 convolutions."""
  416. return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))
  417. class C3k(C3):
  418. """C3k is a CSP bottleneck module with customizable kernel sizes for feature extraction in neural networks."""
  419. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, k=3):
  420. """Initializes the C3k module with specified channels, number of layers, and configurations."""
  421. super().__init__(c1, c2, n, shortcut, g, e)
  422. c_ = int(c2 * e) # hidden channels
  423. # self.m = nn.Sequential(*(RepBottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
  424. self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
  425. class C3k_MAB(C3):
  426. """C3k is a CSP bottleneck module with customizable kernel sizes for feature extraction in neural networks."""
  427. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, k=3):
  428. """Initializes the C3k module with specified channels, number of layers, and configurations."""
  429. super().__init__(c1, c2, n, shortcut, g, e)
  430. c_ = int(c2 * e) # hidden channels
  431. # self.m = nn.Sequential(*(RepBottleneck(c_, c_, shortcut, g, k=(k, k), e=1.0) for _ in range(n)))
  432. self.m = nn.Sequential(*(MAB(c_) for _ in range(n)))
  433. class C3k2_MAB1(C2f):
  434. """Faster Implementation of CSP Bottleneck with 2 convolutions."""
  435. def __init__(self, c1, c2, n=1, c3k=False, e=0.5, g=1, shortcut=True):
  436. """Initializes the C3k2 module, a faster CSP Bottleneck with 2 convolutions and optional C3k blocks."""
  437. super().__init__(c1, c2, n, shortcut, g, e)
  438. self.m = nn.ModuleList(
  439. C3k(self.c, self.c, 2, shortcut, g) if c3k else MAB(self.c) for _ in range(n)
  440. )
  441. class C3k2_MAB2(C2f):
  442. """Faster Implementation of CSP Bottleneck with 2 convolutions."""
  443. def __init__(self, c1, c2, n=1, c3k=False, e=0.5, g=1, shortcut=True):
  444. """Initializes the C3k2 module, a faster CSP Bottleneck with 2 convolutions and optional C3k blocks."""
  445. super().__init__(c1, c2, n, shortcut, g, e)
  446. self.m = nn.ModuleList(
  447. C3k_MAB(self.c, self.c, 2, shortcut, g) if c3k else MAB(self.c) for _ in range(n)
  448. )
  449. if __name__ == "__main__":
  450. # Generating Sample image
  451. image_size = (1, 36, 224, 224)
  452. image = torch.rand(*image_size)
  453. # Model
  454. model = MAB(36)
  455. out = model(image)
  456. 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

  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. # YOLO11 object detection model with P3-P5 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect
  3. # Parameters
  4. nc: 80 # number of classes
  5. scales: # model compound scaling constants, i.e. 'model=yolo11n.yaml' will call yolo11.yaml with scale 'n'
  6. # [depth, width, max_channels]
  7. n: [0.50, 0.25, 1024] # summary: 319 layers, 2624080 parameters, 2624064 gradients, 6.6 GFLOPs
  8. s: [0.50, 0.50, 1024] # summary: 319 layers, 9458752 parameters, 9458736 gradients, 21.7 GFLOPs
  9. m: [0.50, 1.00, 512] # summary: 409 layers, 20114688 parameters, 20114672 gradients, 68.5 GFLOPs
  10. l: [1.00, 1.00, 512] # summary: 631 layers, 25372160 parameters, 25372144 gradients, 87.6 GFLOPs
  11. x: [1.00, 1.50, 512] # summary: 631 layers, 56966176 parameters, 56966160 gradients, 196.0 GFLOPs
  12. # YOLO11n backbone
  13. backbone:
  14. # [from, repeats, module, args]
  15. - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2
  16. - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4
  17. - [-1, 2, C3k2_MAB1, [256, False, 0.25]]
  18. - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8
  19. - [-1, 2, C3k2_MAB1, [512, False, 0.25]]
  20. - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16
  21. - [-1, 2, C3k2_MAB1, [512, True]]
  22. - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32
  23. - [-1, 2, C3k2_MAB1, [1024, True]]
  24. - [-1, 1, SPPF, [1024, 5]] # 9
  25. - [-1, 2, C2PSA, [1024]] # 10
  26. # YOLO11n head
  27. head:
  28. - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
  29. - [[-1, 6], 1, Concat, [1]] # cat backbone P4
  30. - [-1, 2, C3k2_MAB1, [512, False]] # 13
  31. - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
  32. - [[-1, 4], 1, Concat, [1]] # cat backbone P3
  33. - [-1, 2, C3k2_MAB1, [256, False]] # 16 (P3/8-small)
  34. - [-1, 1, Conv, [256, 3, 2]]
  35. - [[-1, 13], 1, Concat, [1]] # cat head P4
  36. - [-1, 2, C3k2_MAB1, [512, False]] # 19 (P4/16-medium)
  37. - [-1, 1, Conv, [512, 3, 2]]
  38. - [[-1, 10], 1, Concat, [1]] # cat head P5
  39. - [-1, 2, C3k2_MAB1, [1024, True]] # 22 (P5/32-large)
  40. - [[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

  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. # YOLO11 object detection model with P3-P5 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect
  3. # Parameters
  4. nc: 80 # number of classes
  5. scales: # model compound scaling constants, i.e. 'model=yolo11n.yaml' will call yolo11.yaml with scale 'n'
  6. # [depth, width, max_channels]
  7. n: [0.50, 0.25, 1024] # summary: 319 layers, 2624080 parameters, 2624064 gradients, 6.6 GFLOPs
  8. s: [0.50, 0.50, 1024] # summary: 319 layers, 9458752 parameters, 9458736 gradients, 21.7 GFLOPs
  9. m: [0.50, 1.00, 512] # summary: 409 layers, 20114688 parameters, 20114672 gradients, 68.5 GFLOPs
  10. l: [1.00, 1.00, 512] # summary: 631 layers, 25372160 parameters, 25372144 gradients, 87.6 GFLOPs
  11. x: [1.00, 1.50, 512] # summary: 631 layers, 56966176 parameters, 56966160 gradients, 196.0 GFLOPs
  12. # YOLO11n backbone
  13. backbone:
  14. # [from, repeats, module, args]
  15. - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2
  16. - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4
  17. - [-1, 2, C3k2_MAB2, [256, False, 0.25]]
  18. - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8
  19. - [-1, 2, C3k2_MAB2, [512, False, 0.25]]
  20. - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16
  21. - [-1, 2, C3k2_MAB2, [512, True]]
  22. - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32
  23. - [-1, 2, C3k2_MAB2, [1024, True]]
  24. - [-1, 1, SPPF, [1024, 5]] # 9
  25. - [-1, 2, C2PSA, [1024]] # 10
  26. # YOLO11n head
  27. head:
  28. - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
  29. - [[-1, 6], 1, Concat, [1]] # cat backbone P4
  30. - [-1, 2, C3k2_MAB2, [512, False]] # 13
  31. - [-1, 1, nn.Upsample, [None, 2, "nearest"]]
  32. - [[-1, 4], 1, Concat, [1]] # cat backbone P3
  33. - [-1, 2, C3k2_MAB2, [256, False]] # 16 (P3/8-small)
  34. - [-1, 1, Conv, [256, 3, 2]]
  35. - [[-1, 13], 1, Concat, [1]] # cat head P4
  36. - [-1, 2, C3k2_MAB2, [512, False]] # 19 (P4/16-medium)
  37. - [-1, 1, Conv, [512, 3, 2]]
  38. - [[-1, 10], 1, Concat, [1]] # cat head P5
  39. - [-1, 2, C3k2_MAB2, [1024, True]] # 22 (P5/32-large)
  40. - [[16, 19, 22], 1, Detect, [nc]] # Detect(P3, P4, P5)

5.3 训练代码

大家可以创建一个py文件将我给的代码复制粘贴进去,配置好自己的文件路径即可运行。

  1. import warnings
  2. warnings.filterwarnings('ignore')
  3. from ultralytics import YOLO
  4. if __name__ == '__main__':
  5. model = YOLO('模型配置文件')
  6. # 如何切换模型版本, 上面的ymal文件可以改为 yolov8s.yaml就是使用的v8s,
  7. # 类似某个改进的yaml文件名称为yolov8-XXX.yaml那么如果想使用其它版本就把上面的名称改为yolov8l-XXX.yaml即可(改的是上面YOLO中间的名字不是配置文件的)!
  8. # model.load('yolov8n.pt') # 是否加载预训练权重,科研不建议大家加载否则很难提升精度
  9. model.train(data=r"C:\Users\Administrator\PycharmProjects\yolov5-master\yolov5-master\Construction Site Safety.v30-raw-images_latestversion.yolov8\data.yaml",
  10. # 如果大家任务是其它的'ultralytics/cfg/default.yaml'找到这里修改task可以改成detect, segment, classify, pose
  11. cache=False,
  12. imgsz=640,
  13. epochs=150,
  14. single_cls=False, # 是否是单类别检测
  15. batch=16,
  16. close_mosaic=0,
  17. workers=0,
  18. device='0',
  19. optimizer='SGD', # using SGD
  20. # resume='runs/train/exp21/weights/last.pt', # 如过想续训就设置last.pt的地址
  21. amp=True, # 如果出现训练损失为Nan可以关闭amp
  22. project='runs/train',
  23. name='exp',
  24. )


5.4 训练过程截图


五、本文总结

到此本文的正式分享内容就结束了,在这里给大家推荐我的YOLOv11改进有效涨点专栏,本专栏目前为新开的平均质量分98分,后期我会根据各种最新的前沿顶会进行论文复现,也会对一些老的改进机制进行补充,如果大家觉得本文帮助到你了,订阅本专栏,关注后续更多的更新~