classifier.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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 math
  16. import os.path as osp
  17. from collections import OrderedDict
  18. import numpy as np
  19. import paddle
  20. import paddle.nn.functional as F
  21. from paddle.static import InputSpec
  22. from paddlex.utils import logging, TrainingStats, DisablePrint
  23. from paddlex.cv.models.base import BaseModel
  24. from paddlex.cv.transforms import arrange_transforms
  25. from paddlex.cv.transforms.operators import Resize
  26. with DisablePrint():
  27. from paddlex.ppcls.modeling import architectures
  28. from paddlex.ppcls.modeling.loss import CELoss
  29. __all__ = [
  30. "ResNet18", "ResNet34", "ResNet50", "ResNet101", "ResNet152",
  31. "ResNet18_vd", "ResNet34_vd", "ResNet50_vd", "ResNet50_vd_ssld",
  32. "ResNet101_vd", "ResNet101_vd_ssld", "ResNet152_vd", "ResNet200_vd",
  33. "AlexNet", "DarkNet53", "MobileNetV1", "MobileNetV2", "MobileNetV3_small",
  34. "MobileNetV3_small_ssld", "MobileNetV3_large", "MobileNetV3_large_ssld",
  35. "DenseNet121", "DenseNet161", "DenseNet169", "DenseNet201", "DenseNet264",
  36. "HRNet_W18_C", "HRNet_W30_C", "HRNet_W32_C", "HRNet_W40_C", "HRNet_W44_C",
  37. "HRNet_W48_C", "HRNet_W64_C", "Xception41", "Xception65", "Xception71",
  38. "ShuffleNetV2", "ShuffleNetV2_swish"
  39. ]
  40. class BaseClassifier(BaseModel):
  41. """Parent class of all classification models.
  42. Args:
  43. model_name (str, optional): Name of classification model. Defaults to 'ResNet50'.
  44. num_classes (int, optional): The number of target classes. Defaults to 1000.
  45. """
  46. def __init__(self, model_name='ResNet50', num_classes=1000, **params):
  47. self.init_params = locals()
  48. self.init_params.update(params)
  49. if 'lr_mult_list' in self.init_params:
  50. del self.init_params['lr_mult_list']
  51. if 'with_net' in self.init_params:
  52. del self.init_params['with_net']
  53. super(BaseClassifier, self).__init__('classifier')
  54. if not hasattr(architectures, model_name):
  55. raise Exception("ERROR: There's no model named {}.".format(
  56. model_name))
  57. self.model_name = model_name
  58. self.labels = None
  59. self.num_classes = num_classes
  60. for k, v in params.items():
  61. setattr(self, k, v)
  62. if params.get('with_net', True):
  63. params.pop('with_net', None)
  64. self.net = self.build_net(**params)
  65. def build_net(self, **params):
  66. with paddle.utils.unique_name.guard():
  67. net = architectures.__dict__[self.model_name](
  68. class_dim=self.num_classes, **params)
  69. return net
  70. def _fix_transforms_shape(self, image_shape):
  71. if hasattr(self, 'test_transforms'):
  72. if self.test_transforms is not None:
  73. self.test_transforms.transforms.append(
  74. Resize(target_size=image_shape))
  75. def _get_test_inputs(self, image_shape):
  76. if image_shape is not None:
  77. if len(image_shape) == 2:
  78. image_shape = [1, 3] + image_shape
  79. self._fix_transforms_shape(image_shape[-2:])
  80. else:
  81. image_shape = [None, 3, -1, -1]
  82. self.fixed_input_shape = image_shape
  83. input_spec = [
  84. InputSpec(
  85. shape=image_shape, name='image', dtype='float32')
  86. ]
  87. return input_spec
  88. def run(self, net, inputs, mode):
  89. net_out = net(inputs[0])
  90. softmax_out = net_out if self.status == 'Infer' else F.softmax(net_out)
  91. if mode == 'test':
  92. outputs = OrderedDict([('prediction', softmax_out)])
  93. elif mode == 'eval':
  94. pred = softmax_out
  95. gt = inputs[1]
  96. labels = inputs[1].reshape([-1, 1])
  97. acc1 = paddle.metric.accuracy(softmax_out, label=labels)
  98. k = min(5, self.num_classes)
  99. acck = paddle.metric.accuracy(softmax_out, label=labels, k=k)
  100. # multi cards eval
  101. if paddle.distributed.get_world_size() > 1:
  102. acc1 = paddle.distributed.all_reduce(
  103. acc1, op=paddle.distributed.ReduceOp.
  104. SUM) / paddle.distributed.get_world_size()
  105. acck = paddle.distributed.all_reduce(
  106. acck, op=paddle.distributed.ReduceOp.
  107. SUM) / paddle.distributed.get_world_size()
  108. pred = list()
  109. gt = list()
  110. paddle.distributed.all_gather(pred, softmax_out)
  111. paddle.distributed.all_gather(gt, inputs[1])
  112. pred = paddle.concat(pred, axis=0)
  113. gt = paddle.concat(gt, axis=0)
  114. outputs = OrderedDict([('acc1', acc1), ('acc{}'.format(k), acck),
  115. ('prediction', pred), ('labels', gt)])
  116. else:
  117. # mode == 'train'
  118. labels = inputs[1].reshape([-1, 1])
  119. loss = CELoss(class_dim=self.num_classes)
  120. loss = loss(net_out, inputs[1])
  121. acc1 = paddle.metric.accuracy(softmax_out, label=labels, k=1)
  122. k = min(5, self.num_classes)
  123. acck = paddle.metric.accuracy(softmax_out, label=labels, k=k)
  124. outputs = OrderedDict([('loss', loss), ('acc1', acc1),
  125. ('acc{}'.format(k), acck)])
  126. return outputs
  127. def default_optimizer(self, parameters, learning_rate, warmup_steps,
  128. warmup_start_lr, lr_decay_epochs, lr_decay_gamma,
  129. num_steps_each_epoch):
  130. boundaries = [b * num_steps_each_epoch for b in lr_decay_epochs]
  131. values = [
  132. learning_rate * (lr_decay_gamma**i)
  133. for i in range(len(lr_decay_epochs) + 1)
  134. ]
  135. scheduler = paddle.optimizer.lr.PiecewiseDecay(boundaries, values)
  136. if warmup_steps > 0:
  137. if warmup_steps > lr_decay_epochs[0] * num_steps_each_epoch:
  138. logging.error(
  139. "In function train(), parameters should satisfy: "
  140. "warmup_steps <= lr_decay_epochs[0]*num_samples_in_train_dataset",
  141. exit=False)
  142. logging.error(
  143. "See this doc for more information: "
  144. "https://github.com/PaddlePaddle/PaddleX/blob/release/2.0.0/docs/parameters.md",
  145. exit=False)
  146. logging.error(
  147. "warmup_steps should less than {} or lr_decay_epochs[0] greater than {}, "
  148. "please modify 'lr_decay_epochs' or 'warmup_steps' in train function".
  149. format(lr_decay_epochs[0] * num_steps_each_epoch,
  150. warmup_steps // num_steps_each_epoch))
  151. scheduler = paddle.optimizer.lr.LinearWarmup(
  152. learning_rate=scheduler,
  153. warmup_steps=warmup_steps,
  154. start_lr=warmup_start_lr,
  155. end_lr=learning_rate)
  156. optimizer = paddle.optimizer.Momentum(
  157. scheduler,
  158. momentum=.9,
  159. weight_decay=paddle.regularizer.L2Decay(coeff=1e-04),
  160. parameters=parameters)
  161. return optimizer
  162. def train(self,
  163. num_epochs,
  164. train_dataset,
  165. train_batch_size=64,
  166. eval_dataset=None,
  167. optimizer=None,
  168. save_interval_epochs=1,
  169. log_interval_steps=10,
  170. save_dir='output',
  171. pretrain_weights='IMAGENET',
  172. learning_rate=.025,
  173. warmup_steps=0,
  174. warmup_start_lr=0.0,
  175. lr_decay_epochs=(30, 60, 90),
  176. lr_decay_gamma=0.1,
  177. early_stop=False,
  178. early_stop_patience=5,
  179. use_vdl=True,
  180. resume_checkpoint=None):
  181. """
  182. Train the model.
  183. Args:
  184. num_epochs(int): The number of epochs.
  185. train_dataset(paddlex.dataset): Training dataset.
  186. train_batch_size(int, optional): Total batch size among all cards used in training. Defaults to 64.
  187. eval_dataset(paddlex.dataset, optional):
  188. Evaluation dataset. If None, the model will not be evaluated during training process. Defaults to None.
  189. optimizer(paddle.optimizer.Optimizer or None, optional):
  190. Optimizer used for training. If None, a default optimizer is used. Defaults to None.
  191. save_interval_epochs(int, optional): Epoch interval for saving the model. Defaults to 1.
  192. log_interval_steps(int, optional): Step interval for printing training information. Defaults to 10.
  193. save_dir(str, optional): Directory to save the model. Defaults to 'output'.
  194. pretrain_weights(str or None, optional):
  195. None or name/path of pretrained weights. If None, no pretrained weights will be loaded.
  196. At most one of `resume_checkpoint` and `pretrain_weights` can be set simultaneously.
  197. Defaults to 'IMAGENET'.
  198. learning_rate(float, optional): Learning rate for training. Defaults to .025.
  199. warmup_steps(int, optional): The number of steps of warm-up training. Defaults to 0.
  200. warmup_start_lr(float, optional): Start learning rate of warm-up training. Defaults to 0..
  201. lr_decay_epochs(List[int] or Tuple[int], optional):
  202. Epoch milestones for learning rate decay. Defaults to (20, 60, 90).
  203. lr_decay_gamma(float, optional): Gamma coefficient of learning rate decay, default .1.
  204. early_stop(bool, optional): Whether to adopt early stop strategy. Defaults to False.
  205. early_stop_patience(int, optional): Early stop patience. Defaults to 5.
  206. use_vdl(bool, optional): Whether to use VisualDL to monitor the training process. Defaults to True.
  207. resume_checkpoint(str or None, optional): The path of the checkpoint to resume training from.
  208. If None, no training checkpoint will be resumed. At most one of `resume_checkpoint` and
  209. `pretrain_weights` can be set simultaneously. Defaults to None.
  210. """
  211. if self.status == 'Infer':
  212. logging.error(
  213. "Exported inference model does not support training.",
  214. exit=True)
  215. if pretrain_weights is not None and resume_checkpoint is not None:
  216. logging.error(
  217. "pretrain_weights and resume_checkpoint cannot be set simultaneously.",
  218. exit=True)
  219. self.labels = train_dataset.labels
  220. # build optimizer if not defined
  221. if optimizer is None:
  222. num_steps_each_epoch = len(train_dataset) // train_batch_size
  223. self.optimizer = self.default_optimizer(
  224. parameters=self.net.parameters(),
  225. learning_rate=learning_rate,
  226. warmup_steps=warmup_steps,
  227. warmup_start_lr=warmup_start_lr,
  228. lr_decay_epochs=lr_decay_epochs,
  229. lr_decay_gamma=lr_decay_gamma,
  230. num_steps_each_epoch=num_steps_each_epoch)
  231. else:
  232. self.optimizer = optimizer
  233. # initiate weights
  234. if pretrain_weights is not None and not osp.exists(pretrain_weights):
  235. if pretrain_weights not in ['IMAGENET']:
  236. logging.warning(
  237. "Path of pretrain_weights('{}') does not exist!".format(
  238. pretrain_weights))
  239. logging.warning(
  240. "Pretrain_weights is forcibly set to 'IMAGENET'. "
  241. "If don't want to use pretrain weights, "
  242. "set pretrain_weights to be None.")
  243. pretrain_weights = 'IMAGENET'
  244. elif pretrain_weights is not None and osp.exists(pretrain_weights):
  245. if osp.splitext(pretrain_weights)[-1] != '.pdparams':
  246. logging.error(
  247. "Invalid pretrain weights. Please specify a '.pdparams' file.",
  248. exit=True)
  249. pretrained_dir = osp.join(save_dir, 'pretrain')
  250. self.net_initialize(
  251. pretrain_weights=pretrain_weights,
  252. save_dir=pretrained_dir,
  253. resume_checkpoint=resume_checkpoint)
  254. # start train loop
  255. self.train_loop(
  256. num_epochs=num_epochs,
  257. train_dataset=train_dataset,
  258. train_batch_size=train_batch_size,
  259. eval_dataset=eval_dataset,
  260. save_interval_epochs=save_interval_epochs,
  261. log_interval_steps=log_interval_steps,
  262. save_dir=save_dir,
  263. early_stop=early_stop,
  264. early_stop_patience=early_stop_patience,
  265. use_vdl=use_vdl)
  266. def quant_aware_train(self,
  267. num_epochs,
  268. train_dataset,
  269. train_batch_size=64,
  270. eval_dataset=None,
  271. optimizer=None,
  272. save_interval_epochs=1,
  273. log_interval_steps=10,
  274. save_dir='output',
  275. learning_rate=.000025,
  276. warmup_steps=0,
  277. warmup_start_lr=0.0,
  278. lr_decay_epochs=(30, 60, 90),
  279. lr_decay_gamma=0.1,
  280. early_stop=False,
  281. early_stop_patience=5,
  282. use_vdl=True,
  283. resume_checkpoint=None,
  284. quant_config=None):
  285. """
  286. Quantization-aware training.
  287. Args:
  288. num_epochs(int): The number of epochs.
  289. train_dataset(paddlex.dataset): Training dataset.
  290. train_batch_size(int, optional): Total batch size among all cards used in training. Defaults to 64.
  291. eval_dataset(paddlex.dataset, optional):
  292. Evaluation dataset. If None, the model will not be evaluated during training process. Defaults to None.
  293. optimizer(paddle.optimizer.Optimizer or None, optional):
  294. Optimizer used for training. If None, a default optimizer is used. Defaults to None.
  295. save_interval_epochs(int, optional): Epoch interval for saving the model. Defaults to 1.
  296. log_interval_steps(int, optional): Step interval for printing training information. Defaults to 10.
  297. save_dir(str, optional): Directory to save the model. Defaults to 'output'.
  298. learning_rate(float, optional): Learning rate for training. Defaults to .025.
  299. warmup_steps(int, optional): The number of steps of warm-up training. Defaults to 0.
  300. warmup_start_lr(float, optional): Start learning rate of warm-up training. Defaults to 0..
  301. lr_decay_epochs(List[int] or Tuple[int], optional):
  302. Epoch milestones for learning rate decay. Defaults to (20, 60, 90).
  303. lr_decay_gamma(float, optional): Gamma coefficient of learning rate decay, default .1.
  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. early_stop=early_stop,
  329. early_stop_patience=early_stop_patience,
  330. use_vdl=use_vdl,
  331. resume_checkpoint=resume_checkpoint)
  332. def evaluate(self, eval_dataset, batch_size=1, return_details=False):
  333. """
  334. Evaluate the model.
  335. Args:
  336. eval_dataset(paddlex.dataset): Evaluation dataset.
  337. batch_size(int, optional): Total batch size among all cards used for evaluation. Defaults to 1.
  338. return_details(bool, optional): Whether to return evaluation details. Defaults to False.
  339. Returns:
  340. collections.OrderedDict with key-value pairs: {"acc1": `top 1 accuracy`, "acc5": `top 5 accuracy`}.
  341. """
  342. # 给transform添加arrange操作
  343. arrange_transforms(
  344. model_type=self.model_type,
  345. transforms=eval_dataset.transforms,
  346. mode='eval')
  347. self.net.eval()
  348. nranks = paddle.distributed.get_world_size()
  349. local_rank = paddle.distributed.get_rank()
  350. if nranks > 1:
  351. # Initialize parallel environment if not done.
  352. if not paddle.distributed.parallel.parallel_helper._is_parallel_ctx_initialized(
  353. ):
  354. paddle.distributed.init_parallel_env()
  355. self.eval_data_loader = self.build_data_loader(
  356. eval_dataset, batch_size=batch_size, mode='eval')
  357. eval_metrics = TrainingStats()
  358. if return_details:
  359. true_labels = list()
  360. pred_scores = list()
  361. logging.info(
  362. "Start to evaluate(total_samples={}, total_steps={})...".format(
  363. eval_dataset.num_samples,
  364. math.ceil(eval_dataset.num_samples * 1.0 / batch_size)))
  365. with paddle.no_grad():
  366. for step, data in enumerate(self.eval_data_loader()):
  367. outputs = self.run(self.net, data, mode='eval')
  368. if return_details:
  369. true_labels.extend(outputs['labels'].tolist())
  370. pred_scores.extend(outputs['prediction'].tolist())
  371. outputs.pop('prediction')
  372. outputs.pop('labels')
  373. eval_metrics.update(outputs)
  374. if return_details:
  375. eval_details = {
  376. 'true_labels': true_labels,
  377. 'pred_scores': pred_scores
  378. }
  379. return eval_metrics.get(), eval_details
  380. else:
  381. return eval_metrics.get()
  382. def predict(self, img_file, transforms=None, topk=1):
  383. """
  384. Do inference.
  385. Args:
  386. img_file(List[np.ndarray or str], str or np.ndarray):
  387. Image path or decoded image data in a BGR format, which also could constitute a list,
  388. meaning all images to be predicted as a mini-batch.
  389. transforms(paddlex.transforms.Compose or None, optional):
  390. Transforms for inputs. If None, the transforms for evaluation process will be used. Defaults to None.
  391. topk(int, optional): Keep topk results in prediction. Defaults to 1.
  392. Returns:
  393. If img_file is a string or np.array, the result is a dict with key-value pairs:
  394. {"category_id": `category_id`, "category": `category`, "score": `score`}.
  395. If img_file is a list, the result is a list composed of dicts with the corresponding fields:
  396. category_id(int): the predicted category ID
  397. category(str): category name
  398. score(float): confidence
  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 transforms is None:
  403. transforms = self.test_transforms
  404. true_topk = min(self.num_classes, topk)
  405. if isinstance(img_file, (str, np.ndarray)):
  406. images = [img_file]
  407. else:
  408. images = img_file
  409. im = self._preprocess(images, transforms)
  410. self.net.eval()
  411. with paddle.no_grad():
  412. outputs = self.run(self.net, im, mode='test')
  413. prediction = outputs['prediction'].numpy()
  414. prediction = self._postprocess(prediction, true_topk)
  415. if isinstance(img_file, (str, np.ndarray)):
  416. prediction = prediction[0]
  417. return prediction
  418. def _preprocess(self, images, transforms, to_tensor=True):
  419. arrange_transforms(
  420. model_type=self.model_type, transforms=transforms, mode='test')
  421. batch_im = list()
  422. for im in images:
  423. sample = {'image': im}
  424. batch_im.append(transforms(sample))
  425. if to_tensor:
  426. batch_im = paddle.to_tensor(batch_im)
  427. else:
  428. batch_im = np.asarray(batch_im)
  429. return batch_im,
  430. def _postprocess(self, results, true_topk):
  431. preds = list()
  432. for i, pred in enumerate(results):
  433. pred_label = np.argsort(pred)[::-1][:true_topk]
  434. preds.append([{
  435. 'category_id': l,
  436. 'category': self.labels[l],
  437. 'score': results[i][l]
  438. } for l in pred_label])
  439. return preds
  440. class ResNet18(BaseClassifier):
  441. def __init__(self, num_classes=1000, **params):
  442. super(ResNet18, self).__init__(
  443. model_name='ResNet18', num_classes=num_classes, **params)
  444. class ResNet34(BaseClassifier):
  445. def __init__(self, num_classes=1000, **params):
  446. super(ResNet34, self).__init__(
  447. model_name='ResNet34', num_classes=num_classes, **params)
  448. class ResNet50(BaseClassifier):
  449. def __init__(self, num_classes=1000, **params):
  450. super(ResNet50, self).__init__(
  451. model_name='ResNet50', num_classes=num_classes, **params)
  452. class ResNet101(BaseClassifier):
  453. def __init__(self, num_classes=1000, **params):
  454. super(ResNet101, self).__init__(
  455. model_name='ResNet101', num_classes=num_classes, **params)
  456. class ResNet152(BaseClassifier):
  457. def __init__(self, num_classes=1000, **params):
  458. super(ResNet152, self).__init__(
  459. model_name='ResNet152', num_classes=num_classes, **params)
  460. class ResNet18_vd(BaseClassifier):
  461. def __init__(self, num_classes=1000, **params):
  462. super(ResNet18_vd, self).__init__(
  463. model_name='ResNet18_vd', num_classes=num_classes, **params)
  464. class ResNet34_vd(BaseClassifier):
  465. def __init__(self, num_classes=1000, **params):
  466. super(ResNet34_vd, self).__init__(
  467. model_name='ResNet34_vd', num_classes=num_classes, **params)
  468. class ResNet50_vd(BaseClassifier):
  469. def __init__(self, num_classes=1000, **params):
  470. super(ResNet50_vd, self).__init__(
  471. model_name='ResNet50_vd', num_classes=num_classes, **params)
  472. class ResNet50_vd_ssld(BaseClassifier):
  473. def __init__(self, num_classes=1000, **params):
  474. super(ResNet50_vd_ssld, self).__init__(
  475. model_name='ResNet50_vd',
  476. num_classes=num_classes,
  477. lr_mult_list=[.1, .1, .2, .2, .3],
  478. **params)
  479. self.model_name = 'ResNet50_vd_ssld'
  480. class ResNet101_vd(BaseClassifier):
  481. def __init__(self, num_classes=1000, **params):
  482. super(ResNet101_vd, self).__init__(
  483. model_name='ResNet101_vd', num_classes=num_classes, **params)
  484. class ResNet101_vd_ssld(BaseClassifier):
  485. def __init__(self, num_classes=1000, **params):
  486. super(ResNet101_vd_ssld, self).__init__(
  487. model_name='ResNet101_vd',
  488. num_classes=num_classes,
  489. lr_mult_list=[.1, .1, .2, .2, .3],
  490. **params)
  491. self.model_name = 'ResNet101_vd_ssld'
  492. class ResNet152_vd(BaseClassifier):
  493. def __init__(self, num_classes=1000, **params):
  494. super(ResNet152_vd, self).__init__(
  495. model_name='ResNet152_vd', num_classes=num_classes, **params)
  496. class ResNet200_vd(BaseClassifier):
  497. def __init__(self, num_classes=1000, **params):
  498. super(ResNet200_vd, self).__init__(
  499. model_name='ResNet200_vd', num_classes=num_classes, **params)
  500. class AlexNet(BaseClassifier):
  501. def __init__(self, num_classes=1000, **params):
  502. super(AlexNet, self).__init__(
  503. model_name='AlexNet', num_classes=num_classes, **params)
  504. def _get_test_inputs(self, image_shape):
  505. if image_shape is not None:
  506. if len(image_shape) == 2:
  507. image_shape = [None, 3] + image_shape
  508. else:
  509. image_shape = [None, 3, 224, 224]
  510. logging.warning(
  511. '[Important!!!] When exporting inference model for {},'.format(
  512. self.__class__.__name__) +
  513. ' if fixed_input_shape is not set, it will be forcibly set to [None, 3, 224, 224]'
  514. +
  515. 'Please check image shape after transforms is [3, 224, 224], if not, fixed_input_shape '
  516. + 'should be specified manually.')
  517. self._fix_transforms_shape(image_shape[-2:])
  518. self.fixed_input_shape = image_shape
  519. input_spec = [
  520. InputSpec(
  521. shape=image_shape, name='image', dtype='float32')
  522. ]
  523. return input_spec
  524. class DarkNet53(BaseClassifier):
  525. def __init__(self, num_classes=1000, **params):
  526. super(DarkNet53, self).__init__(
  527. model_name='DarkNet53', num_classes=num_classes, **params)
  528. class MobileNetV1(BaseClassifier):
  529. def __init__(self, num_classes=1000, scale=1.0, **params):
  530. supported_scale = [.25, .5, .75, 1.0]
  531. if scale not in supported_scale:
  532. logging.warning("scale={} is not supported by MobileNetV1, "
  533. "scale is forcibly set to 1.0".format(scale))
  534. scale = 1.0
  535. if scale == 1:
  536. model_name = 'MobileNetV1'
  537. else:
  538. model_name = 'MobileNetV1_x' + str(scale).replace('.', '_')
  539. self.scale = scale
  540. super(MobileNetV1, self).__init__(
  541. model_name=model_name, num_classes=num_classes, **params)
  542. class MobileNetV2(BaseClassifier):
  543. def __init__(self, num_classes=1000, scale=1.0, **params):
  544. supported_scale = [.25, .5, .75, 1.0, 1.5, 2.0]
  545. if scale not in supported_scale:
  546. logging.warning("scale={} is not supported by MobileNetV2, "
  547. "scale is forcibly set to 1.0".format(scale))
  548. scale = 1.0
  549. if scale == 1:
  550. model_name = 'MobileNetV2'
  551. else:
  552. model_name = 'MobileNetV2_x' + str(scale).replace('.', '_')
  553. super(MobileNetV2, self).__init__(
  554. model_name=model_name, num_classes=num_classes, **params)
  555. class MobileNetV3_small(BaseClassifier):
  556. def __init__(self, num_classes=1000, scale=1.0, **params):
  557. supported_scale = [.35, .5, .75, 1.0, 1.25]
  558. if scale not in supported_scale:
  559. logging.warning("scale={} is not supported by MobileNetV3_small, "
  560. "scale is forcibly set to 1.0".format(scale))
  561. scale = 1.0
  562. model_name = 'MobileNetV3_small_x' + str(float(scale)).replace('.',
  563. '_')
  564. super(MobileNetV3_small, self).__init__(
  565. model_name=model_name, num_classes=num_classes, **params)
  566. class MobileNetV3_small_ssld(BaseClassifier):
  567. def __init__(self, num_classes=1000, scale=1.0, **params):
  568. supported_scale = [.35, 1.0]
  569. if scale not in supported_scale:
  570. logging.warning(
  571. "scale={} is not supported by MobileNetV3_small_ssld, "
  572. "scale is forcibly set to 1.0".format(scale))
  573. scale = 1.0
  574. model_name = 'MobileNetV3_small_x' + str(float(scale)).replace('.',
  575. '_')
  576. super(MobileNetV3_small_ssld, self).__init__(
  577. model_name=model_name, num_classes=num_classes, **params)
  578. self.model_name = model_name + '_ssld'
  579. class MobileNetV3_large(BaseClassifier):
  580. def __init__(self, num_classes=1000, scale=1.0, **params):
  581. supported_scale = [.35, .5, .75, 1.0, 1.25]
  582. if scale not in supported_scale:
  583. logging.warning("scale={} is not supported by MobileNetV3_large, "
  584. "scale is forcibly set to 1.0".format(scale))
  585. scale = 1.0
  586. model_name = 'MobileNetV3_large_x' + str(float(scale)).replace('.',
  587. '_')
  588. super(MobileNetV3_large, self).__init__(
  589. model_name=model_name, num_classes=num_classes, **params)
  590. class MobileNetV3_large_ssld(BaseClassifier):
  591. def __init__(self, num_classes=1000, **params):
  592. super(MobileNetV3_large_ssld, self).__init__(
  593. model_name='MobileNetV3_large_x1_0',
  594. num_classes=num_classes,
  595. **params)
  596. self.model_name = 'MobileNetV3_large_x1_0_ssld'
  597. class DenseNet121(BaseClassifier):
  598. def __init__(self, num_classes=1000, **params):
  599. super(DenseNet121, self).__init__(
  600. model_name='DenseNet121', num_classes=num_classes, **params)
  601. class DenseNet161(BaseClassifier):
  602. def __init__(self, num_classes=1000, **params):
  603. super(DenseNet161, self).__init__(
  604. model_name='DenseNet161', num_classes=num_classes, **params)
  605. class DenseNet169(BaseClassifier):
  606. def __init__(self, num_classes=1000, **params):
  607. super(DenseNet169, self).__init__(
  608. model_name='DenseNet169', num_classes=num_classes, **params)
  609. class DenseNet201(BaseClassifier):
  610. def __init__(self, num_classes=1000, **params):
  611. super(DenseNet201, self).__init__(
  612. model_name='DenseNet201', num_classes=num_classes, **params)
  613. class DenseNet264(BaseClassifier):
  614. def __init__(self, num_classes=1000, **params):
  615. super(DenseNet264, self).__init__(
  616. model_name='DenseNet264', num_classes=num_classes, **params)
  617. class HRNet_W18_C(BaseClassifier):
  618. def __init__(self, num_classes=1000, **params):
  619. super(HRNet_W18_C, self).__init__(
  620. model_name='HRNet_W18_C', num_classes=num_classes, **params)
  621. class HRNet_W30_C(BaseClassifier):
  622. def __init__(self, num_classes=1000, **params):
  623. super(HRNet_W30_C, self).__init__(
  624. model_name='HRNet_W30_C', num_classes=num_classes, **params)
  625. class HRNet_W32_C(BaseClassifier):
  626. def __init__(self, num_classes=1000, **params):
  627. super(HRNet_W32_C, self).__init__(
  628. model_name='HRNet_W32_C', num_classes=num_classes, **params)
  629. class HRNet_W40_C(BaseClassifier):
  630. def __init__(self, num_classes=1000, **params):
  631. super(HRNet_W40_C, self).__init__(
  632. model_name='HRNet_W40_C', num_classes=num_classes, **params)
  633. class HRNet_W44_C(BaseClassifier):
  634. def __init__(self, num_classes=1000, **params):
  635. super(HRNet_W44_C, self).__init__(
  636. model_name='HRNet_W44_C', num_classes=num_classes, **params)
  637. class HRNet_W48_C(BaseClassifier):
  638. def __init__(self, num_classes=1000, **params):
  639. super(HRNet_W48_C, self).__init__(
  640. model_name='HRNet_W48_C', num_classes=num_classes, **params)
  641. class HRNet_W64_C(BaseClassifier):
  642. def __init__(self, num_classes=1000, **params):
  643. super(HRNet_W64_C, self).__init__(
  644. model_name='HRNet_W64_C', num_classes=num_classes, **params)
  645. class Xception41(BaseClassifier):
  646. def __init__(self, num_classes=1000, **params):
  647. super(Xception41, self).__init__(
  648. model_name='Xception41', num_classes=num_classes, **params)
  649. class Xception65(BaseClassifier):
  650. def __init__(self, num_classes=1000, **params):
  651. super(Xception65, self).__init__(
  652. model_name='Xception65', num_classes=num_classes, **params)
  653. class Xception71(BaseClassifier):
  654. def __init__(self, num_classes=1000, **params):
  655. super(Xception71, self).__init__(
  656. model_name='Xception71', num_classes=num_classes, **params)
  657. class ShuffleNetV2(BaseClassifier):
  658. def __init__(self, num_classes=1000, scale=1.0, **params):
  659. supported_scale = [.25, .33, .5, 1.0, 1.5, 2.0]
  660. if scale not in supported_scale:
  661. logging.warning("scale={} is not supported by ShuffleNetV2, "
  662. "scale is forcibly set to 1.0".format(scale))
  663. scale = 1.0
  664. model_name = 'ShuffleNetV2_x' + str(float(scale)).replace('.', '_')
  665. super(ShuffleNetV2, self).__init__(
  666. model_name=model_name, num_classes=num_classes, **params)
  667. def _get_test_inputs(self, image_shape):
  668. if image_shape is not None:
  669. if len(image_shape) == 2:
  670. image_shape = [None, 3] + image_shape
  671. else:
  672. image_shape = [None, 3, 224, 224]
  673. logging.warning(
  674. '[Important!!!] When exporting inference model for {},'.format(
  675. self.__class__.__name__) +
  676. ' if fixed_input_shape is not set, it will be forcibly set to [None, 3, 224, 224]'
  677. +
  678. 'Please check image shape after transforms is [3, 224, 224], if not, fixed_input_shape '
  679. + 'should be specified manually.')
  680. self._fix_transforms_shape(image_shape[-2:])
  681. self.fixed_input_shape = image_shape
  682. input_spec = [
  683. InputSpec(
  684. shape=image_shape, name='image', dtype='float32')
  685. ]
  686. return input_spec
  687. class ShuffleNetV2_swish(BaseClassifier):
  688. def __init__(self, num_classes=1000, **params):
  689. super(ShuffleNetV2_swish, self).__init__(
  690. model_name='ShuffleNetV2_x1_5', num_classes=num_classes, **params)
  691. def _get_test_inputs(self, image_shape):
  692. if image_shape is not None:
  693. if len(image_shape) == 2:
  694. image_shape = [None, 3] + image_shape
  695. else:
  696. image_shape = [None, 3, 224, 224]
  697. logging.warning(
  698. '[Important!!!] When exporting inference model for {},'.format(
  699. self.__class__.__name__) +
  700. ' if fixed_input_shape is not set, it will be forcibly set to [None, 3, 224, 224]'
  701. +
  702. 'Please check image shape after transforms is [3, 224, 224], if not, fixed_input_shape '
  703. + 'should be specified manually.')
  704. self._fix_transforms_shape(image_shape[-2:])
  705. self.fixed_input_shape = image_shape
  706. input_spec = [
  707. InputSpec(
  708. shape=image_shape, name='image', dtype='float32')
  709. ]
  710. return input_spec