• BBAVectors斜框检测网络更换轻量型主干网络


            本文将会手把手教会帅比看官如何更换BBAVectors斜框检测模型骨干网络。

            本博客假设各位看官帅比已经能利用BBAVectors训练自己的数据,但是不知道如何更换其主干网络。原始代码中采用的resnet101做为骨干网络,这个网络训练的时候对资源要求较高,那么如何换为更轻量的resnet18、mobilnet呢?

    一、主干网络修改为resnet18模型

    1、修改ctrbox_net.py中主干网络参数

    1. #修改前
    2. # self.base_network = resnet.resnet101(pretrained=pretrained)
    3. # self.dec_c2 = CombinationModule(512, 256, batch_norm=True)
    4. # self.dec_c3 = CombinationModule(1024, 512, batch_norm=True)
    5. # self.dec_c4 = CombinationModule(2048, 1024, batch_norm=True)
    6. #修改后
    7. self.base_network = resnet.resnet18(pretrained=pretrained)
    8. self.dec_c2 = CombinationModule(128, 64, batch_norm=True)
    9. self.dec_c3 = CombinationModule(256, 128, batch_norm=True)
    10. self.dec_c4 = CombinationModule(512, 256, batch_norm=True)

            首先我们要明白上面几个256、512、1024、2048其实分别是resnet101主干网络中4个featuremap的通道大小。而分析resnet.py的resnet18我们可知,他的4个featuremap的通道数分别是64、128、256、512,你只需要在resnet.py末尾加上下面几句代码,然后运行resnet.py即可知道,仅仅是通道数不同,所以我们直接修改上述参数即可。

    1. if __name__ == '__main__':
    2. device='cpu'
    3. input=np.ones((1,3,512,512)).astype(np.float32)
    4.     dummy_input = torch.from_numpy(input).to(device)
    5.    
    6. model=resnet18().to(device)
    7.     logit=model(dummy_input)
    8.     print(logit[-1].size()) #torch.Size([1, 512, 16, 16])
    9.     print(logit[-2].size()) #torch.Size([1, 256, 32, 32])
    10.     print(logit[-3].size()) #torch.Size([1, 128, 64, 64])
    11.     print(logit[-4].size()) #torch.Size([1, 64, 128, 128])

    2.修改 ctrbox_net.py中的 channels

            当 down_ratio=4的时候,c2_combine输出的通道数是256,这也是后面4个head的输入通道数, ctrbox_net .py的计算代码如下

    1. class CTRBOX(nn.Module):
    2. def __init__(self, heads, pretrained, down_ratio, final_kernel, head_conv,export=False):
    3. super(CTRBOX, self).__init__()
    4. channels = [3, 64, 256, 512, 1024, 2048]
    5. assert down_ratio in [2, 4, 8, 16]
    6. self.l1 = int(np.log2(down_ratio))

            head的输入通道数就是channels[self.l1]=256。但是改成resnet18之后,c2_combine输出的通道数变成了64。这个时候你就会自然而然将main.py中的down_ratio改成2,这样channels[self.l1]=64。

            如果你是通过修改down_ratio=2,就大错特错了。因为ctrbox_net最终的输出大小都是输入大小4倍下采样,即输入512x512,4个head的输出都是128*128,计算loss的时候,gt的大小也应该是128x128。而在dataset/base.py中也会用到down_ration,如果改成2,gt的大小是计算出来就是256x256,这样就会报错。        

    **解决方法**

            我们不改down_ratio,在完成1中的内容修改之后,直接把 ctrbox_net.py中的channels = [3, 64, 256, 512, 1024, 2048]中的256改成64,即channels = [3, 64, 64, 512, 1024, 2048]即可开始训练,简单暴力。

    3.结果

    二、修改为轻量mobilenetv2主干网络

    mobilenetv2的代码如下

    1. import math
    2. import os
    3. import torch
    4. import torch.nn as nn
    5. import torch.utils.model_zoo as model_zoo
    6. BatchNorm2d = nn.BatchNorm2d
    7. def conv_bn(inp, oup, stride):
    8. return nn.Sequential(
    9. nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
    10. BatchNorm2d(oup),
    11. nn.ReLU6(inplace=True)
    12. )
    13. def conv_1x1_bn(inp, oup):
    14. return nn.Sequential(
    15. nn.Conv2d(inp, oup, 1, 1, 0, bias=False),
    16. BatchNorm2d(oup),
    17. nn.ReLU6(inplace=True)
    18. )
    19. class InvertedResidual(nn.Module):
    20. def __init__(self, inp, oup, stride, expand_ratio):
    21. super(InvertedResidual, self).__init__()
    22. self.stride = stride
    23. assert stride in [1, 2]
    24. hidden_dim = round(inp * expand_ratio)
    25. self.use_res_connect = self.stride == 1 and inp == oup
    26. if expand_ratio == 1:
    27. self.conv = nn.Sequential(
    28. # dw
    29. nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),
    30. BatchNorm2d(hidden_dim),
    31. nn.ReLU6(inplace=True),
    32. # pw-linear
    33. nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
    34. BatchNorm2d(oup),
    35. )
    36. else:
    37. self.conv = nn.Sequential(
    38. # pw
    39. nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False),
    40. BatchNorm2d(hidden_dim),
    41. nn.ReLU6(inplace=True),
    42. # dw
    43. nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),
    44. BatchNorm2d(hidden_dim),
    45. nn.ReLU6(inplace=True),
    46. # pw-linear
    47. nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
    48. BatchNorm2d(oup),
    49. )
    50. def forward(self, x):
    51. if self.use_res_connect:
    52. return x + self.conv(x)
    53. else:
    54. return self.conv(x)
    55. class MobileNetV2(nn.Module):
    56. def __init__(self, n_class=1000, input_size=224, width_mult=1.):
    57. super(MobileNetV2, self).__init__()
    58. block = InvertedResidual
    59. input_channel = 32
    60. last_channel = 1280
    61. interverted_residual_setting = [
    62. # t, c, n, s
    63. [1, 16, 1, 1],
    64. [6, 24, 2, 2],
    65. [6, 32, 3, 2],
    66. [6, 64, 4, 2],
    67. [6, 96, 3, 1],
    68. [6, 160, 3, 2],
    69. [6, 320, 1, 1],
    70. ]
    71. # building first layer
    72. assert input_size % 32 == 0
    73. input_channel = int(input_channel * width_mult)
    74. self.last_channel = int(last_channel * width_mult) if width_mult > 1.0 else last_channel
    75. self.features = [conv_bn(3, input_channel, 2)]
    76. # building inverted residual blocks
    77. for t, c, n, s in interverted_residual_setting:
    78. output_channel = int(c * width_mult)
    79. for i in range(n):
    80. if i == 0:
    81. self.features.append(block(input_channel, output_channel, s, expand_ratio=t))
    82. else:
    83. self.features.append(block(input_channel, output_channel, 1, expand_ratio=t))
    84. input_channel = output_channel
    85. # building last several layers
    86. self.features.append(conv_1x1_bn(input_channel, self.last_channel))
    87. # make it nn.Sequential
    88. self.features = nn.Sequential(*self.features)
    89. # building classifier
    90. self.classifier = nn.Sequential(
    91. nn.Dropout(0.2),
    92. nn.Linear(self.last_channel, n_class),
    93. )
    94. self._initialize_weights()
    95. def forward(self, x):
    96. x = self.features(x)
    97. x = x.mean(3).mean(2)
    98. x = self.classifier(x)
    99. return x
    100. def _initialize_weights(self):
    101. for m in self.modules():
    102. if isinstance(m, nn.Conv2d):
    103. n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
    104. m.weight.data.normal_(0, math.sqrt(2. / n))
    105. if m.bias is not None:
    106. m.bias.data.zero_()
    107. elif isinstance(m, BatchNorm2d):
    108. m.weight.data.fill_(1)
    109. m.bias.data.zero_()
    110. elif isinstance(m, nn.Linear):
    111. n = m.weight.size(1)
    112. m.weight.data.normal_(0, 0.01)
    113. m.bias.data.zero_()
    114. def load_url(url, model_dir='./model_data', map_location=None):
    115. if not os.path.exists(model_dir):
    116. os.makedirs(model_dir)
    117. filename = url.split('/')[-1]
    118. cached_file = os.path.join(model_dir, filename)
    119. if os.path.exists(cached_file):
    120. return torch.load(cached_file, map_location=map_location)
    121. else:
    122. return model_zoo.load_url(url,model_dir=model_dir)
    123. def mobilenetv2(pretrained=False, **kwargs):
    124. model = MobileNetV2(n_class=1000, **kwargs)
    125. if pretrained:
    126. model.load_state_dict(load_url('http://sceneparsing.csail.mit.edu/model/pretrained_resnet/mobilenet_v2.pth.tar'), strict=False)
    127. return model
    128. class Backbone(nn.Module):
    129. def __init__(self,pretrained=False):
    130. super(Backbone, self).__init__()
    131. model=mobilenetv2(pretrained)
    132. self.features = model.features[:-1]
    133. def forward(self, x):
    134. C1=self.features[:4](x)
    135. C2=self.features[4:7](C1)
    136. C3=self.features[7:14](C2)
    137. C4=self.features[14:](C3)
    138. return C1,C2,C3,C4
    139. if __name__ == '__main__':
    140. import numpy as np
    141. device='cpu'
    142. model=Backbone().to(device)
    143. input=np.ones((1,3,512,512)).astype(np.float32)
    144. dummy_input = torch.from_numpy(input).to(device)
    145. logit=model(dummy_input)
    146. print(logit[-1].size())
    147. print(logit[-2].size())
    148. print(logit[-3].size())
    149. print(logit[-4].size())

    4个featuremap的大小分别是

    1. torch.Size([1, 320, 16, 16])
    2. torch.Size([1, 96, 32, 32])
    3. torch.Size([1, 32, 64, 64])
    4. torch.Size([1, 24, 128, 128])

    对比之前改成resnet18,你就知道channels和各通道应该改成下面这样

    1. # channels = [3, 64, 256, 512, 1024, 2048] # 当下面采用resnet101的时候用这个
    2. # self.base_network = resnet.resnet101(pretrained=pretrained)
    3. # self.dec_c2 = CombinationModule(512, 256, batch_norm=True)
    4. # self.dec_c3 = CombinationModule(1024, 512, batch_norm=True)
    5. # self.dec_c4 = CombinationModule(2048, 1024, batch_norm=True)
    6. # channels = [3, 64, 64, 512, 1024, 2048] # 用resnet18的时候是这个
    7. # self.base_network = resnet.resnet18(pretrained=pretrained)
    8. # self.dec_c2 = CombinationModule(128, 64, batch_norm=True)
    9. # self.dec_c3 = CombinationModule(256, 128, batch_norm=True)
    10. # self.dec_c4 = CombinationModule(512, 256, batch_norm=True)
    11. channels = [3, 64, 24, 512, 1024, 2048] # mobilenetv2的时候是这个
    12. self.base_network = mobilenet.Backbone(pretrained=pretrained)
    13. self.dec_c2 = CombinationModule(32, 24, batch_norm=True)
    14. self.dec_c3 = CombinationModule(96, 32, batch_norm=True)
    15. self.dec_c4 = CombinationModule(320, 96, batch_norm=True)

    2.结果

     loss下降不如resnet18做骨干网络的loss,这是正常的情况。

    三、完整代码

    完整代码可以参考:见这里,这是我修改过的BBAVectors代码,含DOTA_Devkit, rolabelimg的xml转4点txt格式代码,划分数据集代码,以及导出含decoder的onnx模型代码,tensorrt模型转换与推理的代码,关于tensorrt推理可以看我其他博客。



     

  • 相关阅读:
    BlobDetector的使用与参数说明(OpenCV/C++)
    Redis分布式锁这样用,有坑?
    EdrawMax v12新鲜出炉,重新设计字体库UI
    CSAPP-BombLab详解
    项目实战——实现注册和登录模块
    鸿蒙开发实例 | 可复用列表项的ListContainer
    常见分词算法综述
    vite打包部分页面不显示问题+图片不显示问题
    1.2 异步相关概念:深入了解
    AR空间音频能力,打造沉浸式声音体验
  • 原文地址:https://blog.csdn.net/qq_41043389/article/details/127561102