faster_rcnn.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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 numpy as np
  18. from multiprocessing.pool import ThreadPool
  19. import paddle.fluid as fluid
  20. import paddlex.utils.logging as logging
  21. import paddlex
  22. import os.path as osp
  23. import copy
  24. from paddlex.cv.transforms import arrange_transforms
  25. from paddlex.cv.datasets import generate_minibatch
  26. from .base import BaseAPI
  27. from collections import OrderedDict
  28. from .utils.detection_eval import eval_results, bbox2out
  29. class FasterRCNN(BaseAPI):
  30. """构建FasterRCNN,并实现其训练、评估、预测和模型导出。
  31. Args:
  32. num_classes (int): 包含了背景类的类别数。默认为81。
  33. backbone (str): FasterRCNN的backbone网络,取值范围为['ResNet18', 'ResNet50',
  34. 'ResNet50_vd', 'ResNet101', 'ResNet101_vd', 'HRNet_W18']。默认为'ResNet50'。
  35. with_fpn (bool): 是否使用FPN结构。默认为True。
  36. aspect_ratios (list): 生成anchor高宽比的可选值。默认为[0.5, 1.0, 2.0]。
  37. anchor_sizes (list): 生成anchor大小的可选值。默认为[32, 64, 128, 256, 512]。
  38. """
  39. def __init__(self,
  40. num_classes=81,
  41. backbone='ResNet50',
  42. with_fpn=True,
  43. aspect_ratios=[0.5, 1.0, 2.0],
  44. anchor_sizes=[32, 64, 128, 256, 512]):
  45. self.init_params = locals()
  46. super(FasterRCNN, self).__init__('detector')
  47. backbones = [
  48. 'ResNet18', 'ResNet50', 'ResNet50_vd', 'ResNet101', 'ResNet101_vd',
  49. 'HRNet_W18'
  50. ]
  51. assert backbone in backbones, "backbone should be one of {}".format(
  52. backbones)
  53. self.backbone = backbone
  54. self.num_classes = num_classes
  55. self.with_fpn = with_fpn
  56. self.aspect_ratios = aspect_ratios
  57. self.anchor_sizes = anchor_sizes
  58. self.labels = None
  59. self.fixed_input_shape = None
  60. def _get_backbone(self, backbone_name):
  61. norm_type = None
  62. if backbone_name == 'ResNet18':
  63. layers = 18
  64. variant = 'b'
  65. elif backbone_name == 'ResNet50':
  66. layers = 50
  67. variant = 'b'
  68. elif backbone_name == 'ResNet50_vd':
  69. layers = 50
  70. variant = 'd'
  71. norm_type = 'affine_channel'
  72. elif backbone_name == 'ResNet101':
  73. layers = 101
  74. variant = 'b'
  75. norm_type = 'affine_channel'
  76. elif backbone_name == 'ResNet101_vd':
  77. layers = 101
  78. variant = 'd'
  79. norm_type = 'affine_channel'
  80. elif backbone_name == 'HRNet_W18':
  81. backbone = paddlex.cv.nets.hrnet.HRNet(
  82. width=18, freeze_norm=True, norm_decay=0., freeze_at=0)
  83. if self.with_fpn is False:
  84. self.with_fpn = True
  85. return backbone
  86. if self.with_fpn:
  87. backbone = paddlex.cv.nets.resnet.ResNet(
  88. norm_type='bn' if norm_type is None else norm_type,
  89. layers=layers,
  90. variant=variant,
  91. freeze_norm=True,
  92. norm_decay=0.,
  93. feature_maps=[2, 3, 4, 5],
  94. freeze_at=2)
  95. else:
  96. backbone = paddlex.cv.nets.resnet.ResNet(
  97. norm_type='affine_channel' if norm_type is None else norm_type,
  98. layers=layers,
  99. variant=variant,
  100. freeze_norm=True,
  101. norm_decay=0.,
  102. feature_maps=4,
  103. freeze_at=2)
  104. return backbone
  105. def build_net(self, mode='train'):
  106. train_pre_nms_top_n = 2000 if self.with_fpn else 12000
  107. test_pre_nms_top_n = 1000 if self.with_fpn else 6000
  108. model = paddlex.cv.nets.detection.FasterRCNN(
  109. backbone=self._get_backbone(self.backbone),
  110. mode=mode,
  111. num_classes=self.num_classes,
  112. with_fpn=self.with_fpn,
  113. aspect_ratios=self.aspect_ratios,
  114. anchor_sizes=self.anchor_sizes,
  115. train_pre_nms_top_n=train_pre_nms_top_n,
  116. test_pre_nms_top_n=test_pre_nms_top_n,
  117. fixed_input_shape=self.fixed_input_shape)
  118. inputs = model.generate_inputs()
  119. if mode == 'train':
  120. model_out = model.build_net(inputs)
  121. loss = model_out['loss']
  122. self.optimizer.minimize(loss)
  123. outputs = OrderedDict(
  124. [('loss', model_out['loss']),
  125. ('loss_cls', model_out['loss_cls']),
  126. ('loss_bbox', model_out['loss_bbox']),
  127. ('loss_rpn_cls', model_out['loss_rpn_cls']), (
  128. 'loss_rpn_bbox', model_out['loss_rpn_bbox'])])
  129. else:
  130. outputs = model.build_net(inputs)
  131. return inputs, outputs
  132. def default_optimizer(self, learning_rate, warmup_steps, warmup_start_lr,
  133. lr_decay_epochs, lr_decay_gamma,
  134. num_steps_each_epoch):
  135. if warmup_steps > lr_decay_epochs[0] * num_steps_each_epoch:
  136. logging.error(
  137. "In function train(), parameters should satisfy: warmup_steps <= lr_decay_epochs[0]*num_samples_in_train_dataset",
  138. exit=False)
  139. logging.error(
  140. "See this doc for more information: https://github.com/PaddlePaddle/PaddleX/blob/develop/docs/appendix/parameters.md#notice",
  141. exit=False)
  142. logging.error(
  143. "warmup_steps should less than {} or lr_decay_epochs[0] greater than {}, please modify 'lr_decay_epochs' or 'warmup_steps' in train function".
  144. format(lr_decay_epochs[0] * num_steps_each_epoch, warmup_steps
  145. // num_steps_each_epoch))
  146. boundaries = [b * num_steps_each_epoch for b in lr_decay_epochs]
  147. values = [(lr_decay_gamma**i) * learning_rate
  148. for i in range(len(lr_decay_epochs) + 1)]
  149. lr_decay = fluid.layers.piecewise_decay(
  150. boundaries=boundaries, values=values)
  151. lr_warmup = fluid.layers.linear_lr_warmup(
  152. learning_rate=lr_decay,
  153. warmup_steps=warmup_steps,
  154. start_lr=warmup_start_lr,
  155. end_lr=learning_rate)
  156. optimizer = fluid.optimizer.Momentum(
  157. learning_rate=lr_warmup,
  158. momentum=0.9,
  159. regularization=fluid.regularizer.L2Decay(1e-04))
  160. return optimizer
  161. def train(self,
  162. num_epochs,
  163. train_dataset,
  164. train_batch_size=2,
  165. eval_dataset=None,
  166. save_interval_epochs=1,
  167. log_interval_steps=2,
  168. save_dir='output',
  169. pretrain_weights='IMAGENET',
  170. optimizer=None,
  171. learning_rate=0.0025,
  172. warmup_steps=500,
  173. warmup_start_lr=1.0 / 1200,
  174. lr_decay_epochs=[8, 11],
  175. lr_decay_gamma=0.1,
  176. metric=None,
  177. use_vdl=False,
  178. early_stop=False,
  179. early_stop_patience=5,
  180. resume_checkpoint=None):
  181. """训练。
  182. Args:
  183. num_epochs (int): 训练迭代轮数。
  184. train_dataset (paddlex.datasets): 训练数据读取器。
  185. train_batch_size (int): 训练数据batch大小。目前检测仅支持单卡评估,训练数据batch大小与
  186. 显卡数量之商为验证数据batch大小。默认为2。
  187. eval_dataset (paddlex.datasets): 验证数据读取器。
  188. save_interval_epochs (int): 模型保存间隔(单位:迭代轮数)。默认为1。
  189. log_interval_steps (int): 训练日志输出间隔(单位:迭代次数)。默认为20。
  190. save_dir (str): 模型保存路径。默认值为'output'。
  191. pretrain_weights (str): 若指定为路径时,则加载路径下预训练模型;若为字符串'IMAGENET',
  192. 则自动下载在ImageNet图片数据上预训练的模型权重;若为字符串'COCO',
  193. 则自动下载在COCO数据集上预训练的模型权重;若为None,则不使用预训练模型。默认为'IMAGENET'。
  194. optimizer (paddle.fluid.optimizer): 优化器。当该参数为None时,使用默认优化器:
  195. fluid.layers.piecewise_decay衰减策略,fluid.optimizer.Momentum优化方法。
  196. learning_rate (float): 默认优化器的初始学习率。默认为0.0025。
  197. warmup_steps (int): 默认优化器进行warmup过程的步数。默认为500。
  198. warmup_start_lr (int): 默认优化器warmup的起始学习率。默认为1.0/1200。
  199. lr_decay_epochs (list): 默认优化器的学习率衰减轮数。默认为[8, 11]。
  200. lr_decay_gamma (float): 默认优化器的学习率衰减率。默认为0.1。
  201. metric (bool): 训练过程中评估的方式,取值范围为['COCO', 'VOC']。默认值为None。
  202. use_vdl (bool): 是否使用VisualDL进行可视化。默认值为False。
  203. early_stop (bool): 是否使用提前终止训练策略。默认值为False。
  204. early_stop_patience (int): 当使用提前终止训练策略时,如果验证集精度在`early_stop_patience`个epoch内
  205. 连续下降或持平,则终止训练。默认值为5。
  206. resume_checkpoint (str): 恢复训练时指定上次训练保存的模型路径。若为None,则不会恢复训练。默认值为None。
  207. Raises:
  208. ValueError: 评估类型不在指定列表中。
  209. ValueError: 模型从inference model进行加载。
  210. """
  211. if metric is None:
  212. if isinstance(train_dataset, paddlex.datasets.CocoDetection):
  213. metric = 'COCO'
  214. elif isinstance(train_dataset, paddlex.datasets.VOCDetection) or \
  215. isinstance(train_dataset, paddlex.datasets.EasyDataDet):
  216. metric = 'VOC'
  217. else:
  218. raise ValueError(
  219. "train_dataset should be datasets.VOCDetection or datasets.COCODetection or datasets.EasyDataDet."
  220. )
  221. assert metric in ['COCO', 'VOC'], "Metric only support 'VOC' or 'COCO'"
  222. self.metric = metric
  223. if not self.trainable:
  224. raise ValueError("Model is not trainable from load_model method.")
  225. self.labels = copy.deepcopy(train_dataset.labels)
  226. self.labels.insert(0, 'background')
  227. # 构建训练网络
  228. if optimizer is None:
  229. # 构建默认的优化策略
  230. num_steps_each_epoch = train_dataset.num_samples // train_batch_size
  231. optimizer = self.default_optimizer(
  232. learning_rate, warmup_steps, warmup_start_lr, lr_decay_epochs,
  233. lr_decay_gamma, num_steps_each_epoch)
  234. self.optimizer = optimizer
  235. # 构建训练、验证、测试网络
  236. self.build_program()
  237. fuse_bn = True
  238. if self.with_fpn and self.backbone in [
  239. 'ResNet18', 'ResNet50', 'HRNet_W18'
  240. ]:
  241. fuse_bn = False
  242. self.net_initialize(
  243. startup_prog=fluid.default_startup_program(),
  244. pretrain_weights=pretrain_weights,
  245. fuse_bn=fuse_bn,
  246. save_dir=save_dir,
  247. resume_checkpoint=resume_checkpoint)
  248. # 训练
  249. self.train_loop(
  250. num_epochs=num_epochs,
  251. train_dataset=train_dataset,
  252. train_batch_size=train_batch_size,
  253. eval_dataset=eval_dataset,
  254. save_interval_epochs=save_interval_epochs,
  255. log_interval_steps=log_interval_steps,
  256. save_dir=save_dir,
  257. use_vdl=use_vdl,
  258. early_stop=early_stop,
  259. early_stop_patience=early_stop_patience)
  260. def evaluate(self,
  261. eval_dataset,
  262. batch_size=1,
  263. epoch_id=None,
  264. metric=None,
  265. return_details=False):
  266. """评估。
  267. Args:
  268. eval_dataset (paddlex.datasets): 验证数据读取器。
  269. batch_size (int): 验证数据批大小。默认为1。当前只支持设置为1。
  270. epoch_id (int): 当前评估模型所在的训练轮数。
  271. metric (bool): 训练过程中评估的方式,取值范围为['COCO', 'VOC']。默认为None,
  272. 根据用户传入的Dataset自动选择,如为VOCDetection,则metric为'VOC';
  273. 如为COCODetection,则metric为'COCO'。
  274. return_details (bool): 是否返回详细信息。默认值为False。
  275. Returns:
  276. tuple (metrics, eval_details) /dict (metrics): 当return_details为True时,返回(metrics, eval_details),
  277. 当return_details为False时,返回metrics。metrics为dict,包含关键字:'bbox_mmap'或者’bbox_map‘,
  278. 分别表示平均准确率平均值在各个阈值下的结果取平均值的结果(mmAP)、平均准确率平均值(mAP)。
  279. eval_details为dict,包含关键字:'bbox',对应元素预测结果列表,每个预测结果由图像id、
  280. 预测框类别id、预测框坐标、预测框得分;’gt‘:真实标注框相关信息。
  281. """
  282. arrange_transforms(
  283. model_type=self.model_type,
  284. class_name=self.__class__.__name__,
  285. transforms=eval_dataset.transforms,
  286. mode='eval')
  287. if metric is None:
  288. if hasattr(self, 'metric') and self.metric is not None:
  289. metric = self.metric
  290. else:
  291. if isinstance(eval_dataset, paddlex.datasets.CocoDetection):
  292. metric = 'COCO'
  293. elif isinstance(eval_dataset, paddlex.datasets.VOCDetection):
  294. metric = 'VOC'
  295. else:
  296. raise Exception(
  297. "eval_dataset should be datasets.VOCDetection or datasets.COCODetection."
  298. )
  299. assert metric in ['COCO', 'VOC'], "Metric only support 'VOC' or 'COCO'"
  300. if batch_size > 1:
  301. batch_size = 1
  302. logging.warning(
  303. "Faster RCNN supports batch_size=1 only during evaluating, so batch_size is forced to be set to 1."
  304. )
  305. dataset = eval_dataset.generator(
  306. batch_size=batch_size, drop_last=False)
  307. total_steps = math.ceil(eval_dataset.num_samples * 1.0 / batch_size)
  308. results = list()
  309. logging.info(
  310. "Start to evaluating(total_samples={}, total_steps={})...".format(
  311. eval_dataset.num_samples, total_steps))
  312. for step, data in tqdm.tqdm(enumerate(dataset()), total=total_steps):
  313. images = np.array([d[0] for d in data]).astype('float32')
  314. im_infos = np.array([d[1] for d in data]).astype('float32')
  315. im_shapes = np.array([d[3] for d in data]).astype('float32')
  316. feed_data = {
  317. 'image': images,
  318. 'im_info': im_infos,
  319. 'im_shape': im_shapes,
  320. }
  321. with fluid.scope_guard(self.scope):
  322. outputs = self.exe.run(
  323. self.test_prog,
  324. feed=[feed_data],
  325. fetch_list=list(self.test_outputs.values()),
  326. return_numpy=False)
  327. res = {
  328. 'bbox': (np.array(outputs[0]),
  329. outputs[0].recursive_sequence_lengths())
  330. }
  331. res_im_id = [d[2] for d in data]
  332. res['im_info'] = (im_infos, [])
  333. res['im_shape'] = (im_shapes, [])
  334. res['im_id'] = (np.array(res_im_id), [])
  335. if metric == 'VOC':
  336. res_gt_box = []
  337. res_gt_label = []
  338. res_is_difficult = []
  339. for d in data:
  340. res_gt_box.extend(d[4])
  341. res_gt_label.extend(d[5])
  342. res_is_difficult.extend(d[6])
  343. res_gt_box_lod = [d[4].shape[0] for d in data]
  344. res_gt_label_lod = [d[5].shape[0] for d in data]
  345. res_is_difficult_lod = [d[6].shape[0] for d in data]
  346. res['gt_box'] = (np.array(res_gt_box), [res_gt_box_lod])
  347. res['gt_label'] = (np.array(res_gt_label), [res_gt_label_lod])
  348. res['is_difficult'] = (np.array(res_is_difficult),
  349. [res_is_difficult_lod])
  350. results.append(res)
  351. logging.debug("[EVAL] Epoch={}, Step={}/{}".format(epoch_id, step +
  352. 1, total_steps))
  353. box_ap_stats, eval_details = eval_results(
  354. results, metric, eval_dataset.coco_gt, with_background=True)
  355. metrics = OrderedDict(
  356. zip(['bbox_mmap'
  357. if metric == 'COCO' else 'bbox_map'], box_ap_stats))
  358. if return_details:
  359. return metrics, eval_details
  360. return metrics
  361. @staticmethod
  362. def _preprocess(images, transforms, model_type, class_name, thread_pool=None):
  363. arrange_transforms(
  364. model_type=model_type,
  365. class_name=class_name,
  366. transforms=transforms,
  367. mode='test')
  368. if thread_pool is not None:
  369. batch_data = thread_pool.map(transforms, images)
  370. else:
  371. batch_data = list()
  372. for image in images:
  373. batch_data.append(transforms(image))
  374. padding_batch = generate_minibatch(batch_data)
  375. im = np.array([data[0] for data in padding_batch])
  376. im_resize_info = np.array([data[1] for data in padding_batch])
  377. im_shape = np.array([data[2] for data in padding_batch])
  378. return im, im_resize_info, im_shape
  379. @staticmethod
  380. def _postprocess(res, batch_size, num_classes, labels):
  381. clsid2catid = dict({i: i for i in range(num_classes)})
  382. xywh_results = bbox2out([res], clsid2catid)
  383. preds = [[] for i in range(batch_size)]
  384. for xywh_res in xywh_results:
  385. image_id = xywh_res['image_id']
  386. del xywh_res['image_id']
  387. xywh_res['category'] = labels[xywh_res['category_id']]
  388. preds[image_id].append(xywh_res)
  389. return preds
  390. def predict(self, img_file, transforms=None):
  391. """预测。
  392. Args:
  393. img_file(str|np.ndarray): 预测图像路径,或者是解码后的排列格式为(H, W, C)且类型为float32且为BGR格式的数组。
  394. transforms (paddlex.det.transforms): 数据预处理操作。
  395. Returns:
  396. list: 预测结果列表,每个预测结果由预测框类别标签、
  397. 预测框类别名称、预测框坐标(坐标格式为[xmin, ymin, w, h])、
  398. 预测框得分组成。
  399. """
  400. if transforms is None and not hasattr(self, 'test_transforms'):
  401. raise Exception("transforms need to be defined, now is None.")
  402. if isinstance(img_file, (str, np.ndarray)):
  403. images = [img_file]
  404. else:
  405. raise Exception("img_file must be str/np.ndarray")
  406. if transforms is None:
  407. transforms = self.test_transforms
  408. im, im_resize_info, im_shape = FasterRCNN._preprocess(
  409. images, transforms, self.model_type, self.__class__.__name__)
  410. with fluid.scope_guard(self.scope):
  411. result = self.exe.run(self.test_prog,
  412. feed={
  413. 'image': im,
  414. 'im_info': im_resize_info,
  415. 'im_shape': im_shape
  416. },
  417. fetch_list=list(self.test_outputs.values()),
  418. return_numpy=False,
  419. use_program_cache=True)
  420. res = {
  421. k: (np.array(v), v.recursive_sequence_lengths())
  422. for k, v in zip(list(self.test_outputs.keys()), result)
  423. }
  424. res['im_id'] = (np.array(
  425. [[i] for i in range(len(images))]).astype('int32'), [])
  426. preds = FasterRCNN._postprocess(res,
  427. len(images), self.num_classes,
  428. self.labels)
  429. return preds[0]
  430. def batch_predict(self, img_file_list, transforms=None):
  431. """预测。
  432. Args:
  433. img_file_list(list|tuple): 对列表(或元组)中的图像同时进行预测,列表中的元素可以是图像路径
  434. 也可以是解码后的排列格式为(H,W,C)且类型为float32且为BGR格式的数组。
  435. transforms (paddlex.det.transforms): 数据预处理操作。
  436. Returns:
  437. list: 每个元素都为列表,表示各图像的预测结果。在各图像的预测结果列表中,每个预测结果由预测框类别标签、
  438. 预测框类别名称、预测框坐标(坐标格式为[xmin, ymin, w, h])、
  439. 预测框得分组成。
  440. """
  441. if transforms is None and not hasattr(self, 'test_transforms'):
  442. raise Exception("transforms need to be defined, now is None.")
  443. if not isinstance(img_file_list, (list, tuple)):
  444. raise Exception("im_file must be list/tuple")
  445. if transforms is None:
  446. transforms = self.test_transforms
  447. im, im_resize_info, im_shape = FasterRCNN._preprocess(
  448. img_file_list, transforms, self.model_type,
  449. self.__class__.__name__, self.thread_pool)
  450. with fluid.scope_guard(self.scope):
  451. result = self.exe.run(self.test_prog,
  452. feed={
  453. 'image': im,
  454. 'im_info': im_resize_info,
  455. 'im_shape': im_shape
  456. },
  457. fetch_list=list(self.test_outputs.values()),
  458. return_numpy=False,
  459. use_program_cache=True)
  460. res = {
  461. k: (np.array(v), v.recursive_sequence_lengths())
  462. for k, v in zip(list(self.test_outputs.keys()), result)
  463. }
  464. res['im_id'] = (np.array(
  465. [[i] for i in range(len(img_file_list))]).astype('int32'), [])
  466. preds = FasterRCNN._postprocess(res,
  467. len(img_file_list), self.num_classes,
  468. self.labels)
  469. return preds