本文将会手把手教会帅比看官如何更换BBAVectors斜框检测模型骨干网络。
本博客假设各位看官帅比已经能利用BBAVectors训练自己的数据,但是不知道如何更换其主干网络。原始代码中采用的resnet101做为骨干网络,这个网络训练的时候对资源要求较高,那么如何换为更轻量的resnet18、mobilnet呢?
- #修改前
- # self.base_network = resnet.resnet101(pretrained=pretrained)
- # self.dec_c2 = CombinationModule(512, 256, batch_norm=True)
- # self.dec_c3 = CombinationModule(1024, 512, batch_norm=True)
- # self.dec_c4 = CombinationModule(2048, 1024, batch_norm=True)
-
- #修改后
- self.base_network = resnet.resnet18(pretrained=pretrained)
- self.dec_c2 = CombinationModule(128, 64, batch_norm=True)
- self.dec_c3 = CombinationModule(256, 128, batch_norm=True)
- 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即可知道,仅仅是通道数不同,所以我们直接修改上述参数即可。
- if __name__ == '__main__':
- device='cpu'
- input=np.ones((1,3,512,512)).astype(np.float32)
- dummy_input = torch.from_numpy(input).to(device)
-
- model=resnet18().to(device)
- logit=model(dummy_input)
- print(logit[-1].size()) #torch.Size([1, 512, 16, 16])
- print(logit[-2].size()) #torch.Size([1, 256, 32, 32])
- print(logit[-3].size()) #torch.Size([1, 128, 64, 64])
- print(logit[-4].size()) #torch.Size([1, 64, 128, 128])
当 down_ratio=4的时候,c2_combine输出的通道数是256,这也是后面4个head的输入通道数, ctrbox_net .py的计算代码如下
- class CTRBOX(nn.Module):
- def __init__(self, heads, pretrained, down_ratio, final_kernel, head_conv,export=False):
- super(CTRBOX, self).__init__()
- channels = [3, 64, 256, 512, 1024, 2048]
- assert down_ratio in [2, 4, 8, 16]
- 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]即可开始训练,简单暴力。

