detector.py 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759
  1. # Copyright (c) 2021 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 collections
  16. import copy
  17. import os
  18. import os.path as osp
  19. import six
  20. import numpy as np
  21. import paddle
  22. from paddle.static import InputSpec
  23. import ppdet
  24. from ppdet.modeling.proposal_generator.target_layer import BBoxAssigner, MaskAssigner
  25. import paddlex
  26. import paddlex.utils.logging as logging
  27. from paddlex.cv.transforms.operators import _NormalizeBox, _PadBox, _BboxXYXY2XYWH, Resize, Padding
  28. from paddlex.cv.transforms.batch_operators import BatchCompose, BatchRandomResize, BatchRandomResizeByShort, _BatchPadding, _Gt2YoloTarget
  29. from paddlex.cv.transforms import arrange_transforms
  30. from .base import BaseModel
  31. from .utils.det_metrics import VOCMetric, COCOMetric
  32. from .utils.ema import ExponentialMovingAverage
  33. from paddlex.utils.checkpoint import det_pretrain_weights_dict
  34. __all__ = [
  35. "YOLOv3", "FasterRCNN", "PPYOLO", "PPYOLOTiny", "PPYOLOv2", "MaskRCNN"
  36. ]
  37. class BaseDetector(BaseModel):
  38. def __init__(self, model_name, num_classes=80, **params):
  39. self.init_params.update(locals())
  40. super(BaseDetector, self).__init__('detector')
  41. if not hasattr(ppdet.modeling, model_name):
  42. raise Exception("ERROR: There's no model named {}.".format(
  43. model_name))
  44. self.model_name = model_name
  45. self.num_classes = num_classes
  46. self.labels = None
  47. self.net = self.build_net(**params)
  48. def build_net(self, **params):
  49. with paddle.utils.unique_name.guard():
  50. net = ppdet.modeling.__dict__[self.model_name](**params)
  51. return net
  52. def _fix_transforms_shape(self, image_shape):
  53. raise NotImplementedError("_fix_transforms_shape: not implemented!")
  54. def _define_input_spec(self, image_shape):
  55. input_spec = [{
  56. "image": InputSpec(
  57. shape=image_shape, name='image', dtype='float32'),
  58. "im_shape": InputSpec(
  59. shape=[image_shape[0], 2], name='im_shape', dtype='float32'),
  60. "scale_factor": InputSpec(
  61. shape=[image_shape[0], 2],
  62. name='scale_factor',
  63. dtype='float32')
  64. }]
  65. return input_spec
  66. def _check_image_shape(self, image_shape):
  67. if len(image_shape) == 2:
  68. image_shape = [None, 3] + image_shape
  69. if image_shape[-2] % 32 > 0 or image_shape[-1] % 32 > 0:
  70. raise Exception(
  71. "Height and width in fixed_input_shape must be a multiple of 32, but received {}.".
  72. format(image_shape[-2:]))
  73. return image_shape
  74. def _get_test_inputs(self, image_shape):
  75. if image_shape is not None:
  76. image_shape = self._check_image_shape(image_shape)
  77. self._fix_transforms_shape(image_shape[-2:])
  78. else:
  79. image_shape = [None, 3, -1, -1]
  80. return self._define_input_spec(image_shape)
  81. def _get_backbone(self, backbone_name, **params):
  82. backbone = getattr(ppdet.modeling, backbone_name)(**params)
  83. return backbone
  84. def run(self, net, inputs, mode):
  85. net_out = net(inputs)
  86. if mode in ['train', 'eval']:
  87. outputs = net_out
  88. else:
  89. for key in ['im_shape', 'scale_factor']:
  90. net_out[key] = inputs[key]
  91. outputs = dict()
  92. for key in net_out:
  93. outputs[key] = net_out[key].numpy()
  94. return outputs
  95. def default_optimizer(self, parameters, learning_rate, warmup_steps,
  96. warmup_start_lr, lr_decay_epochs, lr_decay_gamma,
  97. num_steps_each_epoch):
  98. boundaries = [b * num_steps_each_epoch for b in lr_decay_epochs]
  99. values = [(lr_decay_gamma**i) * learning_rate
  100. for i in range(len(lr_decay_epochs) + 1)]
  101. scheduler = paddle.optimizer.lr.PiecewiseDecay(
  102. boundaries=boundaries, values=values)
  103. if warmup_steps > 0:
  104. if warmup_steps > lr_decay_epochs[0] * num_steps_each_epoch:
  105. logging.error(
  106. "In function train(), parameters should satisfy: "
  107. "warmup_steps <= lr_decay_epochs[0]*num_samples_in_train_dataset",
  108. exit=False)
  109. logging.error(
  110. "See this doc for more information: "
  111. "https://github.com/PaddlePaddle/PaddleX/blob/develop/docs/appendix/parameters.md#notice",
  112. exit=False)
  113. scheduler = paddle.optimizer.lr.LinearWarmup(
  114. learning_rate=scheduler,
  115. warmup_steps=warmup_steps,
  116. start_lr=warmup_start_lr,
  117. end_lr=learning_rate)
  118. optimizer = paddle.optimizer.Momentum(
  119. scheduler,
  120. momentum=.9,
  121. weight_decay=paddle.regularizer.L2Decay(coeff=1e-04),
  122. parameters=parameters)
  123. return optimizer
  124. def train(self,
  125. num_epochs,
  126. train_dataset,
  127. train_batch_size=64,
  128. eval_dataset=None,
  129. optimizer=None,
  130. save_interval_epochs=1,
  131. log_interval_steps=10,
  132. save_dir='output',
  133. pretrain_weights='IMAGENET',
  134. learning_rate=.001,
  135. warmup_steps=0,
  136. warmup_start_lr=0.0,
  137. lr_decay_epochs=(216, 243),
  138. lr_decay_gamma=0.1,
  139. metric=None,
  140. use_ema=False,
  141. early_stop=False,
  142. early_stop_patience=5,
  143. use_vdl=True,
  144. resume_checkpoint=None):
  145. """
  146. Train the model.
  147. Args:
  148. num_epochs(int): The number of epochs.
  149. train_dataset(paddlex.dataset): Training dataset.
  150. train_batch_size(int, optional): Total batch size among all cards used in training. Defaults to 64.
  151. eval_dataset(paddlex.dataset, optional):
  152. Evaluation dataset. If None, the model will not be evaluated during training process. Defaults to None.
  153. optimizer(paddle.optimizer.Optimizer or None, optional):
  154. Optimizer used for training. If None, a default optimizer is used. Defaults to None.
  155. save_interval_epochs(int, optional): Epoch interval for saving the model. Defaults to 1.
  156. log_interval_steps(int, optional): Step interval for printing training information. Defaults to 10.
  157. save_dir(str, optional): Directory to save the model. Defaults to 'output'.
  158. pretrain_weights(str or None, optional):
  159. None or name/path of pretrained weights. If None, no pretrained weights will be loaded. Defaults to 'IMAGENET'.
  160. learning_rate(float, optional): Learning rate for training. Defaults to .001.
  161. warmup_steps(int, optional): The number of steps of warm-up training. Defaults to 0.
  162. warmup_start_lr(float, optional): Start learning rate of warm-up training. Defaults to 0..
  163. lr_decay_epochs(list or tuple, optional): Epoch milestones for learning rate decay. Defaults to (216, 243).
  164. lr_decay_gamma(float, optional): Gamma coefficient of learning rate decay. Defaults to .1.
  165. metric({'VOC', 'COCO', None}, optional):
  166. Evaluation metric. If None, determine the metric according to the dataset format. Defaults to None.
  167. use_ema(bool, optional): Whether to use exponential moving average strategy. Defaults to False.
  168. early_stop(bool, optional): Whether to adopt early stop strategy. Defaults to False.
  169. early_stop_patience(int, optional): Early stop patience. Defaults to 5.
  170. use_vdl(bool, optional): Whether to use VisualDL to monitor the training process. Defaults to True.
  171. resume_checkpoint(str or None, optional): The path of the checkpoint to resume training from.
  172. If None, no training checkpoint will be resumed. At most one of `resume_checkpoint` and
  173. `pretrain_weights` can be set simultaneously. Defaults to None.
  174. """
  175. if pretrain_weights is not None and resume_checkpoint is not None:
  176. logging.error(
  177. "pretrain_weights and resume_checkpoint cannot be set simultaneously.",
  178. exit=True)
  179. if train_dataset.__class__.__name__ == 'VOCDetection':
  180. train_dataset.data_fields = {
  181. 'im_id', 'image_shape', 'image', 'gt_bbox', 'gt_class',
  182. 'difficult'
  183. }
  184. elif train_dataset.__class__.__name__ == 'CocoDetection':
  185. if self.__class__.__name__ == 'MaskRCNN':
  186. train_dataset.data_fields = {
  187. 'im_id', 'image_shape', 'image', 'gt_bbox', 'gt_class',
  188. 'gt_poly', 'is_crowd'
  189. }
  190. else:
  191. train_dataset.data_fields = {
  192. 'im_id', 'image_shape', 'image', 'gt_bbox', 'gt_class',
  193. 'is_crowd'
  194. }
  195. if metric is None:
  196. if eval_dataset.__class__.__name__ == 'VOCDetection':
  197. self.metric = 'voc'
  198. elif eval_dataset.__class__.__name__ == 'CocoDetection':
  199. self.metric = 'coco'
  200. else:
  201. assert metric.lower() in ['coco', 'voc'], \
  202. "Evaluation metric {} is not supported, please choose form 'COCO' and 'VOC'"
  203. self.metric = metric.lower()
  204. self.labels = train_dataset.labels
  205. self.num_max_boxes = train_dataset.num_max_boxes
  206. train_dataset.batch_transforms = self._compose_batch_transform(
  207. train_dataset.transforms, mode='train')
  208. # build optimizer if not defined
  209. if optimizer is None:
  210. num_steps_each_epoch = len(train_dataset) // train_batch_size
  211. self.optimizer = self.default_optimizer(
  212. parameters=self.net.parameters(),
  213. learning_rate=learning_rate,
  214. warmup_steps=warmup_steps,
  215. warmup_start_lr=warmup_start_lr,
  216. lr_decay_epochs=lr_decay_epochs,
  217. lr_decay_gamma=lr_decay_gamma,
  218. num_steps_each_epoch=num_steps_each_epoch)
  219. else:
  220. self.optimizer = optimizer
  221. # initiate weights
  222. if pretrain_weights is not None and not osp.exists(pretrain_weights):
  223. if pretrain_weights not in det_pretrain_weights_dict['_'.join(
  224. [self.model_name, self.backbone_name])]:
  225. logging.warning(
  226. "Path of pretrain_weights('{}') does not exist!".format(
  227. pretrain_weights))
  228. pretrain_weights = det_pretrain_weights_dict['_'.join(
  229. [self.model_name, self.backbone_name])][0]
  230. logging.warning("Pretrain_weights is forcibly set to '{}'. "
  231. "If you don't want to use pretrain weights, "
  232. "set pretrain_weights to be None.".format(
  233. pretrain_weights))
  234. elif pretrain_weights is not None and osp.exists(pretrain_weights):
  235. if osp.splitext(pretrain_weights)[-1] != '.pdparams':
  236. logging.error(
  237. "Invalid pretrain weights. Please specify a '.pdparams' file.",
  238. exit=True)
  239. pretrained_dir = osp.join(save_dir, 'pretrain')
  240. self.net_initialize(
  241. pretrain_weights=pretrain_weights,
  242. save_dir=pretrained_dir,
  243. resume_checkpoint=resume_checkpoint)
  244. if use_ema:
  245. ema = ExponentialMovingAverage(
  246. decay=.9998, model=self.net, use_thres_step=True)
  247. else:
  248. ema = None
  249. # start train loop
  250. self.train_loop(
  251. num_epochs=num_epochs,
  252. train_dataset=train_dataset,
  253. train_batch_size=train_batch_size,
  254. eval_dataset=eval_dataset,
  255. save_interval_epochs=save_interval_epochs,
  256. log_interval_steps=log_interval_steps,
  257. save_dir=save_dir,
  258. ema=ema,
  259. early_stop=early_stop,
  260. early_stop_patience=early_stop_patience,
  261. use_vdl=use_vdl)
  262. def quant_aware_train(self,
  263. num_epochs,
  264. train_dataset,
  265. train_batch_size=64,
  266. eval_dataset=None,
  267. optimizer=None,
  268. save_interval_epochs=1,
  269. log_interval_steps=10,
  270. save_dir='output',
  271. learning_rate=.00001,
  272. warmup_steps=0,
  273. warmup_start_lr=0.0,
  274. lr_decay_epochs=(216, 243),
  275. lr_decay_gamma=0.1,
  276. metric=None,
  277. use_ema=False,
  278. early_stop=False,
  279. early_stop_patience=5,
  280. use_vdl=True,
  281. resume_checkpoint=None,
  282. quant_config=None):
  283. """
  284. Quantization-aware training.
  285. Args:
  286. num_epochs(int): The number of epochs.
  287. train_dataset(paddlex.dataset): Training dataset.
  288. train_batch_size(int, optional): Total batch size among all cards used in training. Defaults to 64.
  289. eval_dataset(paddlex.dataset, optional):
  290. Evaluation dataset. If None, the model will not be evaluated during training process. Defaults to None.
  291. optimizer(paddle.optimizer.Optimizer or None, optional):
  292. Optimizer used for training. If None, a default optimizer is used. Defaults to None.
  293. save_interval_epochs(int, optional): Epoch interval for saving the model. Defaults to 1.
  294. log_interval_steps(int, optional): Step interval for printing training information. Defaults to 10.
  295. save_dir(str, optional): Directory to save the model. Defaults to 'output'.
  296. learning_rate(float, optional): Learning rate for training. Defaults to .001.
  297. warmup_steps(int, optional): The number of steps of warm-up training. Defaults to 0.
  298. warmup_start_lr(float, optional): Start learning rate of warm-up training. Defaults to 0..
  299. lr_decay_epochs(list or tuple, optional): Epoch milestones for learning rate decay. Defaults to (216, 243).
  300. lr_decay_gamma(float, optional): Gamma coefficient of learning rate decay. Defaults to .1.
  301. metric({'VOC', 'COCO', None}, optional):
  302. Evaluation metric. If None, determine the metric according to the dataset format. Defaults to None.
  303. use_ema(bool, optional): Whether to use exponential moving average strategy. Defaults to False.
  304. early_stop(bool, optional): Whether to adopt early stop strategy. Defaults to False.
  305. early_stop_patience(int, optional): Early stop patience. Defaults to 5.
  306. use_vdl(bool, optional): Whether to use VisualDL to monitor the training process. Defaults to True.
  307. quant_config(dict or None, optional): Quantization configuration. If None, a default rule of thumb
  308. configuration will be used. Defaults to None.
  309. resume_checkpoint(str or None, optional): The path of the checkpoint to resume quantization-aware training
  310. from. If None, no training checkpoint will be resumed. Defaults to None.
  311. """
  312. self._prepare_qat(quant_config)
  313. self.train(
  314. num_epochs=num_epochs,
  315. train_dataset=train_dataset,
  316. train_batch_size=train_batch_size,
  317. eval_dataset=eval_dataset,
  318. optimizer=optimizer,
  319. save_interval_epochs=save_interval_epochs,
  320. log_interval_steps=log_interval_steps,
  321. save_dir=save_dir,
  322. pretrain_weights=None,
  323. learning_rate=learning_rate,
  324. warmup_steps=warmup_steps,
  325. warmup_start_lr=warmup_start_lr,
  326. lr_decay_epochs=lr_decay_epochs,
  327. lr_decay_gamma=lr_decay_gamma,
  328. metric=metric,
  329. use_ema=use_ema,
  330. early_stop=early_stop,
  331. early_stop_patience=early_stop_patience,
  332. use_vdl=use_vdl,
  333. resume_checkpoint=resume_checkpoint)
  334. def evaluate(self,
  335. eval_dataset,
  336. batch_size=1,
  337. metric=None,
  338. return_details=False):
  339. """
  340. Evaluate the model.
  341. Args:
  342. eval_dataset(paddlex.dataset): Evaluation dataset.
  343. batch_size(int, optional): Total batch size among all cards used for evaluation. Defaults to 1.
  344. metric({'VOC', 'COCO', None}, optional):
  345. Evaluation metric. If None, determine the metric according to the dataset format. Defaults to None.
  346. return_details(bool, optional): Whether to return evaluation details. Defaults to False.
  347. Returns:
  348. collections.OrderedDict with key-value pairs: {"mAP(0.50, 11point)":`mean average precision`}.
  349. """
  350. if metric is None:
  351. if not hasattr(self, 'metric'):
  352. if eval_dataset.__class__.__name__ == 'VOCDetection':
  353. self.metric = 'voc'
  354. elif eval_dataset.__class__.__name__ == 'CocoDetection':
  355. self.metric = 'coco'
  356. else:
  357. assert metric.lower() in ['coco', 'voc'], \
  358. "Evaluation metric {} is not supported, please choose form 'COCO' and 'VOC'"
  359. self.metric = metric.lower()
  360. if self.metric == 'voc':
  361. eval_dataset.data_fields = {
  362. 'im_id', 'image_shape', 'image', 'gt_bbox', 'gt_class',
  363. 'difficult'
  364. }
  365. elif self.metric == 'coco':
  366. if self.__class__.__name__ == 'MaskRCNN':
  367. eval_dataset.data_fields = {
  368. 'im_id', 'image_shape', 'image', 'gt_bbox', 'gt_class',
  369. 'gt_poly', 'is_crowd'
  370. }
  371. else:
  372. eval_dataset.data_fields = {
  373. 'im_id', 'image_shape', 'image', 'gt_bbox', 'gt_class',
  374. 'is_crowd'
  375. }
  376. eval_dataset.batch_transforms = self._compose_batch_transform(
  377. eval_dataset.transforms, mode='eval')
  378. arrange_transforms(
  379. model_type=self.model_type,
  380. transforms=eval_dataset.transforms,
  381. mode='eval')
  382. self.net.eval()
  383. nranks = paddle.distributed.get_world_size()
  384. local_rank = paddle.distributed.get_rank()
  385. if nranks > 1:
  386. # Initialize parallel environment if not done.
  387. if not paddle.distributed.parallel.parallel_helper._is_parallel_ctx_initialized(
  388. ):
  389. paddle.distributed.init_parallel_env()
  390. if batch_size > 1:
  391. logging.warning(
  392. "Detector only supports single card evaluation with batch_size=1 "
  393. "during evaluation, so batch_size is forcibly set to 1.")
  394. batch_size = 1
  395. if nranks < 2 or local_rank == 0:
  396. self.eval_data_loader = self.build_data_loader(
  397. eval_dataset, batch_size=batch_size, mode='eval')
  398. is_bbox_normalized = False
  399. if eval_dataset.batch_transforms is not None:
  400. is_bbox_normalized = any(
  401. isinstance(t, _NormalizeBox)
  402. for t in eval_dataset.batch_transforms.batch_transforms)
  403. if self.metric == 'voc':
  404. eval_metric = VOCMetric(
  405. labels=eval_dataset.labels,
  406. coco_gt=copy.deepcopy(eval_dataset.coco_gt),
  407. is_bbox_normalized=is_bbox_normalized,
  408. classwise=False)
  409. else:
  410. eval_metric = COCOMetric(
  411. coco_gt=copy.deepcopy(eval_dataset.coco_gt),
  412. classwise=False)
  413. scores = collections.OrderedDict()
  414. logging.info(
  415. "Start to evaluate(total_samples={}, total_steps={})...".
  416. format(eval_dataset.num_samples, eval_dataset.num_samples))
  417. with paddle.no_grad():
  418. for step, data in enumerate(self.eval_data_loader):
  419. outputs = self.run(self.net, data, 'eval')
  420. eval_metric.update(data, outputs)
  421. eval_metric.accumulate()
  422. self.eval_details = eval_metric.details
  423. scores.update(eval_metric.get())
  424. eval_metric.reset()
  425. if return_details:
  426. return scores, self.eval_details
  427. return scores
  428. def predict(self, img_file, transforms=None):
  429. """
  430. Do inference.
  431. Args:
  432. img_file(List[np.ndarray or str], str or np.ndarray): img_file(list or str or np.array):
  433. Image path or decoded image data in a BGR format, which also could constitute a list,
  434. meaning all images to be predicted as a mini-batch.
  435. transforms(paddlex.transforms.Compose or None, optional):
  436. Transforms for inputs. If None, the transforms for evaluation process will be used. Defaults to None.
  437. Returns:
  438. If img_file is a string or np.array, the result is a list of dict with key-value pairs:
  439. {"category_id": `category_id`, "category": `category`, "bbox": `[x, y, w, h]`, "score": `score`}.
  440. If img_file is a list, the result is a list composed of dicts with the corresponding fields:
  441. category_id(int): the predicted category ID. 0 represents the first category in the dataset, and so on.
  442. category(str): category name
  443. bbox(list): bounding box in [x, y, w, h] format
  444. score(str): confidence
  445. mask(dict): Only for instance segmentation task. Mask of the object in RLE format
  446. """
  447. if transforms is None and not hasattr(self, 'test_transforms'):
  448. raise Exception("transforms need to be defined, now is None.")
  449. if transforms is None:
  450. transforms = self.test_transforms
  451. if isinstance(img_file, (str, np.ndarray)):
  452. images = [img_file]
  453. else:
  454. images = img_file
  455. batch_samples = self._preprocess(images, transforms)
  456. self.net.eval()
  457. outputs = self.run(self.net, batch_samples, 'test')
  458. prediction = self._postprocess(outputs)
  459. if isinstance(img_file, (str, np.ndarray)):
  460. prediction = prediction[0]
  461. return prediction
  462. def _preprocess(self, images, transforms):
  463. arrange_transforms(
  464. model_type=self.model_type, transforms=transforms, mode='test')
  465. batch_samples = list()
  466. for im in images:
  467. sample = {'image': im}
  468. batch_samples.append(transforms(sample))
  469. batch_transforms = self._compose_batch_transform(transforms, 'test')
  470. batch_samples = batch_transforms(batch_samples)
  471. for k, v in batch_samples.items():
  472. batch_samples[k] = paddle.to_tensor(v)
  473. return batch_samples
  474. def _postprocess(self, batch_pred):
  475. infer_result = {}
  476. if 'bbox' in batch_pred:
  477. bboxes = batch_pred['bbox']
  478. bbox_nums = batch_pred['bbox_num']
  479. det_res = []
  480. k = 0
  481. for i in range(len(bbox_nums)):
  482. det_nums = bbox_nums[i]
  483. for j in range(det_nums):
  484. dt = bboxes[k]
  485. k = k + 1
  486. num_id, score, xmin, ymin, xmax, ymax = dt.tolist()
  487. if int(num_id) < 0:
  488. continue
  489. category = self.labels[int(num_id)]
  490. w = xmax - xmin
  491. h = ymax - ymin
  492. bbox = [xmin, ymin, w, h]
  493. dt_res = {
  494. 'category_id': int(num_id),
  495. 'category': category,
  496. 'bbox': bbox,
  497. 'score': score
  498. }
  499. det_res.append(dt_res)
  500. infer_result['bbox'] = det_res
  501. if 'mask' in batch_pred:
  502. masks = batch_pred['mask']
  503. bboxes = batch_pred['bbox']
  504. mask_nums = batch_pred['bbox_num']
  505. seg_res = []
  506. k = 0
  507. for i in range(len(mask_nums)):
  508. det_nums = mask_nums[i]
  509. for j in range(det_nums):
  510. mask = masks[k].astype(np.uint8)
  511. score = float(bboxes[k][1])
  512. label = int(bboxes[k][0])
  513. k = k + 1
  514. if label == -1:
  515. continue
  516. category = self.labels[int(label)]
  517. import pycocotools.mask as mask_util
  518. rle = mask_util.encode(
  519. np.array(
  520. mask[:, :, None], order="F", dtype="uint8"))[0]
  521. if six.PY3:
  522. if 'counts' in rle:
  523. rle['counts'] = rle['counts'].decode("utf8")
  524. sg_res = {
  525. 'category_id': int(label),
  526. 'category': category,
  527. 'mask': rle,
  528. 'score': score
  529. }
  530. seg_res.append(sg_res)
  531. infer_result['mask'] = seg_res
  532. bbox_num = batch_pred['bbox_num']
  533. results = []
  534. start = 0
  535. for num in bbox_num:
  536. end = start + num
  537. curr_res = infer_result['bbox'][start:end]
  538. if 'mask' in infer_result:
  539. mask_res = infer_result['mask'][start:end]
  540. for box, mask in zip(curr_res, mask_res):
  541. box.update(mask)
  542. results.append(curr_res)
  543. start = end
  544. return results
  545. class YOLOv3(BaseDetector):
  546. def __init__(self,
  547. num_classes=80,
  548. backbone='MobileNetV1',
  549. anchors=[[10, 13], [16, 30], [33, 23], [30, 61], [62, 45],
  550. [59, 119], [116, 90], [156, 198], [373, 326]],
  551. anchor_masks=[[6, 7, 8], [3, 4, 5], [0, 1, 2]],
  552. ignore_threshold=0.7,
  553. nms_score_threshold=0.01,
  554. nms_topk=1000,
  555. nms_keep_topk=100,
  556. nms_iou_threshold=0.45,
  557. label_smooth=False):
  558. self.init_params = locals()
  559. if backbone not in [
  560. 'MobileNetV1', 'MobileNetV1_ssld', 'MobileNetV3',
  561. 'MobileNetV3_ssld', 'DarkNet53', 'ResNet50_vd_dcn', 'ResNet34'
  562. ]:
  563. raise ValueError(
  564. "backbone: {} is not supported. Please choose one of "
  565. "('MobileNetV1', 'MobileNetV1_ssld', 'MobileNetV3', 'MobileNetV3_ssld', 'DarkNet53', 'ResNet50_vd_dcn', 'ResNet34')".
  566. format(backbone))
  567. if paddlex.env_info['place'] == 'gpu' and paddlex.env_info[
  568. 'num'] > 1 and not os.environ.get('PADDLEX_EXPORT_STAGE'):
  569. norm_type = 'sync_bn'
  570. else:
  571. norm_type = 'bn'
  572. self.backbone_name = backbone
  573. if 'MobileNetV1' in backbone:
  574. norm_type = 'bn'
  575. backbone = self._get_backbone('MobileNet', norm_type=norm_type)
  576. elif 'MobileNetV3' in backbone:
  577. backbone = self._get_backbone(
  578. 'MobileNetV3', norm_type=norm_type, feature_maps=[7, 13, 16])
  579. elif backbone == 'ResNet50_vd_dcn':
  580. backbone = self._get_backbone(
  581. 'ResNet',
  582. norm_type=norm_type,
  583. variant='d',
  584. return_idx=[1, 2, 3],
  585. dcn_v2_stages=[3],
  586. freeze_at=-1,
  587. freeze_norm=False)
  588. elif backbone == 'ResNet34':
  589. backbone = self._get_backbone(
  590. 'ResNet',
  591. depth=34,
  592. norm_type=norm_type,
  593. return_idx=[1, 2, 3],
  594. freeze_at=-1,
  595. freeze_norm=False,
  596. norm_decay=0.)
  597. else:
  598. backbone = self._get_backbone('DarkNet', norm_type=norm_type)
  599. neck = ppdet.modeling.YOLOv3FPN(
  600. norm_type=norm_type,
  601. in_channels=[i.channels for i in backbone.out_shape])
  602. loss = ppdet.modeling.YOLOv3Loss(
  603. num_classes=num_classes,
  604. ignore_thresh=ignore_threshold,
  605. label_smooth=label_smooth)
  606. yolo_head = ppdet.modeling.YOLOv3Head(
  607. in_channels=[i.channels for i in neck.out_shape],
  608. anchors=anchors,
  609. anchor_masks=anchor_masks,
  610. num_classes=num_classes,
  611. loss=loss)
  612. post_process = ppdet.modeling.BBoxPostProcess(
  613. decode=ppdet.modeling.YOLOBox(num_classes=num_classes),
  614. nms=ppdet.modeling.MultiClassNMS(
  615. score_threshold=nms_score_threshold,
  616. nms_top_k=nms_topk,
  617. keep_top_k=nms_keep_topk,
  618. nms_threshold=nms_iou_threshold))
  619. params = {
  620. 'backbone': backbone,
  621. 'neck': neck,
  622. 'yolo_head': yolo_head,
  623. 'post_process': post_process
  624. }
  625. super(YOLOv3, self).__init__(
  626. model_name='YOLOv3', num_classes=num_classes, **params)
  627. self.anchors = anchors
  628. self.anchor_masks = anchor_masks
  629. def _compose_batch_transform(self, transforms, mode='train'):
  630. if mode == 'train':
  631. default_batch_transforms = [
  632. _BatchPadding(pad_to_stride=-1), _NormalizeBox(),
  633. _PadBox(getattr(self, 'num_max_boxes', 50)), _BboxXYXY2XYWH(),
  634. _Gt2YoloTarget(
  635. anchor_masks=self.anchor_masks,
  636. anchors=self.anchors,
  637. downsample_ratios=getattr(self, 'downsample_ratios',
  638. [32, 16, 8]),
  639. num_classes=self.num_classes)
  640. ]
  641. else:
  642. default_batch_transforms = [_BatchPadding(pad_to_stride=-1)]
  643. if mode == 'eval' and self.metric == 'voc':
  644. collate_batch = False
  645. else:
  646. collate_batch = True
  647. custom_batch_transforms = []
  648. for i, op in enumerate(transforms.transforms):
  649. if isinstance(op, (BatchRandomResize, BatchRandomResizeByShort)):
  650. if mode != 'train':
  651. raise Exception(
  652. "{} cannot be present in the {} transforms. ".format(
  653. op.__class__.__name__, mode) +
  654. "Please check the {} transforms.".format(mode))
  655. custom_batch_transforms.insert(0, copy.deepcopy(op))
  656. batch_transforms = BatchCompose(
  657. custom_batch_transforms + default_batch_transforms,
  658. collate_batch=collate_batch)
  659. return batch_transforms
  660. def _fix_transforms_shape(self, image_shape):
  661. if hasattr(self, 'test_transforms'):
  662. if self.test_transforms is not None:
  663. has_resize_op = False
  664. resize_op_idx = -1
  665. normalize_op_idx = len(self.test_transforms.transforms)
  666. for idx, op in enumerate(self.test_transforms.transforms):
  667. name = op.__class__.__name__
  668. if name == 'Resize':
  669. has_resize_op = True
  670. resize_op_idx = idx
  671. if name == 'Normalize':
  672. normalize_op_idx = idx
  673. if not has_resize_op:
  674. self.test_transforms.transforms.insert(
  675. normalize_op_idx,
  676. Resize(
  677. target_size=image_shape, interp='CUBIC'))
  678. else:
  679. self.test_transforms.transforms[
  680. resize_op_idx].target_size = image_shape
  681. class FasterRCNN(BaseDetector):
  682. def __init__(self,
  683. num_classes=80,
  684. backbone='ResNet50',
  685. with_fpn=True,
  686. with_dcn=False,
  687. aspect_ratios=[0.5, 1.0, 2.0],
  688. anchor_sizes=[[32], [64], [128], [256], [512]],
  689. keep_top_k=100,
  690. nms_threshold=0.5,
  691. score_threshold=0.05,
  692. fpn_num_channels=256,
  693. rpn_batch_size_per_im=256,
  694. rpn_fg_fraction=0.5,
  695. test_pre_nms_top_n=None,
  696. test_post_nms_top_n=1000):
  697. self.init_params = locals()
  698. if backbone not in [
  699. 'ResNet50', 'ResNet50_vd', 'ResNet50_vd_ssld', 'ResNet34',
  700. 'ResNet34_vd', 'ResNet101', 'ResNet101_vd', 'HRNet_W18'
  701. ]:
  702. raise ValueError(
  703. "backbone: {} is not supported. Please choose one of "
  704. "('ResNet50', 'ResNet50_vd', 'ResNet50_vd_ssld', 'ResNet34', 'ResNet34_vd', "
  705. "'ResNet101', 'ResNet101_vd', 'HRNet_W18')".format(backbone))
  706. self.backbone_name = backbone
  707. dcn_v2_stages = [1, 2, 3] if with_dcn else [-1]
  708. if backbone == 'HRNet_W18':
  709. if not with_fpn:
  710. logging.warning(
  711. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  712. format(backbone))
  713. with_fpn = True
  714. if with_dcn:
  715. logging.warning(
  716. "Backbone {} should be used along with dcn disabled, 'with_dcn' is forcibly set to False".
  717. format(backbone))
  718. backbone = self._get_backbone(
  719. 'HRNet', width=18, freeze_at=0, return_idx=[0, 1, 2, 3])
  720. elif backbone == 'ResNet50_vd_ssld':
  721. if not with_fpn:
  722. logging.warning(
  723. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  724. format(backbone))
  725. with_fpn = True
  726. backbone = self._get_backbone(
  727. 'ResNet',
  728. variant='d',
  729. norm_type='bn',
  730. freeze_at=0,
  731. return_idx=[0, 1, 2, 3],
  732. num_stages=4,
  733. lr_mult_list=[0.05, 0.05, 0.1, 0.15],
  734. dcn_v2_stages=dcn_v2_stages)
  735. elif 'ResNet50' in backbone:
  736. if with_fpn:
  737. backbone = self._get_backbone(
  738. 'ResNet',
  739. variant='d' if '_vd' in backbone else 'b',
  740. norm_type='bn',
  741. freeze_at=0,
  742. return_idx=[0, 1, 2, 3],
  743. num_stages=4,
  744. dcn_v2_stages=dcn_v2_stages)
  745. else:
  746. if with_dcn:
  747. logging.warning(
  748. "Backbone {} without fpn should be used along with dcn disabled, 'with_dcn' is forcibly set to False".
  749. format(backbone))
  750. backbone = self._get_backbone(
  751. 'ResNet',
  752. variant='d' if '_vd' in backbone else 'b',
  753. norm_type='bn',
  754. freeze_at=0,
  755. return_idx=[2],
  756. num_stages=3)
  757. elif 'ResNet34' in backbone:
  758. if not with_fpn:
  759. logging.warning(
  760. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  761. format(backbone))
  762. with_fpn = True
  763. backbone = self._get_backbone(
  764. 'ResNet',
  765. depth=34,
  766. variant='d' if 'vd' in backbone else 'b',
  767. norm_type='bn',
  768. freeze_at=0,
  769. return_idx=[0, 1, 2, 3],
  770. num_stages=4,
  771. dcn_v2_stages=dcn_v2_stages)
  772. else:
  773. if not with_fpn:
  774. logging.warning(
  775. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  776. format(backbone))
  777. with_fpn = True
  778. backbone = self._get_backbone(
  779. 'ResNet',
  780. depth=101,
  781. variant='d' if 'vd' in backbone else 'b',
  782. norm_type='bn',
  783. freeze_at=0,
  784. return_idx=[0, 1, 2, 3],
  785. num_stages=4,
  786. dcn_v2_stages=dcn_v2_stages)
  787. rpn_in_channel = backbone.out_shape[0].channels
  788. if with_fpn:
  789. self.backbone_name = self.backbone_name + '_fpn'
  790. if 'HRNet' in self.backbone_name:
  791. neck = ppdet.modeling.HRFPN(
  792. in_channels=[i.channels for i in backbone.out_shape],
  793. out_channel=fpn_num_channels,
  794. spatial_scales=[
  795. 1.0 / i.stride for i in backbone.out_shape
  796. ],
  797. share_conv=False)
  798. else:
  799. neck = ppdet.modeling.FPN(
  800. in_channels=[i.channels for i in backbone.out_shape],
  801. out_channel=fpn_num_channels,
  802. spatial_scales=[
  803. 1.0 / i.stride for i in backbone.out_shape
  804. ])
  805. rpn_in_channel = neck.out_shape[0].channels
  806. anchor_generator_cfg = {
  807. 'aspect_ratios': aspect_ratios,
  808. 'anchor_sizes': anchor_sizes,
  809. 'strides': [4, 8, 16, 32, 64]
  810. }
  811. train_proposal_cfg = {
  812. 'min_size': 0.0,
  813. 'nms_thresh': .7,
  814. 'pre_nms_top_n': 2000,
  815. 'post_nms_top_n': 1000,
  816. 'topk_after_collect': True
  817. }
  818. test_proposal_cfg = {
  819. 'min_size': 0.0,
  820. 'nms_thresh': .7,
  821. 'pre_nms_top_n': 1000
  822. if test_pre_nms_top_n is None else test_pre_nms_top_n,
  823. 'post_nms_top_n': test_post_nms_top_n
  824. }
  825. head = ppdet.modeling.TwoFCHead(
  826. in_channel=neck.out_shape[0].channels, out_channel=1024)
  827. roi_extractor_cfg = {
  828. 'resolution': 7,
  829. 'spatial_scale': [1. / i.stride for i in neck.out_shape],
  830. 'sampling_ratio': 0,
  831. 'aligned': True
  832. }
  833. with_pool = False
  834. else:
  835. neck = None
  836. anchor_generator_cfg = {
  837. 'aspect_ratios': aspect_ratios,
  838. 'anchor_sizes': anchor_sizes,
  839. 'strides': [16]
  840. }
  841. train_proposal_cfg = {
  842. 'min_size': 0.0,
  843. 'nms_thresh': .7,
  844. 'pre_nms_top_n': 12000,
  845. 'post_nms_top_n': 2000,
  846. 'topk_after_collect': False
  847. }
  848. test_proposal_cfg = {
  849. 'min_size': 0.0,
  850. 'nms_thresh': .7,
  851. 'pre_nms_top_n': 6000
  852. if test_pre_nms_top_n is None else test_pre_nms_top_n,
  853. 'post_nms_top_n': test_post_nms_top_n
  854. }
  855. head = ppdet.modeling.Res5Head()
  856. roi_extractor_cfg = {
  857. 'resolution': 14,
  858. 'spatial_scale': [1. / i.stride for i in backbone.out_shape],
  859. 'sampling_ratio': 0,
  860. 'aligned': True
  861. }
  862. with_pool = True
  863. rpn_target_assign_cfg = {
  864. 'batch_size_per_im': rpn_batch_size_per_im,
  865. 'fg_fraction': rpn_fg_fraction,
  866. 'negative_overlap': .3,
  867. 'positive_overlap': .7,
  868. 'use_random': True
  869. }
  870. rpn_head = ppdet.modeling.RPNHead(
  871. anchor_generator=anchor_generator_cfg,
  872. rpn_target_assign=rpn_target_assign_cfg,
  873. train_proposal=train_proposal_cfg,
  874. test_proposal=test_proposal_cfg,
  875. in_channel=rpn_in_channel)
  876. bbox_assigner = BBoxAssigner(num_classes=num_classes)
  877. bbox_head = ppdet.modeling.BBoxHead(
  878. head=head,
  879. in_channel=head.out_shape[0].channels,
  880. roi_extractor=roi_extractor_cfg,
  881. with_pool=with_pool,
  882. bbox_assigner=bbox_assigner,
  883. num_classes=num_classes)
  884. bbox_post_process = ppdet.modeling.BBoxPostProcess(
  885. num_classes=num_classes,
  886. decode=ppdet.modeling.RCNNBox(num_classes=num_classes),
  887. nms=ppdet.modeling.MultiClassNMS(
  888. score_threshold=score_threshold,
  889. keep_top_k=keep_top_k,
  890. nms_threshold=nms_threshold))
  891. params = {
  892. 'backbone': backbone,
  893. 'neck': neck,
  894. 'rpn_head': rpn_head,
  895. 'bbox_head': bbox_head,
  896. 'bbox_post_process': bbox_post_process
  897. }
  898. self.with_fpn = with_fpn
  899. super(FasterRCNN, self).__init__(
  900. model_name='FasterRCNN', num_classes=num_classes, **params)
  901. def _compose_batch_transform(self, transforms, mode='train'):
  902. if mode == 'train':
  903. default_batch_transforms = [
  904. _BatchPadding(pad_to_stride=32 if self.with_fpn else -1)
  905. ]
  906. collate_batch = False
  907. else:
  908. default_batch_transforms = [
  909. _BatchPadding(pad_to_stride=32 if self.with_fpn else -1)
  910. ]
  911. collate_batch = True
  912. custom_batch_transforms = []
  913. for i, op in enumerate(transforms.transforms):
  914. if isinstance(op, (BatchRandomResize, BatchRandomResizeByShort)):
  915. if mode != 'train':
  916. raise Exception(
  917. "{} cannot be present in the {} transforms. ".format(
  918. op.__class__.__name__, mode) +
  919. "Please check the {} transforms.".format(mode))
  920. custom_batch_transforms.insert(0, copy.deepcopy(op))
  921. batch_transforms = BatchCompose(
  922. custom_batch_transforms + default_batch_transforms,
  923. collate_batch=collate_batch)
  924. return batch_transforms
  925. def _fix_transforms_shape(self, image_shape):
  926. if hasattr(self, 'test_transforms'):
  927. if self.test_transforms is not None:
  928. has_resize_op = False
  929. resize_op_idx = -1
  930. normalize_op_idx = len(self.test_transforms.transforms)
  931. for idx, op in enumerate(self.test_transforms.transforms):
  932. name = op.__class__.__name__
  933. if name == 'ResizeByShort':
  934. has_resize_op = True
  935. resize_op_idx = idx
  936. if name == 'Normalize':
  937. normalize_op_idx = idx
  938. if not has_resize_op:
  939. self.test_transforms.transforms.insert(
  940. normalize_op_idx,
  941. Resize(
  942. target_size=image_shape,
  943. keep_ratio=True,
  944. interp='CUBIC'))
  945. else:
  946. self.test_transforms.transforms[resize_op_idx] = Resize(
  947. target_size=image_shape,
  948. keep_ratio=True,
  949. interp='CUBIC')
  950. self.test_transforms.transforms.append(
  951. Padding(im_padding_value=[0., 0., 0.]))
  952. def _get_test_inputs(self, image_shape):
  953. if image_shape is not None:
  954. image_shape = self._check_image_shape(image_shape)
  955. self._fix_transforms_shape(image_shape[-2:])
  956. else:
  957. image_shape = [None, 3, -1, -1]
  958. if self.with_fpn:
  959. self.test_transforms.transforms.append(
  960. Padding(im_padding_value=[0., 0., 0.]))
  961. return self._define_input_spec(image_shape)
  962. class PPYOLO(YOLOv3):
  963. def __init__(self,
  964. num_classes=80,
  965. backbone='ResNet50_vd_dcn',
  966. anchors=None,
  967. anchor_masks=None,
  968. use_coord_conv=True,
  969. use_iou_aware=True,
  970. use_spp=True,
  971. use_drop_block=True,
  972. scale_x_y=1.05,
  973. ignore_threshold=0.7,
  974. label_smooth=False,
  975. use_iou_loss=True,
  976. use_matrix_nms=True,
  977. nms_score_threshold=0.01,
  978. nms_topk=-1,
  979. nms_keep_topk=100,
  980. nms_iou_threshold=0.45):
  981. self.init_params = locals()
  982. if backbone not in [
  983. 'ResNet50_vd_dcn', 'ResNet18_vd', 'MobileNetV3_large',
  984. 'MobileNetV3_small'
  985. ]:
  986. raise ValueError(
  987. "backbone: {} is not supported. Please choose one of "
  988. "('ResNet50_vd_dcn', 'ResNet18_vd', 'MobileNetV3_large', 'MobileNetV3_small')".
  989. format(backbone))
  990. self.backbone_name = backbone
  991. if paddlex.env_info['place'] == 'gpu' and paddlex.env_info[
  992. 'num'] > 1 and not os.environ.get('PADDLEX_EXPORT_STAGE'):
  993. norm_type = 'sync_bn'
  994. else:
  995. norm_type = 'bn'
  996. if anchors is None and anchor_masks is None:
  997. if 'MobileNetV3' in backbone:
  998. anchors = [[11, 18], [34, 47], [51, 126], [115, 71],
  999. [120, 195], [254, 235]]
  1000. anchor_masks = [[3, 4, 5], [0, 1, 2]]
  1001. elif backbone == 'ResNet50_vd_dcn':
  1002. anchors = [[10, 13], [16, 30], [33, 23], [30, 61], [62, 45],
  1003. [59, 119], [116, 90], [156, 198], [373, 326]]
  1004. anchor_masks = [[6, 7, 8], [3, 4, 5], [0, 1, 2]]
  1005. else:
  1006. anchors = [[10, 14], [23, 27], [37, 58], [81, 82], [135, 169],
  1007. [344, 319]]
  1008. anchor_masks = [[3, 4, 5], [0, 1, 2]]
  1009. elif anchors is None or anchor_masks is None:
  1010. raise ValueError("Please define both anchors and anchor_masks.")
  1011. if backbone == 'ResNet50_vd_dcn':
  1012. backbone = self._get_backbone(
  1013. 'ResNet',
  1014. variant='d',
  1015. norm_type=norm_type,
  1016. return_idx=[1, 2, 3],
  1017. dcn_v2_stages=[3],
  1018. freeze_at=-1,
  1019. freeze_norm=False,
  1020. norm_decay=0.)
  1021. downsample_ratios = [32, 16, 8]
  1022. elif backbone == 'ResNet18_vd':
  1023. backbone = self._get_backbone(
  1024. 'ResNet',
  1025. depth=18,
  1026. variant='d',
  1027. norm_type=norm_type,
  1028. return_idx=[2, 3],
  1029. freeze_at=-1,
  1030. freeze_norm=False,
  1031. norm_decay=0.)
  1032. downsample_ratios = [32, 16, 8]
  1033. elif backbone == 'MobileNetV3_large':
  1034. backbone = self._get_backbone(
  1035. 'MobileNetV3',
  1036. model_name='large',
  1037. norm_type=norm_type,
  1038. scale=1,
  1039. with_extra_blocks=False,
  1040. extra_block_filters=[],
  1041. feature_maps=[13, 16])
  1042. downsample_ratios = [32, 16]
  1043. elif backbone == 'MobileNetV3_small':
  1044. backbone = self._get_backbone(
  1045. 'MobileNetV3',
  1046. model_name='small',
  1047. norm_type=norm_type,
  1048. scale=1,
  1049. with_extra_blocks=False,
  1050. extra_block_filters=[],
  1051. feature_maps=[9, 12])
  1052. downsample_ratios = [32, 16]
  1053. neck = ppdet.modeling.PPYOLOFPN(
  1054. norm_type=norm_type,
  1055. in_channels=[i.channels for i in backbone.out_shape],
  1056. coord_conv=use_coord_conv,
  1057. drop_block=use_drop_block,
  1058. spp=use_spp,
  1059. conv_block_num=0 if ('MobileNetV3' in self.backbone_name or
  1060. self.backbone_name == 'ResNet18_vd') else 2)
  1061. loss = ppdet.modeling.YOLOv3Loss(
  1062. num_classes=num_classes,
  1063. ignore_thresh=ignore_threshold,
  1064. downsample=downsample_ratios,
  1065. label_smooth=label_smooth,
  1066. scale_x_y=scale_x_y,
  1067. iou_loss=ppdet.modeling.IouLoss(
  1068. loss_weight=2.5, loss_square=True) if use_iou_loss else None,
  1069. iou_aware_loss=ppdet.modeling.IouAwareLoss(loss_weight=1.0)
  1070. if use_iou_aware else None)
  1071. yolo_head = ppdet.modeling.YOLOv3Head(
  1072. in_channels=[i.channels for i in neck.out_shape],
  1073. anchors=anchors,
  1074. anchor_masks=anchor_masks,
  1075. num_classes=num_classes,
  1076. loss=loss,
  1077. iou_aware=use_iou_aware)
  1078. if use_matrix_nms:
  1079. nms = ppdet.modeling.MatrixNMS(
  1080. keep_top_k=nms_keep_topk,
  1081. score_threshold=nms_score_threshold,
  1082. post_threshold=.05
  1083. if 'MobileNetV3' in self.backbone_name else .01,
  1084. nms_top_k=nms_topk,
  1085. background_label=-1)
  1086. else:
  1087. nms = ppdet.modeling.MultiClassNMS(
  1088. score_threshold=nms_score_threshold,
  1089. nms_top_k=nms_topk,
  1090. keep_top_k=nms_keep_topk,
  1091. nms_threshold=nms_iou_threshold)
  1092. post_process = ppdet.modeling.BBoxPostProcess(
  1093. decode=ppdet.modeling.YOLOBox(
  1094. num_classes=num_classes,
  1095. conf_thresh=.005
  1096. if 'MobileNetV3' in self.backbone_name else .01,
  1097. scale_x_y=scale_x_y),
  1098. nms=nms)
  1099. params = {
  1100. 'backbone': backbone,
  1101. 'neck': neck,
  1102. 'yolo_head': yolo_head,
  1103. 'post_process': post_process
  1104. }
  1105. super(YOLOv3, self).__init__(
  1106. model_name='YOLOv3', num_classes=num_classes, **params)
  1107. self.anchors = anchors
  1108. self.anchor_masks = anchor_masks
  1109. self.downsample_ratios = downsample_ratios
  1110. self.model_name = 'PPYOLO'
  1111. class PPYOLOTiny(YOLOv3):
  1112. def __init__(self,
  1113. num_classes=80,
  1114. backbone='MobileNetV3',
  1115. anchors=[[10, 15], [24, 36], [72, 42], [35, 87], [102, 96],
  1116. [60, 170], [220, 125], [128, 222], [264, 266]],
  1117. anchor_masks=[[6, 7, 8], [3, 4, 5], [0, 1, 2]],
  1118. use_iou_aware=False,
  1119. use_spp=True,
  1120. use_drop_block=True,
  1121. scale_x_y=1.05,
  1122. ignore_threshold=0.5,
  1123. label_smooth=False,
  1124. use_iou_loss=True,
  1125. use_matrix_nms=False,
  1126. nms_score_threshold=0.005,
  1127. nms_topk=1000,
  1128. nms_keep_topk=100,
  1129. nms_iou_threshold=0.45):
  1130. self.init_params = locals()
  1131. if backbone != 'MobileNetV3':
  1132. logging.warning(
  1133. "PPYOLOTiny only supports MobileNetV3 as backbone. "
  1134. "Backbone is forcibly set to MobileNetV3.")
  1135. self.backbone_name = 'MobileNetV3'
  1136. if paddlex.env_info['place'] == 'gpu' and paddlex.env_info[
  1137. 'num'] > 1 and not os.environ.get('PADDLEX_EXPORT_STAGE'):
  1138. norm_type = 'sync_bn'
  1139. else:
  1140. norm_type = 'bn'
  1141. backbone = self._get_backbone(
  1142. 'MobileNetV3',
  1143. model_name='large',
  1144. norm_type=norm_type,
  1145. scale=.5,
  1146. with_extra_blocks=False,
  1147. extra_block_filters=[],
  1148. feature_maps=[7, 13, 16])
  1149. downsample_ratios = [32, 16, 8]
  1150. neck = ppdet.modeling.PPYOLOTinyFPN(
  1151. detection_block_channels=[160, 128, 96],
  1152. in_channels=[i.channels for i in backbone.out_shape],
  1153. spp=use_spp,
  1154. drop_block=use_drop_block)
  1155. loss = ppdet.modeling.YOLOv3Loss(
  1156. num_classes=num_classes,
  1157. ignore_thresh=ignore_threshold,
  1158. downsample=downsample_ratios,
  1159. label_smooth=label_smooth,
  1160. scale_x_y=scale_x_y,
  1161. iou_loss=ppdet.modeling.IouLoss(
  1162. loss_weight=2.5, loss_square=True) if use_iou_loss else None,
  1163. iou_aware_loss=ppdet.modeling.IouAwareLoss(loss_weight=1.0)
  1164. if use_iou_aware else None)
  1165. yolo_head = ppdet.modeling.YOLOv3Head(
  1166. in_channels=[i.channels for i in neck.out_shape],
  1167. anchors=anchors,
  1168. anchor_masks=anchor_masks,
  1169. num_classes=num_classes,
  1170. loss=loss,
  1171. iou_aware=use_iou_aware)
  1172. if use_matrix_nms:
  1173. nms = ppdet.modeling.MatrixNMS(
  1174. keep_top_k=nms_keep_topk,
  1175. score_threshold=nms_score_threshold,
  1176. post_threshold=.05,
  1177. nms_top_k=nms_topk,
  1178. background_label=-1)
  1179. else:
  1180. nms = ppdet.modeling.MultiClassNMS(
  1181. score_threshold=nms_score_threshold,
  1182. nms_top_k=nms_topk,
  1183. keep_top_k=nms_keep_topk,
  1184. nms_threshold=nms_iou_threshold)
  1185. post_process = ppdet.modeling.BBoxPostProcess(
  1186. decode=ppdet.modeling.YOLOBox(
  1187. num_classes=num_classes,
  1188. conf_thresh=.005,
  1189. downsample_ratio=32,
  1190. clip_bbox=True,
  1191. scale_x_y=scale_x_y),
  1192. nms=nms)
  1193. params = {
  1194. 'backbone': backbone,
  1195. 'neck': neck,
  1196. 'yolo_head': yolo_head,
  1197. 'post_process': post_process
  1198. }
  1199. super(YOLOv3, self).__init__(
  1200. model_name='YOLOv3', num_classes=num_classes, **params)
  1201. self.anchors = anchors
  1202. self.anchor_masks = anchor_masks
  1203. self.downsample_ratios = downsample_ratios
  1204. self.model_name = 'PPYOLOTiny'
  1205. class PPYOLOv2(YOLOv3):
  1206. def __init__(self,
  1207. num_classes=80,
  1208. backbone='ResNet50_vd_dcn',
  1209. anchors=[[10, 13], [16, 30], [33, 23], [30, 61], [62, 45],
  1210. [59, 119], [116, 90], [156, 198], [373, 326]],
  1211. anchor_masks=[[6, 7, 8], [3, 4, 5], [0, 1, 2]],
  1212. use_iou_aware=True,
  1213. use_spp=True,
  1214. use_drop_block=True,
  1215. scale_x_y=1.05,
  1216. ignore_threshold=0.7,
  1217. label_smooth=False,
  1218. use_iou_loss=True,
  1219. use_matrix_nms=True,
  1220. nms_score_threshold=0.01,
  1221. nms_topk=-1,
  1222. nms_keep_topk=100,
  1223. nms_iou_threshold=0.45):
  1224. self.init_params = locals()
  1225. if backbone not in ['ResNet50_vd_dcn', 'ResNet101_vd_dcn']:
  1226. raise ValueError(
  1227. "backbone: {} is not supported. Please choose one of "
  1228. "('ResNet50_vd_dcn', 'ResNet18_vd')".format(backbone))
  1229. self.backbone_name = backbone
  1230. if paddlex.env_info['place'] == 'gpu' and paddlex.env_info[
  1231. 'num'] > 1 and not os.environ.get('PADDLEX_EXPORT_STAGE'):
  1232. norm_type = 'sync_bn'
  1233. else:
  1234. norm_type = 'bn'
  1235. if backbone == 'ResNet50_vd_dcn':
  1236. backbone = self._get_backbone(
  1237. 'ResNet',
  1238. variant='d',
  1239. norm_type=norm_type,
  1240. return_idx=[1, 2, 3],
  1241. dcn_v2_stages=[3],
  1242. freeze_at=-1,
  1243. freeze_norm=False,
  1244. norm_decay=0.)
  1245. downsample_ratios = [32, 16, 8]
  1246. elif backbone == 'ResNet101_vd_dcn':
  1247. backbone = self._get_backbone(
  1248. 'ResNet',
  1249. depth=101,
  1250. variant='d',
  1251. norm_type=norm_type,
  1252. return_idx=[1, 2, 3],
  1253. dcn_v2_stages=[3],
  1254. freeze_at=-1,
  1255. freeze_norm=False,
  1256. norm_decay=0.)
  1257. downsample_ratios = [32, 16, 8]
  1258. neck = ppdet.modeling.PPYOLOPAN(
  1259. norm_type=norm_type,
  1260. in_channels=[i.channels for i in backbone.out_shape],
  1261. drop_block=use_drop_block,
  1262. block_size=3,
  1263. keep_prob=.9,
  1264. spp=use_spp)
  1265. loss = ppdet.modeling.YOLOv3Loss(
  1266. num_classes=num_classes,
  1267. ignore_thresh=ignore_threshold,
  1268. downsample=downsample_ratios,
  1269. label_smooth=label_smooth,
  1270. scale_x_y=scale_x_y,
  1271. iou_loss=ppdet.modeling.IouLoss(
  1272. loss_weight=2.5, loss_square=True) if use_iou_loss else None,
  1273. iou_aware_loss=ppdet.modeling.IouAwareLoss(loss_weight=1.0)
  1274. if use_iou_aware else None)
  1275. yolo_head = ppdet.modeling.YOLOv3Head(
  1276. in_channels=[i.channels for i in neck.out_shape],
  1277. anchors=anchors,
  1278. anchor_masks=anchor_masks,
  1279. num_classes=num_classes,
  1280. loss=loss,
  1281. iou_aware=use_iou_aware,
  1282. iou_aware_factor=.5)
  1283. if use_matrix_nms:
  1284. nms = ppdet.modeling.MatrixNMS(
  1285. keep_top_k=nms_keep_topk,
  1286. score_threshold=nms_score_threshold,
  1287. post_threshold=.01,
  1288. nms_top_k=nms_topk,
  1289. background_label=-1)
  1290. else:
  1291. nms = ppdet.modeling.MultiClassNMS(
  1292. score_threshold=nms_score_threshold,
  1293. nms_top_k=nms_topk,
  1294. keep_top_k=nms_keep_topk,
  1295. nms_threshold=nms_iou_threshold)
  1296. post_process = ppdet.modeling.BBoxPostProcess(
  1297. decode=ppdet.modeling.YOLOBox(
  1298. num_classes=num_classes,
  1299. conf_thresh=.01,
  1300. downsample_ratio=32,
  1301. clip_bbox=True,
  1302. scale_x_y=scale_x_y),
  1303. nms=nms)
  1304. params = {
  1305. 'backbone': backbone,
  1306. 'neck': neck,
  1307. 'yolo_head': yolo_head,
  1308. 'post_process': post_process
  1309. }
  1310. super(YOLOv3, self).__init__(
  1311. model_name='YOLOv3', num_classes=num_classes, **params)
  1312. self.anchors = anchors
  1313. self.anchor_masks = anchor_masks
  1314. self.downsample_ratios = downsample_ratios
  1315. self.model_name = 'PPYOLOv2'
  1316. def _get_test_inputs(self, image_shape):
  1317. if image_shape is not None:
  1318. if len(image_shape) == 2:
  1319. image_shape = [None, 3] + image_shape
  1320. if image_shape[-2] % 32 > 0 or image_shape[-1] % 32 > 0:
  1321. raise Exception(
  1322. "Height and width in fixed_input_shape must be a multiple of 32, but recieved is {}.".
  1323. format(image_shape[-2:]))
  1324. self._fix_transforms_shape(image_shape[-2:])
  1325. else:
  1326. logging.warning(
  1327. '[Important!!!] When exporting inference model for {},'.format(
  1328. self.__class__.__name__) +
  1329. ' if fixed_input_shape is not set, it will be forcibly set to [None, 3, 608, 608]. '
  1330. +
  1331. 'Please check image shape after transforms is [3, 608, 608], if not, fixed_input_shape '
  1332. + 'should be specified manually.')
  1333. image_shape = [None, 3, 608, 608]
  1334. input_spec = [{
  1335. "image": InputSpec(
  1336. shape=image_shape, name='image', dtype='float32'),
  1337. "im_shape": InputSpec(
  1338. shape=[image_shape[0], 2], name='im_shape', dtype='float32'),
  1339. "scale_factor": InputSpec(
  1340. shape=[image_shape[0], 2],
  1341. name='scale_factor',
  1342. dtype='float32')
  1343. }]
  1344. return input_spec
  1345. class MaskRCNN(BaseDetector):
  1346. def __init__(self,
  1347. num_classes=80,
  1348. backbone='ResNet50_vd',
  1349. with_fpn=True,
  1350. with_dcn=False,
  1351. aspect_ratios=[0.5, 1.0, 2.0],
  1352. anchor_sizes=[[32], [64], [128], [256], [512]],
  1353. keep_top_k=100,
  1354. nms_threshold=0.5,
  1355. score_threshold=0.05,
  1356. fpn_num_channels=256,
  1357. rpn_batch_size_per_im=256,
  1358. rpn_fg_fraction=0.5,
  1359. test_pre_nms_top_n=None,
  1360. test_post_nms_top_n=1000):
  1361. self.init_params = locals()
  1362. if backbone not in [
  1363. 'ResNet50', 'ResNet50_vd', 'ResNet50_vd_ssld', 'ResNet101',
  1364. 'ResNet101_vd'
  1365. ]:
  1366. raise ValueError(
  1367. "backbone: {} is not supported. Please choose one of "
  1368. "('ResNet50', 'ResNet50_vd', 'ResNet50_vd_ssld', 'ResNet101', 'ResNet101_vd')".
  1369. format(backbone))
  1370. self.backbone_name = backbone + '_fpn' if with_fpn else backbone
  1371. dcn_v2_stages = [1, 2, 3] if with_dcn else [-1]
  1372. if backbone == 'ResNet50':
  1373. if with_fpn:
  1374. backbone = self._get_backbone(
  1375. 'ResNet',
  1376. norm_type='bn',
  1377. freeze_at=0,
  1378. return_idx=[0, 1, 2, 3],
  1379. num_stages=4,
  1380. dcn_v2_stages=dcn_v2_stages)
  1381. else:
  1382. if with_dcn:
  1383. logging.warning(
  1384. "Backbone {} should be used along with dcn disabled, 'with_dcn' is forcibly set to False".
  1385. format(backbone))
  1386. backbone = self._get_backbone(
  1387. 'ResNet',
  1388. norm_type='bn',
  1389. freeze_at=0,
  1390. return_idx=[2],
  1391. num_stages=3)
  1392. elif 'ResNet50_vd' in backbone:
  1393. if not with_fpn:
  1394. logging.warning(
  1395. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  1396. format(backbone))
  1397. with_fpn = True
  1398. backbone = self._get_backbone(
  1399. 'ResNet',
  1400. variant='d',
  1401. norm_type='bn',
  1402. freeze_at=0,
  1403. return_idx=[0, 1, 2, 3],
  1404. num_stages=4,
  1405. lr_mult_list=[0.05, 0.05, 0.1, 0.15]
  1406. if '_ssld' in backbone else [1.0, 1.0, 1.0, 1.0],
  1407. dcn_v2_stages=dcn_v2_stages)
  1408. else:
  1409. if not with_fpn:
  1410. logging.warning(
  1411. "Backbone {} should be used along with fpn enabled, 'with_fpn' is forcibly set to True".
  1412. format(backbone))
  1413. with_fpn = True
  1414. backbone = self._get_backbone(
  1415. 'ResNet',
  1416. variant='d' if '_vd' in backbone else 'b',
  1417. depth=101,
  1418. norm_type='bn',
  1419. freeze_at=0,
  1420. return_idx=[0, 1, 2, 3],
  1421. num_stages=4,
  1422. dcn_v2_stages=dcn_v2_stages)
  1423. rpn_in_channel = backbone.out_shape[0].channels
  1424. if with_fpn:
  1425. neck = ppdet.modeling.FPN(
  1426. in_channels=[i.channels for i in backbone.out_shape],
  1427. out_channel=fpn_num_channels,
  1428. spatial_scales=[1.0 / i.stride for i in backbone.out_shape])
  1429. rpn_in_channel = neck.out_shape[0].channels
  1430. anchor_generator_cfg = {
  1431. 'aspect_ratios': aspect_ratios,
  1432. 'anchor_sizes': anchor_sizes,
  1433. 'strides': [4, 8, 16, 32, 64]
  1434. }
  1435. train_proposal_cfg = {
  1436. 'min_size': 0.0,
  1437. 'nms_thresh': .7,
  1438. 'pre_nms_top_n': 2000,
  1439. 'post_nms_top_n': 1000,
  1440. 'topk_after_collect': True
  1441. }
  1442. test_proposal_cfg = {
  1443. 'min_size': 0.0,
  1444. 'nms_thresh': .7,
  1445. 'pre_nms_top_n': 1000
  1446. if test_pre_nms_top_n is None else test_pre_nms_top_n,
  1447. 'post_nms_top_n': test_post_nms_top_n
  1448. }
  1449. bb_head = ppdet.modeling.TwoFCHead(
  1450. in_channel=neck.out_shape[0].channels, out_channel=1024)
  1451. bb_roi_extractor_cfg = {
  1452. 'resolution': 7,
  1453. 'spatial_scale': [1. / i.stride for i in neck.out_shape],
  1454. 'sampling_ratio': 0,
  1455. 'aligned': True
  1456. }
  1457. with_pool = False
  1458. m_head = ppdet.modeling.MaskFeat(
  1459. in_channel=neck.out_shape[0].channels,
  1460. out_channel=256,
  1461. num_convs=4)
  1462. m_roi_extractor_cfg = {
  1463. 'resolution': 14,
  1464. 'spatial_scale': [1. / i.stride for i in neck.out_shape],
  1465. 'sampling_ratio': 0,
  1466. 'aligned': True
  1467. }
  1468. mask_assigner = MaskAssigner(
  1469. num_classes=num_classes, mask_resolution=28)
  1470. share_bbox_feat = False
  1471. else:
  1472. neck = None
  1473. anchor_generator_cfg = {
  1474. 'aspect_ratios': aspect_ratios,
  1475. 'anchor_sizes': anchor_sizes,
  1476. 'strides': [16]
  1477. }
  1478. train_proposal_cfg = {
  1479. 'min_size': 0.0,
  1480. 'nms_thresh': .7,
  1481. 'pre_nms_top_n': 12000,
  1482. 'post_nms_top_n': 2000,
  1483. 'topk_after_collect': False
  1484. }
  1485. test_proposal_cfg = {
  1486. 'min_size': 0.0,
  1487. 'nms_thresh': .7,
  1488. 'pre_nms_top_n': 6000
  1489. if test_pre_nms_top_n is None else test_pre_nms_top_n,
  1490. 'post_nms_top_n': test_post_nms_top_n
  1491. }
  1492. bb_head = ppdet.modeling.Res5Head()
  1493. bb_roi_extractor_cfg = {
  1494. 'resolution': 14,
  1495. 'spatial_scale': [1. / i.stride for i in backbone.out_shape],
  1496. 'sampling_ratio': 0,
  1497. 'aligned': True
  1498. }
  1499. with_pool = True
  1500. m_head = ppdet.modeling.MaskFeat(
  1501. in_channel=bb_head.out_shape[0].channels,
  1502. out_channel=256,
  1503. num_convs=0)
  1504. m_roi_extractor_cfg = {
  1505. 'resolution': 14,
  1506. 'spatial_scale': [1. / i.stride for i in backbone.out_shape],
  1507. 'sampling_ratio': 0,
  1508. 'aligned': True
  1509. }
  1510. mask_assigner = MaskAssigner(
  1511. num_classes=num_classes, mask_resolution=14)
  1512. share_bbox_feat = True
  1513. rpn_target_assign_cfg = {
  1514. 'batch_size_per_im': rpn_batch_size_per_im,
  1515. 'fg_fraction': rpn_fg_fraction,
  1516. 'negative_overlap': .3,
  1517. 'positive_overlap': .7,
  1518. 'use_random': True
  1519. }
  1520. rpn_head = ppdet.modeling.RPNHead(
  1521. anchor_generator=anchor_generator_cfg,
  1522. rpn_target_assign=rpn_target_assign_cfg,
  1523. train_proposal=train_proposal_cfg,
  1524. test_proposal=test_proposal_cfg,
  1525. in_channel=rpn_in_channel)
  1526. bbox_assigner = BBoxAssigner(num_classes=num_classes)
  1527. bbox_head = ppdet.modeling.BBoxHead(
  1528. head=bb_head,
  1529. in_channel=bb_head.out_shape[0].channels,
  1530. roi_extractor=bb_roi_extractor_cfg,
  1531. with_pool=with_pool,
  1532. bbox_assigner=bbox_assigner,
  1533. num_classes=num_classes)
  1534. mask_head = ppdet.modeling.MaskHead(
  1535. head=m_head,
  1536. roi_extractor=m_roi_extractor_cfg,
  1537. mask_assigner=mask_assigner,
  1538. share_bbox_feat=share_bbox_feat,
  1539. num_classes=num_classes)
  1540. bbox_post_process = ppdet.modeling.BBoxPostProcess(
  1541. num_classes=num_classes,
  1542. decode=ppdet.modeling.RCNNBox(num_classes=num_classes),
  1543. nms=ppdet.modeling.MultiClassNMS(
  1544. score_threshold=score_threshold,
  1545. keep_top_k=keep_top_k,
  1546. nms_threshold=nms_threshold))
  1547. mask_post_process = ppdet.modeling.MaskPostProcess(binary_thresh=.5)
  1548. params = {
  1549. 'backbone': backbone,
  1550. 'neck': neck,
  1551. 'rpn_head': rpn_head,
  1552. 'bbox_head': bbox_head,
  1553. 'mask_head': mask_head,
  1554. 'bbox_post_process': bbox_post_process,
  1555. 'mask_post_process': mask_post_process
  1556. }
  1557. self.with_fpn = with_fpn
  1558. super(MaskRCNN, self).__init__(
  1559. model_name='MaskRCNN', num_classes=num_classes, **params)
  1560. def _compose_batch_transform(self, transforms, mode='train'):
  1561. if mode == 'train':
  1562. default_batch_transforms = [
  1563. _BatchPadding(pad_to_stride=32 if self.with_fpn else -1)
  1564. ]
  1565. collate_batch = False
  1566. else:
  1567. default_batch_transforms = [
  1568. _BatchPadding(pad_to_stride=32 if self.with_fpn else -1)
  1569. ]
  1570. collate_batch = True
  1571. custom_batch_transforms = []
  1572. for i, op in enumerate(transforms.transforms):
  1573. if isinstance(op, (BatchRandomResize, BatchRandomResizeByShort)):
  1574. if mode != 'train':
  1575. raise Exception(
  1576. "{} cannot be present in the {} transforms. ".format(
  1577. op.__class__.__name__, mode) +
  1578. "Please check the {} transforms.".format(mode))
  1579. custom_batch_transforms.insert(0, copy.deepcopy(op))
  1580. batch_transforms = BatchCompose(
  1581. custom_batch_transforms + default_batch_transforms,
  1582. collate_batch=collate_batch)
  1583. return batch_transforms
  1584. def _fix_transforms_shape(self, image_shape):
  1585. if hasattr(self, 'test_transforms'):
  1586. if self.test_transforms is not None:
  1587. has_resize_op = False
  1588. resize_op_idx = -1
  1589. normalize_op_idx = len(self.test_transforms.transforms)
  1590. for idx, op in enumerate(self.test_transforms.transforms):
  1591. name = op.__class__.__name__
  1592. if name == 'ResizeByShort':
  1593. has_resize_op = True
  1594. resize_op_idx = idx
  1595. if name == 'Normalize':
  1596. normalize_op_idx = idx
  1597. if not has_resize_op:
  1598. self.test_transforms.transforms.insert(
  1599. normalize_op_idx,
  1600. Resize(
  1601. target_size=image_shape,
  1602. keep_ratio=True,
  1603. interp='CUBIC'))
  1604. else:
  1605. self.test_transforms.transforms[resize_op_idx] = Resize(
  1606. target_size=image_shape,
  1607. keep_ratio=True,
  1608. interp='CUBIC')
  1609. self.test_transforms.transforms.append(
  1610. Padding(im_padding_value=[0., 0., 0.]))
  1611. def _get_test_inputs(self, image_shape):
  1612. if image_shape is not None:
  1613. image_shape = self._check_image_shape(image_shape)
  1614. self._fix_transforms_shape(image_shape[-2:])
  1615. else:
  1616. image_shape = [None, 3, -1, -1]
  1617. if self.with_fpn:
  1618. self.test_transforms.transforms.append(
  1619. Padding(im_padding_value=[0., 0., 0.]))
  1620. return self._define_input_spec(image_shape)