classifier.py 34 KB

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