deeplabv3p.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  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 os.path as osp
  16. import numpy as np
  17. import tqdm
  18. import math
  19. import cv2
  20. from multiprocessing.pool import ThreadPool
  21. import paddle.fluid as fluid
  22. import paddlex.utils.logging as logging
  23. import paddlex
  24. from paddlex.cv.transforms import arrange_transforms
  25. from paddlex.cv.datasets import generate_minibatch
  26. from collections import OrderedDict
  27. from .base import BaseAPI
  28. from .utils.seg_eval import ConfusionMatrix
  29. from .utils.visualize import visualize_segmentation
  30. class DeepLabv3p(BaseAPI):
  31. """实现DeepLabv3+网络的构建并进行训练、评估、预测和模型导出。
  32. Args:
  33. num_classes (int): 类别数。
  34. backbone (str): DeepLabv3+的backbone网络,实现特征图的计算,取值范围为['Xception65', 'Xception41',
  35. 'MobileNetV2_x0.25', 'MobileNetV2_x0.5', 'MobileNetV2_x1.0', 'MobileNetV2_x1.5',
  36. 'MobileNetV2_x2.0']。默认'MobileNetV2_x1.0'。
  37. output_stride (int): backbone 输出特征图相对于输入的下采样倍数,一般取值为8或16。默认16。
  38. aspp_with_sep_conv (bool): 在asspp模块是否采用separable convolutions。默认True。
  39. decoder_use_sep_conv (bool): decoder模块是否采用separable convolutions。默认True。
  40. encoder_with_aspp (bool): 是否在encoder阶段采用aspp模块。默认True。
  41. enable_decoder (bool): 是否使用decoder模块。默认True。
  42. use_bce_loss (bool): 是否使用bce loss作为网络的损失函数,只能用于两类分割。可与dice loss同时使用。默认False。
  43. use_dice_loss (bool): 是否使用dice loss作为网络的损失函数,只能用于两类分割,可与bce loss同时使用,
  44. 当use_bce_loss和use_dice_loss都为False时,使用交叉熵损失函数。默认False。
  45. class_weight (list/str): 交叉熵损失函数各类损失的权重。当class_weight为list的时候,长度应为
  46. num_classes。当class_weight为str时, weight.lower()应为'dynamic',这时会根据每一轮各类像素的比重
  47. 自行计算相应的权重,每一类的权重为:每类的比例 * num_classes。class_weight取默认值None时,各类的权重1,
  48. 即平时使用的交叉熵损失函数。
  49. ignore_index (int): label上忽略的值,label为ignore_index的像素不参与损失函数的计算。默认255。
  50. Raises:
  51. ValueError: use_bce_loss或use_dice_loss为真且num_calsses > 2。
  52. ValueError: backbone取值不在['Xception65', 'Xception41', 'MobileNetV2_x0.25',
  53. 'MobileNetV2_x0.5', 'MobileNetV2_x1.0', 'MobileNetV2_x1.5', 'MobileNetV2_x2.0']之内。
  54. ValueError: class_weight为list, 但长度不等于num_class。
  55. class_weight为str, 但class_weight.low()不等于dynamic。
  56. TypeError: class_weight不为None时,其类型不是list或str。
  57. """
  58. def __init__(self,
  59. num_classes=2,
  60. backbone='MobileNetV2_x1.0',
  61. output_stride=16,
  62. aspp_with_sep_conv=True,
  63. decoder_use_sep_conv=True,
  64. encoder_with_aspp=True,
  65. enable_decoder=True,
  66. use_bce_loss=False,
  67. use_dice_loss=False,
  68. class_weight=None,
  69. ignore_index=255):
  70. self.init_params = locals()
  71. super(DeepLabv3p, self).__init__('segmenter')
  72. # dice_loss或bce_loss只适用两类分割中
  73. if num_classes > 2 and (use_bce_loss or use_dice_loss):
  74. raise ValueError(
  75. "dice loss and bce loss is only applicable to binary classfication"
  76. )
  77. self.output_stride = output_stride
  78. if backbone not in [
  79. 'Xception65', 'Xception41', 'MobileNetV2_x0.25',
  80. 'MobileNetV2_x0.5', 'MobileNetV2_x1.0', 'MobileNetV2_x1.5',
  81. 'MobileNetV2_x2.0'
  82. ]:
  83. raise ValueError(
  84. "backbone: {} is set wrong. it should be one of "
  85. "('Xception65', 'Xception41', 'MobileNetV2_x0.25', 'MobileNetV2_x0.5',"
  86. " 'MobileNetV2_x1.0', 'MobileNetV2_x1.5', 'MobileNetV2_x2.0')".
  87. format(backbone))
  88. if class_weight is not None:
  89. if isinstance(class_weight, list):
  90. if len(class_weight) != num_classes:
  91. raise ValueError(
  92. "Length of class_weight should be equal to number of classes"
  93. )
  94. elif isinstance(class_weight, str):
  95. if class_weight.lower() != 'dynamic':
  96. raise ValueError(
  97. "if class_weight is string, must be dynamic!")
  98. else:
  99. raise TypeError(
  100. 'Expect class_weight is a list or string but receive {}'.
  101. format(type(class_weight)))
  102. self.backbone = backbone
  103. self.num_classes = num_classes
  104. self.use_bce_loss = use_bce_loss
  105. self.use_dice_loss = use_dice_loss
  106. self.class_weight = class_weight
  107. self.ignore_index = ignore_index
  108. self.aspp_with_sep_conv = aspp_with_sep_conv
  109. self.decoder_use_sep_conv = decoder_use_sep_conv
  110. self.encoder_with_aspp = encoder_with_aspp
  111. self.enable_decoder = enable_decoder
  112. self.labels = None
  113. self.sync_bn = True
  114. self.fixed_input_shape = None
  115. def _get_backbone(self, backbone):
  116. def mobilenetv2(backbone):
  117. # backbone: xception结构配置
  118. # output_stride:下采样倍数
  119. # end_points: mobilenetv2的block数
  120. # decode_point: 从mobilenetv2中引出分支所在block数, 作为decoder输入
  121. if '0.25' in backbone:
  122. scale = 0.25
  123. elif '0.5' in backbone:
  124. scale = 0.5
  125. elif '1.0' in backbone:
  126. scale = 1.0
  127. elif '1.5' in backbone:
  128. scale = 1.5
  129. elif '2.0' in backbone:
  130. scale = 2.0
  131. end_points = 18
  132. decode_points = 4
  133. return paddlex.cv.nets.MobileNetV2(
  134. scale=scale,
  135. output_stride=self.output_stride,
  136. end_points=end_points,
  137. decode_points=decode_points)
  138. def xception(backbone):
  139. # decode_point: 从Xception中引出分支所在block数,作为decoder输入
  140. # end_point:Xception的block数
  141. if '65' in backbone:
  142. decode_points = 2
  143. end_points = 21
  144. layers = 65
  145. if '41' in backbone:
  146. decode_points = 2
  147. end_points = 13
  148. layers = 41
  149. if '71' in backbone:
  150. decode_points = 3
  151. end_points = 23
  152. layers = 71
  153. return paddlex.cv.nets.Xception(
  154. layers=layers,
  155. output_stride=self.output_stride,
  156. end_points=end_points,
  157. decode_points=decode_points)
  158. if 'Xception' in backbone:
  159. return xception(backbone)
  160. elif 'MobileNetV2' in backbone:
  161. return mobilenetv2(backbone)
  162. def build_net(self, mode='train'):
  163. model = paddlex.cv.nets.segmentation.DeepLabv3p(
  164. self.num_classes,
  165. mode=mode,
  166. backbone=self._get_backbone(self.backbone),
  167. output_stride=self.output_stride,
  168. aspp_with_sep_conv=self.aspp_with_sep_conv,
  169. decoder_use_sep_conv=self.decoder_use_sep_conv,
  170. encoder_with_aspp=self.encoder_with_aspp,
  171. enable_decoder=self.enable_decoder,
  172. use_bce_loss=self.use_bce_loss,
  173. use_dice_loss=self.use_dice_loss,
  174. class_weight=self.class_weight,
  175. ignore_index=self.ignore_index,
  176. fixed_input_shape=self.fixed_input_shape)
  177. inputs = model.generate_inputs()
  178. model_out = model.build_net(inputs)
  179. outputs = OrderedDict()
  180. if mode == 'train':
  181. self.optimizer.minimize(model_out)
  182. outputs['loss'] = model_out
  183. else:
  184. outputs['pred'] = model_out[0]
  185. outputs['logit'] = model_out[1]
  186. return inputs, outputs
  187. def default_optimizer(self,
  188. learning_rate,
  189. num_epochs,
  190. num_steps_each_epoch,
  191. lr_decay_power=0.9):
  192. decay_step = num_epochs * num_steps_each_epoch
  193. lr_decay = fluid.layers.polynomial_decay(
  194. learning_rate,
  195. decay_step,
  196. end_learning_rate=0,
  197. power=lr_decay_power)
  198. optimizer = fluid.optimizer.Momentum(
  199. lr_decay,
  200. momentum=0.9,
  201. regularization=fluid.regularizer.L2Decay(
  202. regularization_coeff=4e-05))
  203. return optimizer
  204. def train(self,
  205. num_epochs,
  206. train_dataset,
  207. train_batch_size=2,
  208. eval_dataset=None,
  209. save_interval_epochs=1,
  210. log_interval_steps=2,
  211. save_dir='output',
  212. pretrain_weights='IMAGENET',
  213. optimizer=None,
  214. learning_rate=0.01,
  215. lr_decay_power=0.9,
  216. use_vdl=False,
  217. sensitivities_file=None,
  218. eval_metric_loss=0.05,
  219. early_stop=False,
  220. early_stop_patience=5,
  221. resume_checkpoint=None):
  222. """训练。
  223. Args:
  224. num_epochs (int): 训练迭代轮数。
  225. train_dataset (paddlex.datasets): 训练数据读取器。
  226. train_batch_size (int): 训练数据batch大小。同时作为验证数据batch大小。默认为2。
  227. eval_dataset (paddlex.datasets): 评估数据读取器。
  228. save_interval_epochs (int): 模型保存间隔(单位:迭代轮数)。默认为1。
  229. log_interval_steps (int): 训练日志输出间隔(单位:迭代次数)。默认为2。
  230. save_dir (str): 模型保存路径。默认'output'。
  231. pretrain_weights (str): 若指定为路径时,则加载路径下预训练模型;若为字符串'IMAGENET',
  232. 则自动下载在ImageNet图片数据上预训练的模型权重;若为字符串'COCO',
  233. 则自动下载在COCO数据集上预训练的模型权重;若为字符串'CITYSCAPES',
  234. 则自动下载在CITYSCAPES数据集上预训练的模型权重;若为None,则不使用预训练模型。默认'IMAGENET。
  235. optimizer (paddle.fluid.optimizer): 优化器。当该参数为None时,使用默认的优化器:使用
  236. fluid.optimizer.Momentum优化方法,polynomial的学习率衰减策略。
  237. learning_rate (float): 默认优化器的初始学习率。默认0.01。
  238. lr_decay_power (float): 默认优化器学习率衰减指数。默认0.9。
  239. use_vdl (bool): 是否使用VisualDL进行可视化。默认False。
  240. sensitivities_file (str): 若指定为路径时,则加载路径下敏感度信息进行裁剪;若为字符串'DEFAULT',
  241. 则自动下载在Cityscapes图片数据上获得的敏感度信息进行裁剪;若为None,则不进行裁剪。默认为None。
  242. eval_metric_loss (float): 可容忍的精度损失。默认为0.05。
  243. early_stop (bool): 是否使用提前终止训练策略。默认值为False。
  244. early_stop_patience (int): 当使用提前终止训练策略时,如果验证集精度在`early_stop_patience`个epoch内
  245. 连续下降或持平,则终止训练。默认值为5。
  246. resume_checkpoint (str): 恢复训练时指定上次训练保存的模型路径。若为None,则不会恢复训练。默认值为None。
  247. Raises:
  248. ValueError: 模型从inference model进行加载。
  249. """
  250. if not self.trainable:
  251. raise ValueError("Model is not trainable from load_model method.")
  252. self.labels = train_dataset.labels
  253. if optimizer is None:
  254. num_steps_each_epoch = train_dataset.num_samples // train_batch_size
  255. optimizer = self.default_optimizer(
  256. learning_rate=learning_rate,
  257. num_epochs=num_epochs,
  258. num_steps_each_epoch=num_steps_each_epoch,
  259. lr_decay_power=lr_decay_power)
  260. self.optimizer = optimizer
  261. # 构建训练、验证、预测网络
  262. self.build_program()
  263. # 初始化网络权重
  264. self.net_initialize(
  265. startup_prog=fluid.default_startup_program(),
  266. pretrain_weights=pretrain_weights,
  267. save_dir=save_dir,
  268. sensitivities_file=sensitivities_file,
  269. eval_metric_loss=eval_metric_loss,
  270. resume_checkpoint=resume_checkpoint)
  271. # 训练
  272. self.train_loop(
  273. num_epochs=num_epochs,
  274. train_dataset=train_dataset,
  275. train_batch_size=train_batch_size,
  276. eval_dataset=eval_dataset,
  277. save_interval_epochs=save_interval_epochs,
  278. log_interval_steps=log_interval_steps,
  279. save_dir=save_dir,
  280. use_vdl=use_vdl,
  281. early_stop=early_stop,
  282. early_stop_patience=early_stop_patience)
  283. def evaluate(self,
  284. eval_dataset,
  285. batch_size=1,
  286. epoch_id=None,
  287. return_details=False):
  288. """评估。
  289. Args:
  290. eval_dataset (paddlex.datasets): 评估数据读取器。
  291. batch_size (int): 评估时的batch大小。默认1。
  292. epoch_id (int): 当前评估模型所在的训练轮数。
  293. return_details (bool): 是否返回详细信息。默认False。
  294. Returns:
  295. dict: 当return_details为False时,返回dict。包含关键字:'miou'、'category_iou'、'macc'、
  296. 'category_acc'和'kappa',分别表示平均iou、各类别iou、平均准确率、各类别准确率和kappa系数。
  297. tuple (metrics, eval_details):当return_details为True时,增加返回dict (eval_details),
  298. 包含关键字:'confusion_matrix',表示评估的混淆矩阵。
  299. """
  300. arrange_transforms(
  301. model_type=self.model_type,
  302. class_name=self.__class__.__name__,
  303. transforms=eval_dataset.transforms,
  304. mode='eval')
  305. total_steps = math.ceil(eval_dataset.num_samples * 1.0 / batch_size)
  306. conf_mat = ConfusionMatrix(self.num_classes, streaming=True)
  307. data_generator = eval_dataset.generator(
  308. batch_size=batch_size, drop_last=False)
  309. if not hasattr(self, 'parallel_test_prog'):
  310. with fluid.scope_guard(self.scope):
  311. self.parallel_test_prog = fluid.CompiledProgram(
  312. self.test_prog).with_data_parallel(
  313. share_vars_from=self.parallel_train_prog)
  314. logging.info(
  315. "Start to evaluating(total_samples={}, total_steps={})...".format(
  316. eval_dataset.num_samples, total_steps))
  317. for step, data in tqdm.tqdm(
  318. enumerate(data_generator()), total=total_steps):
  319. images = np.array([d[0] for d in data])
  320. labels = np.array([d[1] for d in data])
  321. num_samples = images.shape[0]
  322. if num_samples < batch_size:
  323. num_pad_samples = batch_size - num_samples
  324. pad_images = np.tile(images[0:1], (num_pad_samples, 1, 1, 1))
  325. images = np.concatenate([images, pad_images])
  326. feed_data = {'image': images}
  327. with fluid.scope_guard(self.scope):
  328. outputs = self.exe.run(
  329. self.parallel_test_prog,
  330. feed=feed_data,
  331. fetch_list=list(self.test_outputs.values()),
  332. return_numpy=True)
  333. pred = outputs[0]
  334. if num_samples < batch_size:
  335. pred = pred[0:num_samples]
  336. mask = labels != self.ignore_index
  337. conf_mat.calculate(pred=pred, label=labels, ignore=mask)
  338. _, iou = conf_mat.mean_iou()
  339. logging.debug("[EVAL] Epoch={}, Step={}/{}, iou={}".format(
  340. epoch_id, step + 1, total_steps, iou))
  341. category_iou, miou = conf_mat.mean_iou()
  342. category_acc, macc = conf_mat.accuracy()
  343. metrics = OrderedDict(
  344. zip(['miou', 'category_iou', 'macc', 'category_acc', 'kappa'],
  345. [miou, category_iou, macc, category_acc, conf_mat.kappa()]))
  346. if return_details:
  347. eval_details = {
  348. 'confusion_matrix': conf_mat.confusion_matrix.tolist()
  349. }
  350. return metrics, eval_details
  351. return metrics
  352. @staticmethod
  353. def _preprocess(images, transforms, model_type, class_name, thread_num=1):
  354. arrange_transforms(
  355. model_type=model_type,
  356. class_name=class_name,
  357. transforms=transforms,
  358. mode='test')
  359. pool = ThreadPool(thread_num)
  360. batch_data = pool.map(transforms, images)
  361. pool.close()
  362. pool.join()
  363. padding_batch = generate_minibatch(batch_data)
  364. im = np.array(
  365. [data[0] for data in padding_batch],
  366. dtype=padding_batch[0][0].dtype)
  367. im_info = [data[1] for data in padding_batch]
  368. return im, im_info
  369. @staticmethod
  370. def _postprocess(results, im_info):
  371. pred_list = list()
  372. logit_list = list()
  373. for i, (pred, logit) in enumerate(zip(results[0], results[1])):
  374. pred = pred.astype('uint8')
  375. pred = np.squeeze(pred).astype('uint8')
  376. logit = np.transpose(logit, (1, 2, 0))
  377. for info in im_info[i][::-1]:
  378. if info[0] == 'resize':
  379. w, h = info[1][1], info[1][0]
  380. pred = cv2.resize(pred, (w, h), cv2.INTER_NEAREST)
  381. logit = cv2.resize(logit, (w, h), cv2.INTER_LINEAR)
  382. elif info[0] == 'padding':
  383. w, h = info[1][1], info[1][0]
  384. pred = pred[0:h, 0:w]
  385. logit = logit[0:h, 0:w, :]
  386. else:
  387. raise Exception("Unexpected info '{}' in im_info".format(
  388. info[0]))
  389. pred_list.append(pred)
  390. logit_list.append(logit)
  391. preds = list()
  392. for pred, logit in zip(pred_list, logit_list):
  393. preds.append({'label_map': pred, 'score_map': logit})
  394. return preds
  395. def predict(self, img_file, transforms=None):
  396. """预测。
  397. Args:
  398. img_file(str|np.ndarray): 预测图像路径,或者是解码后的排列格式为(H, W, C)且类型为float32且为BGR格式的数组。
  399. transforms(paddlex.cv.transforms): 数据预处理操作。
  400. Returns:
  401. dict: 包含关键字'label_map'和'score_map', 'label_map'存储预测结果灰度图,
  402. 像素值表示对应的类别,'score_map'存储各类别的概率,shape=(h, w, num_classes)
  403. """
  404. if transforms is None and not hasattr(self, 'test_transforms'):
  405. raise Exception("transforms need to be defined, now is None.")
  406. if isinstance(img_file, (str, np.ndarray)):
  407. images = [img_file]
  408. else:
  409. raise Exception("img_file must be str/np.ndarray")
  410. if transforms is None:
  411. transforms = self.test_transforms
  412. im, im_info = DeepLabv3p._preprocess(
  413. images, transforms, self.model_type, self.__class__.__name__)
  414. with fluid.scope_guard(self.scope):
  415. result = self.exe.run(self.test_prog,
  416. feed={'image': im},
  417. fetch_list=list(self.test_outputs.values()),
  418. use_program_cache=True)
  419. preds = DeepLabv3p._postprocess(result, im_info)
  420. return preds[0]
  421. def batch_predict(self, img_file_list, transforms=None, thread_num=2):
  422. """预测。
  423. Args:
  424. img_file_list(list|tuple): 对列表(或元组)中的图像同时进行预测,列表中的元素可以是图像路径
  425. 也可以是解码后的排列格式为(H,W,C)且类型为float32且为BGR格式的数组。
  426. transforms(paddlex.cv.transforms): 数据预处理操作。
  427. Returns:
  428. list: 每个元素都为列表,表示各图像的预测结果。各图像的预测结果用字典表示,包含关键字'label_map'和'score_map', 'label_map'存储预测结果灰度图,
  429. 像素值表示对应的类别,'score_map'存储各类别的概率,shape=(h, w, num_classes)
  430. """
  431. if transforms is None and not hasattr(self, 'test_transforms'):
  432. raise Exception("transforms need to be defined, now is None.")
  433. if not isinstance(img_file_list, (list, tuple)):
  434. raise Exception("im_file must be list/tuple")
  435. if transforms is None:
  436. transforms = self.test_transforms
  437. im, im_info = DeepLabv3p._preprocess(
  438. img_file_list, transforms, self.model_type,
  439. self.__class__.__name__, thread_num)
  440. with fluid.scope_guard(self.scope):
  441. result = self.exe.run(self.test_prog,
  442. feed={'image': im},
  443. fetch_list=list(self.test_outputs.values()),
  444. use_program_cache=True)
  445. preds = DeepLabv3p._postprocess(result, im_info)
  446. return preds