classifier.py 34 KB

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