classifier.py 26 KB

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