yshuqiao / steelDetect

Apache License 2.0
3 stars 1 forks source link

此项目github地址为https://github.com/yshuqiao/steelDetect,码云地址为https://gitee.com/yang_shuqiao/steelDetect

mmdetection原本工具使用

tools文件夹下另增的脚本

在mmdetection基础上修改的地方

resnet.py regnet.py schedule_1x.py
se cbam cosineAnnealing

1.resnet.py中增加SE通道注意力
主要是在resnet.py里面添加SELayer类:

class SELayer(nn.Module):
    def __init__(self,channel,reduction=16):
        super(SELayer,self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.fc = nn.Sequential(
            nn.Linear(channel,channel//reduction,bias=False),
            nn.ReLU(inplace=True),
            nn.Linear(channel//reduction,channel,bias=False),
            nn.Sigmoid()
        )
    def forward(self,x):
        b,c,_,_ = x.size()
        y = self.avg_pool(x).view(b,c)
        y = self.fc(y).view(b,c,1,1)
        return x*y.expand_as(x)

并在Bottleneck模块类中添加self.se参数,在其中的forward函数里添加:

if self.se:
    se_block = SELayer(self.planes)
    out = se_block(out)

Bottleneck类中也能看到,如果加入generalized_attention模块(Transformer)这样的插件的话,会插入到Bottleneck中第一个卷积层conv1(卷积核大小为3x3,紧接着BN层和relu)和第二个卷积层conv2之间。

2.regnet.py中增加CBAM混合注意力,可以参考https://zhuanlan.zhihu.com/p/99261200
在类中添加self.se参数(其Bottleneck类会调用resnext.py中的Bottleneck,而resnext.py中的Bottleneck继承了resnet.py的Bottleneck)和self.cbam参数,
如果self.cbam为True,则初始化ChannelAttention类和SpatialAttention类,相应地,在前传函数forward中的最后一个阶段后面添加cbam。
而如果self.se为True,则对第三阶段和第四阶段的残差层传入self.se=True的参数值,使残差层中每一个Bottleneck的残差支路末尾,即在与恒等映射支路相加之前添加SE模块。 3.把schedule_1x.py中的step学习率衰减策略改为cosineAnnealing学习率衰减策略。
根据https://github.com/open-mmlab/mmdetection/blob/master/docs/tutorials/customize_runtime.md,即把

lr_config = dict(
    policy='step',
    warmup='linear',  # 可改为余弦退火算法
    warmup_iters=500,  # 在初始的500次迭代中学习率逐渐增加
    warmup_ratio=0.001,  # 起始的学习率
    step=[8, 11]  # 在第8和11个epoch时降低学习率,可调成step=[16, 19]
)

改为

lr_config = dict(
    policy='CosineAnnealing',
    warmup='linear',
    warmup_iters=1000,
    warmup_ratio=1.0/10,
    min_lr_ratio=1e-5,
)

其他