• 基于MindSpore的YOLOv3-DarkNet53网络实现


    基于MindSpore的YOLOv3-DarkNet53网络实现

    网络模型介绍

    1、backbone:Darknet-53

    YOLOv3使用Darknet-53提取特征,其借鉴了Darknet-19结构。不同于Darknet-19的是,Darknet-53引入了大量的残差结构,并且使用步长为2,卷积核大小为3×3卷积层Conv2D代替池化层Maxpooling2D。通过在ImageNet上的分类表现,Darknet-53经过以上改造在保证准确率的同时极大地提升了网络的运行速度,证明了Darknet-53在特征提取能力上的有效性。

    图1

    图1为Darknet-53的网络模型,Darknet-53中总共有6个单独的卷积层和23个Residual层,每个Residual包含2个卷积层(一个1×1,一个3×3),所以Darknet-53中共有52层卷积,之所以称为Darknet-53,是因为在YOLOv3中,前52层只用作特征提取,最后一层是用于输出预测值的,故加上输出那一层称为Darknet-53。

    图2

    图2为Darknet-53中的残差结构。加入残差结构Residual的目的是为了增加网络的深度,用于支持网络提取更高级别的语义特征,同时残差的结构可以帮助我们避免梯度的消失或爆炸。因为残差的物理结构,反映到反向梯度传播中,可以使得梯度传递到前面很远的网络层中,削弱反向求导的链式反应。从图2中可以看到,输入首先经过一个1×1的卷积层Conv(1×1 stride=1)将通道数降低一半变为In_channels/2, 然后经过一个3×3的卷积层Conv(3×3,stride=1)进行特征提取,这时通道数又从In_channels/2恢复为In_channels。最后3×3卷积的输出与经过Shorcut传递过来的输入Input相加得到最终的Output(此时3×3卷积的输出与Input的形状(In_channels,h,w)相同,可以直接相加)。我们看到,经过Residual运算之后,输入的特征图形状保持不变。

    2、整体网络框架

    图3

    图3为YOLOV3的整体架构图,可以看出其使用Darknet-53进行特征抽取,使用其中的三个分支进行预测输出。第一个分支输出的特征图大小为13x13,主要用于检测大物体(感受野越大,越能检测到大物体)。第二个分支输出的特征图大小为26x26,第一个分支输出的特征图进行上采样后(特征图由13x13变为26x26)和第二个分支输出融合作为最终的第二个分支预测,主要用于检测中等物体。第三个分支输出的特征图大小为52x52,第二个分支输出的特征图进行上采样后和第三个分支输出融合作为最终的第三个分支预测,主要用于检测小物体。更多网络框架细节问题将在代码流程中逐一分析讲解。

    3、损失函数

    图4

    YOLOV3的损失函数可以分为三部分,分别是边界框损失、置信度损失、分类损失。通过不断的训练使网络收敛,使三种损失都达到相对小的值。

    代码流程介绍

    项目地址:models: Models of MindSpore - Gitee.com

    代码总览:

    图5

    下面主要分析darknet.py、yolo.py、loss.py这三个文件,分别对应YOLOV3特征抽取网络网络、YOLOV3网络、YOLOV3损失函数。

    Darknet53

    darknet.py文件中定义了一个函数两个类。其中conv_block函数定义了基本的Conv+BN+relu组合,Darknet53网络中大量使用了这种组合;ResidualBlock类定义了残差结构;DarkNet按照网络结构图,搭积木般构造了darknet53网络;darknet53函数返回DarkNet类,相当于对外的接口。

    conv_block

    1. # 构造了Conv2d+BatchNorm2d+ReLU的组合。
    2. def conv_block(in_channels, out_channels, kernel_size, stride,dilation=1):
    3. """Get a conv2d batchnorm and relu layer"""
    4. pad_mode = 'same'
    5. padding = 0
    6. return nn.SequentialCell(
    7. [nn.Conv2d(in_channels,
    8. out_channels,
    9. kernel_size=kernel_size,
    10. stride=stride,
    11. padding=padding,
    12. dilation=dilation,
    13. pad_mode=pad_mode),
    14. nn.BatchNorm2d(out_channels, momentum=0.1),
    15. nn.ReLU()]
    16. )

    ResidualBlock

    1. class ResidualBlock(nn.Cell):
    2. """
    3. DarkNet V1 residual block definition.
    4. Args:
    5. in_channels: Integer. Input channel.
    6. out_channels: Integer. Output channel.
    7. Returns:
    8. Tensor, output tensor.
    9. Examples:
    10. ResidualBlock(3, 208)
    11. """
    12. expansion = 4
    13. def __init__(self,
    14. in_channels,
    15. out_channels):
    16. super(ResidualBlock, self).__init__()
    17. out_chls = out_channels//2
    18. # 定义残差结构。首先通过1x1的卷积核将通道数降为一半,然后通过3x3的卷积核将通道数恢复。
    19. # 无论是经过1x1卷积还是3x3卷积,特征图的大小是不变的。padding=same,stride=1.
    20. # 输入经过残差结构后,特征图大小和通道数是保持不变的,所以可以进行ops.Add()操作。
    21. self.conv1 = conv_block(in_channels, out_chls, kernel_size=1, stride=1)
    22. self.conv2 = conv_block(out_chls, out_channels, kernel_size=3, stride=1)
    23. self.add = ops.Add()
    24. def construct(self, x):
    25. identity = x
    26. out = self.conv1(x)
    27. out = self.conv2(out)
    28. out = self.add(out, identity)
    29. return out

    DarkNet

    1. class DarkNet(nn.Cell):
    2. """
    3. DarkNet V1 network.
    4. Args:
    5. block: Cell. Block for network.
    6. layer_nums: List. Numbers of different layers.
    7. in_channels: Integer. Input channel.
    8. out_channels: Integer. Output channel.
    9. detect: Bool. Whether detect or not. Default:False.
    10. Returns:
    11. Tuple, tuple of output tensor,(f1,f2,f3,f4,f5).
    12. Examples:
    13. DarkNet(ResidualBlock,
    14. [1, 2, 8, 8, 4],
    15. [32, 64, 128, 256, 512],
    16. [64, 128, 256, 512, 1024],
    17. 100)
    18. """
    19. def __init__(self,
    20. block,
    21. layer_nums,
    22. in_channels,
    23. out_channels,
    24. detect=False):
    25. super(DarkNet, self).__init__()
    26. self.outchannel = out_channels[-1]
    27. self.detect = detect
    28. # labyer_nums对应Darknet53网络结构中ResidualBlock的重复个数顺序列表。实际值为[1, 2, 8, 8, 4]
    29. # in_channels对应Darknet53网络结构中ResidualBlock中第一个Conv的卷积核个数。实际值为[32, 64, 128, 256, 512]
    30. # in_channels对应Darknet53网络结构中ResidualBlock中第二个Conv的卷积核个数。实际值为[64, 128, 256, 512, 1024]
    31. if not len(layer_nums) == len(in_channels) == len(out_channels) == 5:
    32. raise ValueError("the length of layer_num, inchannel, outchannel list must be 5!")
    33. # convx对应Darknet536个单独的卷积层,layerx对应Darknet535个残差结构,它们的重复次数为[1, 2, 8, 8, 4]
    34. self.conv0 = conv_block(3,
    35. in_channels[0],
    36. kernel_size=3,
    37. stride=1)
    38. self.conv1 = conv_block(in_channels[0],
    39. out_channels[0],
    40. kernel_size=3,
    41. stride=2)
    42. self.layer1 = self._make_layer(block,
    43. layer_nums[0],
    44. in_channel=out_channels[0],
    45. out_channel=out_channels[0])
    46. self.conv2 = conv_block(in_channels[1],
    47. out_channels[1],
    48. kernel_size=3,
    49. stride=2)
    50. self.layer2 = self._make_layer(block,
    51. layer_nums[1],
    52. in_channel=out_channels[1],
    53. out_channel=out_channels[1])
    54. self.conv3 = conv_block(in_channels[2],
    55. out_channels[2],
    56. kernel_size=3,
    57. stride=2)
    58. self.layer3 = self._make_layer(block,
    59. layer_nums[2],
    60. in_channel=out_channels[2],
    61. out_channel=out_channels[2])
    62. self.conv4 = conv_block(in_channels[3],
    63. out_channels[3],
    64. kernel_size=3,
    65. stride=2)
    66. self.layer4 = self._make_layer(block,
    67. layer_nums[3],
    68. in_channel=out_channels[3],
    69. out_channel=out_channels[3])
    70. self.conv5 = conv_block(in_channels[4],
    71. out_channels[4],
    72. kernel_size=3,
    73. stride=2)
    74. self.layer5 = self._make_layer(block,
    75. layer_nums[4],
    76. in_channel=out_channels[4],
    77. out_channel=out_channels[4])
    78. def _make_layer(self, block, layer_num, in_channel, out_channel):
    79. """
    80. Make Layer for DarkNet.
    81. :param block: Cell. DarkNet block.
    82. :param layer_num: Integer. Layer number.
    83. :param in_channel: Integer. Input channel.
    84. :param out_channel: Integer. Output channel.
    85. Examples:
    86. _make_layer(ConvBlock, 1, 128, 256)
    87. """
    88. layers = []
    89. darkblk = block(in_channel, out_channel)
    90. layers.append(darkblk)
    91. for _ in range(1, layer_num):
    92. darkblk = block(out_channel, out_channel)
    93. layers.append(darkblk)
    94. return nn.SequentialCell(layers)
    95. def construct(self, x):
    96. c1 = self.conv0(x)
    97. c2 = self.conv1(c1)
    98. c3 = self.layer1(c2)
    99. c4 = self.conv2(c3)
    100. c5 = self.layer2(c4)
    101. c6 = self.conv3(c5)
    102. c7 = self.layer3(c6)
    103. c8 = self.conv4(c7)
    104. c9 = self.layer4(c8)
    105. c10 = self.conv5(c9)
    106. c11 = self.layer5(c10)
    107. # 如果是作为YOLOV3的特征抽取网络,那么输出三个分支的特征图,用于之后的检测。
    108. if self.detect:
    109. return c7, c9, c11
    110. return c11
    111. def get_out_channels(self):
    112. return self.outchannel

    YOLOV3网络

    yolo.py文件中定义了一个函数和六个类。其中_conv_bn_relu定义了Conv2d+BatchNorm2d+LeakyRelu组合。YoloBlock类和YOLOv3类为一组,前者可以认为是基础类、后者是基于前者输出三个特征图的相关信息。同理有DetectionBlock类和YOLOV3DarkNet53类以及YoloLossBlock类和YoloWithLossCell类。IOU类计算IOU值。下面主要讲解一下YoloBlock类和YOLOv3类。

    YoloBlock

    1. # Darknet53网络输出的特征图经过一系列的Conv2d+BatchNorm2d+LeakyReLU组合后,其中Conv2d为1x13x3的卷积核。
    2. # 最终输出255通道数的特征图。其中255=3*(80+5).一个像素分配三个anchor,
    3. # 每一个anchor负责预测80分类+4个位置坐标+1个类别置信度。
    4. class YoloBlock(nn.Cell):
    5. """
    6. YoloBlock for YOLOv3.
    7. Args:
    8. in_channels: Integer. Input channel.
    9. out_chls: Integer. Middle channel.
    10. out_channels: Integer. Output channel.
    11. Returns:
    12. Tuple, tuple of output tensor,(f1,f2,f3).
    13. Examples:
    14. YoloBlock(1024, 512, 255)
    15. """
    16. def __init__(self, in_channels, out_chls, out_channels):
    17. super(YoloBlock, self).__init__()
    18. out_chls_2 = out_chls*2
    19. self.conv0 = _conv_bn_relu(in_channels, out_chls, ksize=1)
    20. self.conv1 = _conv_bn_relu(out_chls, out_chls_2, ksize=3)
    21. self.conv2 = _conv_bn_relu(out_chls_2, out_chls, ksize=1)
    22. self.conv3 = _conv_bn_relu(out_chls, out_chls_2, ksize=3)
    23. self.conv4 = _conv_bn_relu(out_chls_2, out_chls, ksize=1)
    24. self.conv5 = _conv_bn_relu(out_chls, out_chls_2, ksize=3)
    25. self.conv6 = nn.Conv2d(out_chls_2, out_channels, kernel_size=1, stride=1, has_bias=True)
    26. def construct(self, x):
    27. c1 = self.conv0(x)
    28. c2 = self.conv1(c1)
    29. c3 = self.conv2(c2)
    30. c4 = self.conv3(c3)
    31. c5 = self.conv4(c4)
    32. c6 = self.conv5(c5)
    33. out = self.conv6(c6)
    34. return c5, out

    YOLOv3

    1. # 基于YoloBlock,输出大、中、小三个特征图中经过上采样、Conv2d+BatchNorm2d+LeakyReLU组合后的结果。
    2. class YOLOv3(nn.Cell):
    3. """
    4. YOLOv3 Network.
    5. Note:
    6. backbone = darknet53
    7. Args:
    8. backbone_shape: List. Darknet output channels shape.
    9. backbone: Cell. Backbone Network.
    10. out_channel: Integer. Output channel.
    11. Returns:
    12. Tensor, output tensor.
    13. Examples:
    14. YOLOv3(backbone_shape=[64, 128, 256, 512, 1024]
    15. backbone=darknet53(),
    16. out_channel=255)
    17. """
    18. def __init__(self, backbone_shape, backbone, out_channel):
    19. super(YOLOv3, self).__init__()
    20. self.out_channel = out_channel
    21. self.backbone = backbone
    22. # 第一个特征图输入13x13,输入通道为1024,中间通道为512,输出通道为255. 对应大物体检测。
    23. self.backblock0 = YoloBlock(backbone_shape[-1], out_chls=backbone_shape[-2], out_channels=out_channel)
    24. self.conv1 = _conv_bn_relu(in_channel=backbone_shape[-2], out_channel=backbone_shape[-2]//2, ksize=1)
    25. # 第二个特征图输入26x26并且融合第一个特征图输出后+上采样,输入通道为512+256,中间通道256,输出通道255.
    26. self.backblock1 = YoloBlock(in_channels=backbone_shape[-2]+backbone_shape[-3],
    27. out_chls=backbone_shape[-3],
    28. out_channels=out_channel)
    29. self.conv2 = _conv_bn_relu(in_channel=backbone_shape[-3], out_channel=backbone_shape[-3]//2, ksize=1)
    30. # 第三个特征图输入13x13并且融合第二个特征图输出后+上采样,输入通道为256+128,中间通道128,输出通道255.
    31. self.backblock2 = YoloBlock(in_channels=backbone_shape[-3]+backbone_shape[-4],
    32. out_chls=backbone_shape[-4],
    33. out_channels=out_channel)
    34. self.concat = ops.Concat(axis=1)
    35. def construct(self, x):
    36. # input_shape of x is (batch_size, 3, h, w)
    37. # feature_map1 is (batch_size, backbone_shape[2], h/8, w/8)
    38. # feature_map2 is (batch_size, backbone_shape[3], h/16, w/16)
    39. # feature_map3 is (batch_size, backbone_shape[4], h/32, w/32)
    40. img_hight = ops.Shape()(x)[2]
    41. img_width = ops.Shape()(x)[3]
    42. feature_map1, feature_map2, feature_map3 = self.backbone(x)
    43. con1, big_object_output = self.backblock0(feature_map3)
    44. con1 = self.conv1(con1)
    45. # 使用线性插值法进行上采样,将特征图尺寸由13x13变为26x26
    46. ups1 = ops.ResizeNearestNeighbor((img_hight // 16, img_width // 16))(con1)
    47. # 特征图大小相等26x26,直接通道数相加。
    48. con1 = self.concat((ups1, feature_map2))
    49. con2, medium_object_output = self.backblock1(con1)
    50. con2 = self.conv2(con2)
    51. # 使用线性插值法进行上采样,将特征图尺寸由26x26变为52x52
    52. ups2 = ops.ResizeNearestNeighbor((img_hight // 8, img_width // 8))(con2)
    53. # 特征图大小相等52x52,直接通道数相加。
    54. con3 = self.concat((ups2, feature_map1))
    55. _, small_object_output = self.backblock2(con3)
    56. return big_object_output, medium_object_output, small_object_output

    损失函数

    loss.py中定义了损失函数的具体计算公式,包括物体中心点坐标损失、物体宽高损失、检测框置信度损失、物体类别损失。

    训练过程

    训练的相关参数通过default_config.yaml文件来配置。

    1. # Training options
    2. # dataset related
    3. data_dir: "/cache/data/coco2014/"
    4. per_batch_size: 32
    5. # network related
    6. pretrained_backbone: "/cache/checkpoint_path/0-148_92000.ckpt"
    7. resume_yolov3: ""
    8. # optimizer and lr related
    9. lr_scheduler: "exponential"
    10. lr: 0.001
    11. lr_epochs: "220,250"
    12. lr_gamma: 0.1
    13. eta_min: 0.0
    14. T_max: 320
    15. max_epoch: 320
    16. warmup_epochs: 0
    17. weight_decay: 0.0005
    18. momentum: 0.9
    19. # loss related
    20. loss_scale: 1024
    21. label_smooth: 0
    22. label_smooth_factor: 0.1
    23. # logging related
    24. log_interval: 100
    25. ckpt_path: "outputs/"
    26. ckpt_interval: -1
    27. is_save_on_master: 1
    28. # distributed related
    29. is_distributed: 1
    30. rank: 0
    31. group_size: 1
    32. bind_cpu: True
    33. device_num: 8
    34. # profiler init
    35. need_profiler: 0
    36. # reset default config
    37. training_shape: ""

    YOLOV3的训练脚本train.py中首先加载训练参数以及环境变量:

    1. def run_train():
    2. """Train function."""
    3. if config.lr_scheduler == 'cosine_annealing' and config.max_epoch > config.T_max:
    4. config.T_max = config.max_epoch
    5. config.lr_epochs = list(map(int, config.lr_epochs.split(',')))
    6. config.data_root = os.path.join(config.data_dir, 'train2014')
    7. config.annFile = os.path.join(config.data_dir, 'annotations/instances_train2014.json')
    8. profiler = network_init(config)

    train.py中定义网络结构和损失函数:

    1. network = YOLOV3DarkNet53(is_training=True)
    2. # default is kaiming-normal
    3. default_recurisive_init(network)
    4. load_yolov3_params(config, network)
    5. network = YoloWithLossCell(network)

    定义学习率和优化器:

    1. lr = get_lr(config)
    2. opt = nn.Momentum(params=get_param_groups(network), momentum=config.momentum, learning_rate=ms.Tensor(lr),
    3. weight_decay=config.weight_decay, loss_scale=config.loss_scale)

    调用nn.TrainOneStepCell接口进行训练:

    1. network = nn.TrainOneStepCell(network, opt, sens=config.loss_scale)
    2. network.set_train()
    3. t_end = time.time()
    4. data_loader = ds.create_dict_iterator(output_numpy=True)
    5. first_step = True
    6. stop_profiler = False
    7. for epoch_idx in range(config.max_epoch):
    8. for step_idx, data in enumerate(data_loader):
    9. images = data["image"]
    10. input_shape = images.shape[2:4]
    11. config.logger.info('iter[{}], shape{}'.format(step_idx, input_shape[0]))
    12. images = ms.Tensor.from_numpy(images)
    13. batch_y_true_0 = ms.Tensor.from_numpy(data['bbox1'])
    14. batch_y_true_1 = ms.Tensor.from_numpy(data['bbox2'])
    15. batch_y_true_2 = ms.Tensor.from_numpy(data['bbox3'])
    16. batch_gt_box0 = ms.Tensor.from_numpy(data['gt_box1'])
    17. batch_gt_box1 = ms.Tensor.from_numpy(data['gt_box2'])
    18. batch_gt_box2 = ms.Tensor.from_numpy(data['gt_box3'])
    19. loss = network(images, batch_y_true_0, batch_y_true_1, batch_y_true_2, batch_gt_box0, batch_gt_box1,
    20. batch_gt_box2)
    21. loss_meter.update(loss.asnumpy())

    YOLOV3 + COCO2014 dataset示例训练输出:

    1. epoch[0], iter[0], loss:7809.262695, 0.15 imgs/sec, lr:9.746589057613164e-06
    2. epoch[0], iter[100], loss:2778.349033, 133.92 imgs/sec, lr:0.0009844054002314806
    3. epoch[0], iter[200], loss:535.517361, 130.54 imgs/sec, lr:0.0019590642768889666

    推理过程

    推理脚本需要首先加载训练得到的权重文件、然后在定义网络后使用set_train(False)切换到推理模式。示意流程代码如下:

    1. # define Net
    2. network = YOLOV3DarkNet53(is_training=False)
    3. # load checkpoint
    4. load_parameters(network, config.pretrained)
    5. # init detection engine
    6. detection = DetectionEngine(config)
    7. # eval
    8. network.set_train(False)
    9. output_big, output_me, output_small = network(image)
    10. detection.detect([output_small, output_me, output_big], config.per_batch_size, image_shape, image_id)

    YOLOV3 + COCO2014 dataset实例推理输出:

    1. Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.311
    2. Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.528
    3. Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.322
    4. Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.127
    5. Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.323
    6. Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.428
    7. Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.259
    8. Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.398
    9. Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.423
    10. Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.224
    11. Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.442
    12. Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.551
  • 相关阅读:
    股票配资软件cs架构开发技术方案[附源码]
    运行ps软件提示由于找不到vcruntime140.dll无法继续执行代码怎么修复
    Nginx网站服务
    2021第7届中国大学生程序设计竞赛CCPC广州站, 签到题4题
    C语言小程序-通讯录(动态内存管理)
    华为机试真题 Java 实现【最大括号深度】
    网络基础aaa
    【windows】实战部署二(使用)SVNserver服务端+SVNclient客户端
    2023年华数杯数学建模C题母亲身心健康对婴儿成长的影响解题全过程文档及程序
    cookie详解
  • 原文地址:https://blog.csdn.net/Kenji_Shinji/article/details/127314611