yolo_v3.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import absolute_import
  15. import math
  16. import tqdm
  17. import paddlex
  18. from .ppyolo import PPYOLO
  19. class YOLOv3(PPYOLO):
  20. """构建YOLOv3,并实现其训练、评估、预测和模型导出。
  21. Args:
  22. num_classes (int): 类别数。默认为80。
  23. backbone (str): YOLOv3的backbone网络,取值范围为['DarkNet53',
  24. 'ResNet34', 'MobileNetV1', 'MobileNetV3_large']。默认为'MobileNetV1'。
  25. anchors (list|tuple): anchor框的宽度和高度,为None时表示使用默认值
  26. [[10, 13], [16, 30], [33, 23], [30, 61], [62, 45],
  27. [59, 119], [116, 90], [156, 198], [373, 326]]。
  28. anchor_masks (list|tuple): 在计算YOLOv3损失时,使用anchor的mask索引,为None时表示使用默认值
  29. [[6, 7, 8], [3, 4, 5], [0, 1, 2]]。
  30. ignore_threshold (float): 在计算YOLOv3损失时,IoU大于`ignore_threshold`的预测框的置信度被忽略。默认为0.7。
  31. nms_score_threshold (float): 检测框的置信度得分阈值,置信度得分低于阈值的框应该被忽略。默认为0.01。
  32. nms_topk (int): 进行NMS时,根据置信度保留的最大检测框数。默认为1000。
  33. nms_keep_topk (int): 进行NMS后,每个图像要保留的总检测框数。默认为100。
  34. nms_iou_threshold (float): 进行NMS时,用于剔除检测框IoU的阈值。默认为0.45。
  35. label_smooth (bool): 是否使用label smooth。默认值为False。
  36. train_random_shapes (list|tuple): 训练时从列表中随机选择图像大小。默认值为[320, 352, 384, 416, 448, 480, 512, 544, 576, 608]。
  37. input_channel (int): 输入图像的通道数量。默认为3。
  38. """
  39. def __init__(self,
  40. num_classes=80,
  41. backbone='MobileNetV1',
  42. anchors=None,
  43. anchor_masks=None,
  44. ignore_threshold=0.7,
  45. nms_score_threshold=0.01,
  46. nms_topk=1000,
  47. nms_keep_topk=100,
  48. nms_iou_threshold=0.45,
  49. label_smooth=False,
  50. train_random_shapes=[
  51. 320, 352, 384, 416, 448, 480, 512, 544, 576, 608
  52. ],
  53. input_channel=3):
  54. self.init_params = locals()
  55. backbones = [
  56. 'DarkNet53', 'ResNet34', 'MobileNetV1', 'MobileNetV3_large'
  57. ]
  58. assert backbone in backbones, "backbone should be one of {}".format(
  59. backbones)
  60. super(PPYOLO, self).__init__('detector')
  61. self.backbone = backbone
  62. self.num_classes = num_classes
  63. self.anchors = anchors
  64. self.anchor_masks = anchor_masks
  65. self.ignore_threshold = ignore_threshold
  66. self.nms_score_threshold = nms_score_threshold
  67. self.nms_topk = nms_topk
  68. self.nms_keep_topk = nms_keep_topk
  69. self.nms_iou_threshold = nms_iou_threshold
  70. self.label_smooth = label_smooth
  71. self.sync_bn = True
  72. self.train_random_shapes = train_random_shapes
  73. self.fixed_input_shape = None
  74. self.use_fine_grained_loss = False
  75. self.use_coord_conv = False
  76. self.use_iou_aware = False
  77. self.use_spp = False
  78. self.use_drop_block = False
  79. self.use_iou_loss = False
  80. self.scale_x_y = 1.
  81. self.use_matrix_nms = False
  82. self.use_ema = False
  83. self.with_dcn_v2 = False
  84. self.input_channel = input_channel
  85. def _get_backbone(self, backbone_name):
  86. if backbone_name == 'DarkNet53':
  87. backbone = paddlex.cv.nets.DarkNet(norm_type='sync_bn')
  88. elif backbone_name == 'ResNet34':
  89. backbone = paddlex.cv.nets.ResNet(
  90. norm_type='sync_bn',
  91. layers=34,
  92. freeze_norm=False,
  93. norm_decay=0.,
  94. feature_maps=[3, 4, 5],
  95. freeze_at=0)
  96. elif backbone_name == 'MobileNetV1':
  97. backbone = paddlex.cv.nets.MobileNetV1(norm_type='sync_bn')
  98. elif backbone_name.startswith('MobileNetV3'):
  99. model_name = backbone_name.split('_')[1]
  100. backbone = paddlex.cv.nets.MobileNetV3(
  101. norm_type='sync_bn', model_name=model_name)
  102. return backbone
  103. def train(self,
  104. num_epochs,
  105. train_dataset,
  106. train_batch_size=8,
  107. eval_dataset=None,
  108. save_interval_epochs=20,
  109. log_interval_steps=2,
  110. save_dir='output',
  111. pretrain_weights='IMAGENET',
  112. optimizer=None,
  113. learning_rate=1.0 / 8000,
  114. warmup_steps=1000,
  115. warmup_start_lr=0.0,
  116. lr_decay_epochs=[213, 240],
  117. lr_decay_gamma=0.1,
  118. metric=None,
  119. use_vdl=False,
  120. sensitivities_file=None,
  121. eval_metric_loss=0.05,
  122. early_stop=False,
  123. early_stop_patience=5,
  124. resume_checkpoint=None):
  125. """训练。
  126. Args:
  127. num_epochs (int): 训练迭代轮数。
  128. train_dataset (paddlex.datasets): 训练数据读取器。
  129. train_batch_size (int): 训练数据batch大小。目前检测仅支持单卡评估,训练数据batch大小与显卡
  130. 数量之商为验证数据batch大小。默认值为8。
  131. eval_dataset (paddlex.datasets): 验证数据读取器。
  132. save_interval_epochs (int): 模型保存间隔(单位:迭代轮数)。默认为20。
  133. log_interval_steps (int): 训练日志输出间隔(单位:迭代次数)。默认为10。
  134. save_dir (str): 模型保存路径。默认值为'output'。
  135. pretrain_weights (str): 若指定为路径时,则加载路径下预训练模型;若为字符串'IMAGENET',
  136. 则自动下载在ImageNet图片数据上预训练的模型权重;若为字符串'COCO',
  137. 则自动下载在COCO数据集上预训练的模型权重;若为None,则不使用预训练模型。默认为'IMAGENET'。
  138. optimizer (paddle.fluid.optimizer): 优化器。当该参数为None时,使用默认优化器:
  139. fluid.layers.piecewise_decay衰减策略,fluid.optimizer.Momentum优化方法。
  140. learning_rate (float): 默认优化器的学习率。默认为1.0/8000。
  141. warmup_steps (int): 默认优化器进行warmup过程的步数。默认为1000。
  142. warmup_start_lr (int): 默认优化器warmup的起始学习率。默认为0.0。
  143. lr_decay_epochs (list): 默认优化器的学习率衰减轮数。默认为[213, 240]。
  144. lr_decay_gamma (float): 默认优化器的学习率衰减率。默认为0.1。
  145. metric (bool): 训练过程中评估的方式,取值范围为['COCO', 'VOC']。默认值为None。
  146. use_vdl (bool): 是否使用VisualDL进行可视化。默认值为False。
  147. sensitivities_file (str): 若指定为路径时,则加载路径下敏感度信息进行裁剪;若为字符串'DEFAULT',
  148. 则自动下载在ImageNet图片数据上获得的敏感度信息进行裁剪;若为None,则不进行裁剪。默认为None。
  149. eval_metric_loss (float): 可容忍的精度损失。默认为0.05。
  150. early_stop (bool): 是否使用提前终止训练策略。默认值为False。
  151. early_stop_patience (int): 当使用提前终止训练策略时,如果验证集精度在`early_stop_patience`个epoch内
  152. 连续下降或持平,则终止训练。默认值为5。
  153. resume_checkpoint (str): 恢复训练时指定上次训练保存的模型路径。若为None,则不会恢复训练。默认值为None。
  154. Raises:
  155. ValueError: 评估类型不在指定列表中。
  156. ValueError: 模型从inference model进行加载。
  157. """
  158. return super(YOLOv3, self).train(
  159. num_epochs, train_dataset, train_batch_size, eval_dataset,
  160. save_interval_epochs, log_interval_steps, save_dir,
  161. pretrain_weights, optimizer, learning_rate, warmup_steps,
  162. warmup_start_lr, lr_decay_epochs, lr_decay_gamma, metric, use_vdl,
  163. sensitivities_file, eval_metric_loss, early_stop,
  164. early_stop_patience, resume_checkpoint, False)