当前位置:   article > 正文

YOLOv5改进--添加CBAM注意力机制_yolov5 cbam

yolov5 cbam

注意力机制包括CBAM、CA、ECA、SE、S2A、SimAM等,接下来介绍具体添加方式。

  1.  CBAM代码,在common文件中添加以下模块:
  1. class CBAMC3(nn.Module):
  2. # CSP Bottleneck with 3 convolutions
  3. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
  4. super(CBAMC3, self).__init__()
  5. c_ = int(c2 * e) # hidden channels
  6. self.cv1 = Conv(c1, c_, 1, 1)
  7. self.cv2 = Conv(c1, c_, 1, 1)
  8. self.cv3 = Conv(2 * c_, c2, 1)
  9. self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
  10. self.channel_attention = ChannelAttention(c2, 16)
  11. self.spatial_attention = SpatialAttention(7)
  12. # self.m = nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)])
  13. def forward(self, x):
  14. # 将最后的标准卷积模块改为了注意力机制提取特征
  15. return self.spatial_attention(
  16. self.channel_attention(self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))))

 2. 在yolo文件中,定位到parse_model函数,在C3Ghost后面加入CBAMC3模块

  1. if m in (Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,BottleneckCSP, C3, C3TR, C3SPP, C3Ghost):
  2. c1, c2 = ch[f], args[0]
  3. if c2 != no: # if not output
  4. c2 = make_divisible(c2 * gw, 8)
  5. args = [c1, c2, *args[1:]]
  6. if m in [BottleneckCSP, C3, C3TR, C3Ghost]:
  7. args.insert(2, n) # number of repeats
  8. n = 1

 3.在yolov5s.yaml文件中修改网络结构,可以在backbone中添加一层

  1. [[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
  2. [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
  3. [-1, 3, C3, [128]],
  4. [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
  5. [-1, 6, C3, [256]],
  6. [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
  7. [-1, 9, C3, [512]],
  8. [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
  9. [-1, 3, C3, [1024]],
  10. [-1, 1, CBAMC3,[1024]],
  11. [-1, 1, SPPF, [1024, 5]], # 9
  12. ]

则下面的head也得修改,p4,p5以及最后的总层数都得+1。

  1. [[-1, 1, Conv, [512, 1, 1]],
  2. [-1, 1, nn.Upsample, [None, 2, 'nearest']],
  3. [[-1, 6], 1, Concat, [1]], # cat backbone P4
  4. [-1, 3, C3, [512, False]], # 13
  5. [-1, 1, Conv, [256, 1, 1]],
  6. [-1, 1, nn.Upsample, [None, 2, 'nearest']],
  7. [[-1, 4], 1, Concat, [1]], # cat backbone P3
  8. [-1, 3, C3, [256, False]], # 17 (P3/8-small)
  9. [-1, 1, Conv, [256, 3, 2]],
  10. [[-1, 15], 1, Concat, [1]], # cat head P4
  11. [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
  12. [-1, 1, Conv, [512, 3, 2]],
  13. [[-1, 11], 1,Concat, [1]], # cat head P5
  14. [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
  15. [[18, 21, 24], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
  16. ]

正常训练即可。

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

闽ICP备14008679号