mobilenetv2的代码如下
- import math
- import os
-
- import torch
- import torch.nn as nn
- import torch.utils.model_zoo as model_zoo
-
- BatchNorm2d = nn.BatchNorm2d
-
- def conv_bn(inp, oup, stride):
- return nn.Sequential(
- nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
- BatchNorm2d(oup),
- nn.ReLU6(inplace=True)
- )
-
- def conv_1x1_bn(inp, oup):
- return nn.Sequential(
- nn.Conv2d(inp, oup, 1, 1, 0, bias=False),
- BatchNorm2d(oup),
- nn.ReLU6(inplace=True)
- )
-
- class InvertedResidual(nn.Module):
- def __init__(self, inp, oup, stride, expand_ratio):
- super(InvertedResidual, self).__init__()
- self.stride = stride
- assert stride in [1, 2]
-
- hidden_dim = round(inp * expand_ratio)
- self.use_res_connect = self.stride == 1 and inp == oup
-
- if expand_ratio == 1:
- self.conv = nn.Sequential(
- # dw
- nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),
- BatchNorm2d(hidden_dim),
- nn.ReLU6(inplace=True),
- # pw-linear
- nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
- BatchNorm2d(oup),
- )
- else:
- self.conv = nn.Sequential(
- # pw
- nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False),
- BatchNorm2d(hidden_dim),
- nn.ReLU6(inplace=True),
- # dw
- nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),
- BatchNorm2d(hidden_dim),
- nn.ReLU6(inplace=True),
- # pw-linear
- nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
- BatchNorm2d(oup),
- )
-
- def forward(self, x):
- if self.use_res_connect:
- return x + self.conv(x)
- else:
- return self.conv(x)
-
- class MobileNetV2(nn.Module):
- def __init__(self, n_class=1000, input_size=224, width_mult=1.):
- super(MobileNetV2, self).__init__()
- block = InvertedResidual
- input_channel = 32
- last_channel = 1280
- interverted_residual_setting = [
- # t, c, n, s
- [1, 16, 1, 1],
- [6, 24, 2, 2],
- [6, 32, 3, 2],
- [6, 64, 4, 2],
- [6, 96, 3, 1],
- [6, 160, 3, 2],
- [6, 320, 1, 1],
- ]
-
- # building first layer
- assert input_size % 32 == 0
- input_channel = int(input_channel * width_mult)
- self.last_channel = int(last_channel * width_mult) if width_mult > 1.0 else last_channel
- self.features = [conv_bn(3, input_channel, 2)]
- # building inverted residual blocks
- for t, c, n, s in interverted_residual_setting:
- output_channel = int(c * width_mult)
- for i in range(n):
- if i == 0:
- self.features.append(block(input_channel, output_channel, s, expand_ratio=t))
- else:
- self.features.append(block(input_channel, output_channel, 1, expand_ratio=t))
- input_channel = output_channel
- # building last several layers
- self.features.append(conv_1x1_bn(input_channel, self.last_channel))
- # make it nn.Sequential
- self.features = nn.Sequential(*self.features)
-
- # building classifier
- self.classifier = nn.Sequential(
- nn.Dropout(0.2),
- nn.Linear(self.last_channel, n_class),
- )
-
- self._initialize_weights()
-
- def forward(self, x):
- x = self.features(x)
- x = x.mean(3).mean(2)
- x = self.classifier(x)
- return x
-
- def _initialize_weights(self):
- for m in self.modules():
- if isinstance(m, nn.Conv2d):
- n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
- m.weight.data.normal_(0, math.sqrt(2. / n))
- if m.bias is not None:
- m.bias.data.zero_()
- elif isinstance(m, BatchNorm2d):
- m.weight.data.fill_(1)
- m.bias.data.zero_()
- elif isinstance(m, nn.Linear):
- n = m.weight.size(1)
- m.weight.data.normal_(0, 0.01)
- m.bias.data.zero_()
-
-
- def load_url(url, model_dir='./model_data', map_location=None):
- if not os.path.exists(model_dir):
- os.makedirs(model_dir)
- filename = url.split('/')[-1]
- cached_file = os.path.join(model_dir, filename)
- if os.path.exists(cached_file):
- return torch.load(cached_file, map_location=map_location)
- else:
- return model_zoo.load_url(url,model_dir=model_dir)
-
- def mobilenetv2(pretrained=False, **kwargs):
- model = MobileNetV2(n_class=1000, **kwargs)
- if pretrained:
- model.load_state_dict(load_url('http://sceneparsing.csail.mit.edu/model/pretrained_resnet/mobilenet_v2.pth.tar'), strict=False)
- return model
-
- class Backbone(nn.Module):
- def __init__(self,pretrained=False):
- super(Backbone, self).__init__()
- model=mobilenetv2(pretrained)
- self.features = model.features[:-1]
-
- def forward(self, x):
-
- C1=self.features[:4](x)
- C2=self.features[4:7](C1)
- C3=self.features[7:14](C2)
- C4=self.features[14:](C3)
-
- return C1,C2,C3,C4
-
- if __name__ == '__main__':
- import numpy as np
-
- device='cpu'
- model=Backbone().to(device)
- input=np.ones((1,3,512,512)).astype(np.float32)
-
- dummy_input = torch.from_numpy(input).to(device)
- logit=model(dummy_input)
- print(logit[-1].size())
- print(logit[-2].size())
- print(logit[-3].size())
- print(logit[-4].size())
4个featuremap的大小分别是
- torch.Size([1, 320, 16, 16])
- torch.Size([1, 96, 32, 32])
- torch.Size([1, 32, 64, 64])
- torch.Size([1, 24, 128, 128])
对比之前改成resnet18,你就知道channels和各通道应该改成下面这样
- # channels = [3, 64, 256, 512, 1024, 2048] # 当下面采用resnet101的时候用这个
- # self.base_network = resnet.resnet101(pretrained=pretrained)
- # self.dec_c2 = CombinationModule(512, 256, batch_norm=True)
- # self.dec_c3 = CombinationModule(1024, 512, batch_norm=True)
- # self.dec_c4 = CombinationModule(2048, 1024, batch_norm=True)
-
- # channels = [3, 64, 64, 512, 1024, 2048] # 用resnet18的时候是这个
- # self.base_network = resnet.resnet18(pretrained=pretrained)
- # self.dec_c2 = CombinationModule(128, 64, batch_norm=True)
- # self.dec_c3 = CombinationModule(256, 128, batch_norm=True)
- # self.dec_c4 = CombinationModule(512, 256, batch_norm=True)
-
- channels = [3, 64, 24, 512, 1024, 2048] # mobilenetv2的时候是这个
- self.base_network = mobilenet.Backbone(pretrained=pretrained)
- self.dec_c2 = CombinationModule(32, 24, batch_norm=True)
- self.dec_c3 = CombinationModule(96, 32, batch_norm=True)
- self.dec_c4 = CombinationModule(320, 96, batch_norm=True)
2.结果

loss下降不如resnet18做骨干网络的loss,这是正常的情况。
三、完整代码
完整代码可以参考:见这里,这是我修改过的BBAVectors代码,含DOTA_Devkit, rolabelimg的xml转4点txt格式代码,划分数据集代码,以及导出含decoder的onnx模型代码,tensorrt模型转换与推理的代码,关于tensorrt推理可以看我其他博客。