classifier.py 33 KB

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