当前位置:   article > 正文

改进YOLO:YOLOv8结合swin transformer

改进YOLO:YOLOv8结合swin transformer

目录

1、修改yaml文件

2、添加 SwinTransformer.py

3、修改 tasks.py

4、根目录增加文件


1、修改yaml文件

修改 ultralytics/cfg/models/v8/yolov8.yaml

  1. backbone:
  2. # [from, repeats, module, args]
  3. - [-1, 1, Conv, [64, 3, 2]] # 0-P1/2
  4. - [-1, 1, Conv, [128, 3, 2]] # 1-P2/4
  5. - [-1, 3, C2f, [128, True]]
  6. - [-1, 1, Conv, [256, 3, 2]] # 3-P3/8
  7. # - [-1, 6, C2f, [256, True]]
  8. - [-1, 6, SwinTransformer, [256, True]]
  9. - [-1, 1, Conv, [512, 3, 2]] # 5-P4/16
  10. - [-1, 6, C2f, [512, True]]
  11. - [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32
  12. - [-1, 3, C2f, [1024, True]]
  13. - [-1, 1, SPPF, [1024, 5]] # 9

C2f 那一行,替换为 SwinTransformer

2、添加 SwinTransformer.py

在 ultralytics/nn 下新增该文件

  1. import torch
  2. import torch.nn as nn
  3. # from .conv import Conv
  4. from ultralytics.nn.modules.conv import Conv
  5. import torch.nn.functional as F
  6. from timm.models.layers import DropPath as TimmDropPath
  7. from timm.models.layers import trunc_normal_
  8. class DropPath(TimmDropPath):
  9. def __init__(self, drop_prob=None):
  10. super().__init__(drop_prob=drop_prob)
  11. self.drop_prob = drop_prob
  12. def __repr__(self):
  13. msg = super().__repr__()
  14. msg += f'(drop_prob={self.drop_prob})'
  15. return msg
  16. class WindowAttention(nn.Module):
  17. def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
  18. super().__init__()
  19. self.dim = dim
  20. self.window_size = window_size # Wh, Ww
  21. self.num_heads = num_heads
  22. head_dim = dim // num_heads
  23. self.scale = qk_scale or head_dim ** -0.5
  24. # define a parameter table of relative position bias
  25. self.relative_position_bias_table = nn.Parameter(
  26. torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
  27. # get pair-wise relative position index for each token inside the window
  28. coords_h = torch.arange(self.window_size[0])
  29. coords_w = torch.arange(self.window_size[1])
  30. coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
  31. coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
  32. relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
  33. relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
  34. relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
  35. relative_coords[:, :, 1] += self.window_size[1] - 1
  36. relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
  37. relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
  38. self.register_buffer("relative_position_index", relative_position_index)
  39. self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
  40. self.attn_drop = nn.Dropout(attn_drop)
  41. self.proj = nn.Linear(dim, dim)
  42. self.proj_drop = nn.Dropout(proj_drop)
  43. nn.init.normal_(self.relative_position_bias_table, std=.02)
  44. self.softmax = nn.Softmax(dim=-1)
  45. def forward(self, x, mask=None):
  46. B_, N, C = x.shape
  47. qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
  48. q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
  49. q = q * self.scale
  50. attn = (q @ k.transpose(-2, -1))
  51. relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
  52. self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH
  53. relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
  54. attn = attn + relative_position_bias.unsqueeze(0)
  55. if mask is not None:
  56. nW = mask.shape[0]
  57. attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
  58. attn = attn.view(-1, self.num_heads, N, N)
  59. attn = self.softmax(attn)
  60. else:
  61. attn = self.softmax(attn)
  62. attn = self.attn_drop(attn)
  63. # print(attn.dtype, v.dtype)
  64. try:
  65. x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
  66. except:
  67. # print(attn.dtype, v.dtype)
  68. x = (attn.half() @ v).transpose(1, 2).reshape(B_, N, C)
  69. x = self.proj(x)
  70. x = self.proj_drop(x)
  71. return x
  72. class SwinTransformer(nn.Module):
  73. # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
  74. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
  75. super(SwinTransformer, self).__init__()
  76. c_ = int(c2 * e) # hidden channels
  77. self.cv1 = Conv(c1, c_, 1, 1)
  78. self.cv2 = Conv(c1, c_, 1, 1)
  79. self.cv3 = Conv(2 * c_, c2, 1, 1)
  80. num_heads = c_ // 32
  81. self.m = SwinTransformerBlock(c_, c_, num_heads, n)
  82. # self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
  83. def forward(self, x):
  84. y1 = self.m(self.cv1(x))
  85. y2 = self.cv2(x)
  86. return self.cv3(torch.cat((y1, y2), dim=1))
  87. class SwinTransformerB(nn.Module):
  88. # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
  89. def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
  90. super(SwinTransformerB, self).__init__()
  91. c_ = int(c2) # hidden channels
  92. self.cv1 = Conv(c1, c_, 1, 1)
  93. self.cv2 = Conv(c_, c_, 1, 1)
  94. self.cv3 = Conv(2 * c_, c2, 1, 1)
  95. num_heads = c_ // 32
  96. self.m = SwinTransformerBlock(c_, c_, num_heads, n)
  97. # self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
  98. def forward(self, x):
  99. x1 = self.cv1(x)
  100. y1 = self.m(x1)
  101. y2 = self.cv2(x1)
  102. return self.cv3(torch.cat((y1, y2), dim=1))
  103. class SwinTransformerC(nn.Module):
  104. # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
  105. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
  106. super(SwinTransformerC, self).__init__()
  107. c_ = int(c2 * e) # hidden channels
  108. self.cv1 = Conv(c1, c_, 1, 1)
  109. self.cv2 = Conv(c1, c_, 1, 1)
  110. self.cv3 = Conv(c_, c_, 1, 1)
  111. self.cv4 = Conv(2 * c_, c2, 1, 1)
  112. num_heads = c_ // 32
  113. self.m = SwinTransformerBlock(c_, c_, num_heads, n)
  114. # self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
  115. def forward(self, x):
  116. y1 = self.cv3(self.m(self.cv1(x)))
  117. y2 = self.cv2(x)
  118. return self.cv4(torch.cat((y1, y2), dim=1))
  119. class Mlp(nn.Module):
  120. def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.SiLU, drop=0.):
  121. super().__init__()
  122. out_features = out_features or in_features
  123. hidden_features = hidden_features or in_features
  124. self.fc1 = nn.Linear(in_features, hidden_features)
  125. self.act = act_layer()
  126. self.fc2 = nn.Linear(hidden_features, out_features)
  127. self.drop = nn.Dropout(drop)
  128. def forward(self, x):
  129. x = self.fc1(x)
  130. x = self.act(x)
  131. x = self.drop(x)
  132. x = self.fc2(x)
  133. x = self.drop(x)
  134. return x
  135. def window_partition(x, window_size):
  136. B, H, W, C = x.shape
  137. assert H % window_size == 0, 'feature map h and w can not divide by window size'
  138. x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
  139. windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
  140. return windows
  141. def window_reverse(windows, window_size, H, W):
  142. B = int(windows.shape[0] / (H * W / window_size / window_size))
  143. x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
  144. x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
  145. return x
  146. class SwinTransformerLayer(nn.Module):
  147. def __init__(self, dim, num_heads, window_size=8, shift_size=0,
  148. mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
  149. act_layer=nn.SiLU, norm_layer=nn.LayerNorm):
  150. super().__init__()
  151. self.dim = dim
  152. self.num_heads = num_heads
  153. self.window_size = window_size
  154. self.shift_size = shift_size
  155. self.mlp_ratio = mlp_ratio
  156. # if min(self.input_resolution) <= self.window_size:
  157. # # if window size is larger than input resolution, we don't partition windows
  158. # self.shift_size = 0
  159. # self.window_size = min(self.input_resolution)
  160. assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
  161. self.norm1 = norm_layer(dim)
  162. self.attn = WindowAttention(
  163. dim, window_size=(self.window_size, self.window_size), num_heads=num_heads,
  164. qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
  165. self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
  166. self.norm2 = norm_layer(dim)
  167. mlp_hidden_dim = int(dim * mlp_ratio)
  168. self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
  169. def create_mask(self, H, W):
  170. # calculate attention mask for SW-MSA
  171. img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1
  172. h_slices = (slice(0, -self.window_size),
  173. slice(-self.window_size, -self.shift_size),
  174. slice(-self.shift_size, None))
  175. w_slices = (slice(0, -self.window_size),
  176. slice(-self.window_size, -self.shift_size),
  177. slice(-self.shift_size, None))
  178. cnt = 0
  179. for h in h_slices:
  180. for w in w_slices:
  181. img_mask[:, h, w, :] = cnt
  182. cnt += 1
  183. mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
  184. mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
  185. attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
  186. attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
  187. return attn_mask
  188. def forward(self, x):
  189. # reshape x[b c h w] to x[b l c]
  190. _, _, H_, W_ = x.shape
  191. Padding = False
  192. if min(H_, W_) < self.window_size or H_ % self.window_size != 0 or W_ % self.window_size != 0:
  193. Padding = True
  194. # print(f'img_size {min(H_, W_)} is less than (or not divided by) window_size {self.window_size}, Padding.')
  195. pad_r = (self.window_size - W_ % self.window_size) % self.window_size
  196. pad_b = (self.window_size - H_ % self.window_size) % self.window_size
  197. x = F.pad(x, (0, pad_r, 0, pad_b))
  198. # print('2', x.shape)
  199. B, C, H, W = x.shape
  200. L = H * W
  201. x = x.permute(0, 2, 3, 1).contiguous().view(B, L, C) # b, L, c
  202. # create mask from init to forward
  203. if self.shift_size > 0:
  204. attn_mask = self.create_mask(H, W).to(x.device)
  205. else:
  206. attn_mask = None
  207. shortcut = x
  208. x = self.norm1(x)
  209. x = x.view(B, H, W, C)
  210. # cyclic shift
  211. if self.shift_size > 0:
  212. shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
  213. else:
  214. shifted_x = x
  215. # partition windows
  216. x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
  217. x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
  218. # W-MSA/SW-MSA
  219. attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
  220. # merge windows
  221. attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
  222. shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C
  223. # reverse cyclic shift
  224. if self.shift_size > 0:
  225. x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
  226. else:
  227. x = shifted_x
  228. x = x.view(B, H * W, C)
  229. # FFN
  230. x = shortcut + self.drop_path(x)
  231. x = x + self.drop_path(self.mlp(self.norm2(x)))
  232. x = x.permute(0, 2, 1).contiguous().view(-1, C, H, W) # b c h w
  233. if Padding:
  234. x = x[:, :, :H_, :W_] # reverse padding
  235. return x
  236. class SwinTransformerBlock(nn.Module):
  237. def __init__(self, c1, c2, num_heads, num_layers, window_size=8):
  238. super().__init__()
  239. self.conv = None
  240. if c1 != c2:
  241. self.conv = Conv(c1, c2)
  242. # remove input_resolution
  243. self.blocks = nn.Sequential(*[SwinTransformerLayer(dim=c2, num_heads=num_heads, window_size=window_size,
  244. shift_size=0 if (i % 2 == 0) else window_size // 2) for i in
  245. range(num_layers)])
  246. def forward(self, x):
  247. if self.conv is not None:
  248. x = self.conv(x)
  249. x = self.blocks(x)
  250. return x

3、修改 tasks.py

ultralytics/nn/tasks.py

添加

from ultralytics.nn.SwinTransformer import SwinTransformer

def parse_model函数

  1. if m in (Classify, Conv, ConvTranspose, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, Focus,
  2. BottleneckCSP, C1, C2, C2f, C3, C3TR, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x, RepC3):
  3. c1, c2 = ch[f], args[0]

改为:

  1. if m in (Classify, Conv, ConvTranspose, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, Focus,
  2. BottleneckCSP, C1, C2, C2f, C3, C3TR, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x, RepC3, SwinTransformer):
  3. c1, c2 = ch[f], args[0]

即结尾增加 SwinTransformer

4、根目录增加文件

data.yaml

  1. # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
  2. path: ../dataset_yolo # dataset root dir
  3. train: train # train images (relative to 'path') 128 images
  4. val: val # val images (relative to 'path') 128 images
  5. test: # test images (optional)
  6. # Classes
  7. names:
  8. 0: yb_text
  9. 1: kk_text
  10. 2: zsd_text
  11. 3: xn_text
  12. 4: controls_text
  13. 5: water_mark
  14. 6: yb
  15. 7: kk
  16. 8: zsd
  17. 9: xn
  18. # Download script/URL (optional)
  19. download: https://ultralytics.com/assets/coco128-seg.zip

train.py

不再载入与训练模型

  1. from ultralytics import YOLO
  2. # load a model
  3. # model = YOLO('yolov8m.pt')
  4. model = YOLO('yolov8m.yaml')
  5. # Train the model
  6. model.train(data='./data.yaml',epochs=300,batch=64,optimizer='SGD',close_mosaic=10,imgsz=640,device=[4],cache=True)
  7. # https://blog.csdn.net/apple_59275002/article/details/132181112
  8. # from ultralytics import YOLO
  9. # import os
  10. # model = YOLO('yolov8n.yaml')
  11. # model = YOLO('yolov8n.pt')
  12. # results = model.train(data='custom.yaml', epochs=80, batch=8, patience=0, augment=True, val=False, degrees=15, translate=0.05, scale=0.05, shear=0.05, perspective=0.0, mosaic=0.0, hsv_h=0.010, hsv_s=0.5, hsv_v=0.2)
  13. # results = model.val()
  14. # 更多参数见网址

训练文件  my_train.sh

nohup python train.py >>train.log 2>&1 &

训练即可

训练时提示如下表示模块加入成功

refer:

https://blog.csdn.net/weixin_51692073/article/details/132724315

https://www.bilibili.com/video/BV1T8411B7iP/

https://space.bilibili.com/432570190

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/371449
推荐阅读
相关标签
  

闽ICP备14008679号