deeplabv3p.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. # coding: utf8
  2. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from __future__ import absolute_import
  16. from __future__ import division
  17. from __future__ import print_function
  18. from collections import OrderedDict
  19. import paddle.fluid as fluid
  20. from .model_utils.libs import scope, name_scope
  21. from .model_utils.libs import bn, bn_relu, relu
  22. from .model_utils.libs import conv, max_pool, deconv
  23. from .model_utils.libs import separate_conv
  24. from .model_utils.libs import sigmoid_to_softmax
  25. from .model_utils.loss import softmax_with_loss
  26. from .model_utils.loss import dice_loss
  27. from .model_utils.loss import bce_loss
  28. from paddlex.cv.nets.xception import Xception
  29. from paddlex.cv.nets.mobilenet_v2 import MobileNetV2
  30. class DeepLabv3p(object):
  31. """实现DeepLabv3+模型
  32. `"Encoder-Decoder with Atrous Separable Convolution for Semantic Image Segmentation"
  33. <https://arxiv.org/abs/1802.02611>`
  34. Args:
  35. num_classes (int): 类别数。
  36. backbone (paddlex.cv.nets): 神经网络,实现DeepLabv3+特征图的计算。
  37. mode (str): 网络运行模式,根据mode构建网络的输入和返回。
  38. 当mode为'train'时,输入为image(-1, 3, -1, -1)和label (-1, 1, -1, -1) 返回loss。
  39. 当mode为'train'时,输入为image (-1, 3, -1, -1)和label (-1, 1, -1, -1),返回loss,
  40. pred (与网络输入label 相同大小的预测结果,值代表相应的类别),label,mask(非忽略值的mask,
  41. 与label相同大小,bool类型)。
  42. 当mode为'test'时,输入为image(-1, 3, -1, -1)返回pred (-1, 1, -1, -1)和
  43. logit (-1, num_classes, -1, -1) 通道维上代表每一类的概率值。
  44. output_stride (int): backbone 输出特征图相对于输入的下采样倍数,一般取值为8或16。
  45. aspp_with_sep_conv (bool): 在asspp模块是否采用separable convolutions。
  46. decoder_use_sep_conv (bool): decoder模块是否采用separable convolutions。
  47. encoder_with_aspp (bool): 是否在encoder阶段采用aspp模块。
  48. enable_decoder (bool): 是否使用decoder模块。
  49. use_bce_loss (bool): 是否使用bce loss作为网络的损失函数,只能用于两类分割。可与dice loss同时使用。
  50. use_dice_loss (bool): 是否使用dice loss作为网络的损失函数,只能用于两类分割,可与bce loss同时使用。
  51. 当use_bce_loss和use_dice_loss都为False时,使用交叉熵损失函数。
  52. class_weight (list/str): 交叉熵损失函数各类损失的权重。当class_weight为list的时候,长度应为
  53. num_classes。当class_weight为str时, weight.lower()应为'dynamic',这时会根据每一轮各类像素的比重
  54. 自行计算相应的权重,每一类的权重为:每类的比例 * num_classes。class_weight取默认值None是,各类的权重1,
  55. 即平时使用的交叉熵损失函数。
  56. ignore_index (int): label上忽略的值,label为ignore_index的像素不参与损失函数的计算。
  57. fixed_input_shape (list): 长度为2,维度为1的list,如:[640,720],用来固定模型输入:'image'的shape,默认为None。
  58. Raises:
  59. ValueError: use_bce_loss或use_dice_loss为真且num_calsses > 2。
  60. ValueError: class_weight为list, 但长度不等于num_class。
  61. class_weight为str, 但class_weight.low()不等于dynamic。
  62. TypeError: class_weight不为None时,其类型不是list或str。
  63. """
  64. def __init__(self,
  65. num_classes,
  66. backbone,
  67. mode='train',
  68. output_stride=16,
  69. aspp_with_sep_conv=True,
  70. decoder_use_sep_conv=True,
  71. encoder_with_aspp=True,
  72. enable_decoder=True,
  73. use_bce_loss=False,
  74. use_dice_loss=False,
  75. class_weight=None,
  76. ignore_index=255,
  77. fixed_input_shape=None):
  78. # dice_loss或bce_loss只适用两类分割中
  79. if num_classes > 2 and (use_bce_loss or use_dice_loss):
  80. raise ValueError(
  81. "dice loss and bce loss is only applicable to binary classfication"
  82. )
  83. if class_weight is not None:
  84. if isinstance(class_weight, list):
  85. if len(class_weight) != num_classes:
  86. raise ValueError(
  87. "Length of class_weight should be equal to number of classes"
  88. )
  89. elif isinstance(class_weight, str):
  90. if class_weight.lower() != 'dynamic':
  91. raise ValueError(
  92. "if class_weight is string, must be dynamic!")
  93. else:
  94. raise TypeError(
  95. 'Expect class_weight is a list or string but receive {}'.
  96. format(type(class_weight)))
  97. self.num_classes = num_classes
  98. self.backbone = backbone
  99. self.mode = mode
  100. self.use_bce_loss = use_bce_loss
  101. self.use_dice_loss = use_dice_loss
  102. self.class_weight = class_weight
  103. self.ignore_index = ignore_index
  104. self.output_stride = output_stride
  105. self.aspp_with_sep_conv = aspp_with_sep_conv
  106. self.decoder_use_sep_conv = decoder_use_sep_conv
  107. self.encoder_with_aspp = encoder_with_aspp
  108. self.enable_decoder = enable_decoder
  109. self.fixed_input_shape = fixed_input_shape
  110. def _encoder(self, input):
  111. # 编码器配置,采用ASPP架构,pooling + 1x1_conv + 三个不同尺度的空洞卷积并行, concat后1x1conv
  112. # ASPP_WITH_SEP_CONV:默认为真,使用depthwise可分离卷积,否则使用普通卷积
  113. # OUTPUT_STRIDE: 下采样倍数,8或16,决定aspp_ratios大小
  114. # aspp_ratios:ASPP模块空洞卷积的采样率
  115. if self.output_stride == 16:
  116. aspp_ratios = [6, 12, 18]
  117. elif self.output_stride == 8:
  118. aspp_ratios = [12, 24, 36]
  119. else:
  120. raise Exception("DeepLabv3p only support stride 8 or 16")
  121. param_attr = fluid.ParamAttr(
  122. name=name_scope + 'weights',
  123. regularizer=None,
  124. initializer=fluid.initializer.TruncatedNormal(
  125. loc=0.0, scale=0.06))
  126. with scope('encoder'):
  127. channel = 256
  128. with scope("image_pool"):
  129. image_avg = fluid.layers.reduce_mean(
  130. input, [2, 3], keep_dim=True)
  131. image_avg = bn_relu(
  132. conv(
  133. image_avg,
  134. channel,
  135. 1,
  136. 1,
  137. groups=1,
  138. padding=0,
  139. param_attr=param_attr))
  140. input_shape = fluid.layers.shape(input)
  141. image_avg = fluid.layers.resize_bilinear(image_avg,
  142. input_shape[2:])
  143. with scope("aspp0"):
  144. aspp0 = bn_relu(
  145. conv(
  146. input,
  147. channel,
  148. 1,
  149. 1,
  150. groups=1,
  151. padding=0,
  152. param_attr=param_attr))
  153. with scope("aspp1"):
  154. if self.aspp_with_sep_conv:
  155. aspp1 = separate_conv(
  156. input,
  157. channel,
  158. 1,
  159. 3,
  160. dilation=aspp_ratios[0],
  161. act=relu)
  162. else:
  163. aspp1 = bn_relu(
  164. conv(
  165. input,
  166. channel,
  167. stride=1,
  168. filter_size=3,
  169. dilation=aspp_ratios[0],
  170. padding=aspp_ratios[0],
  171. param_attr=param_attr))
  172. with scope("aspp2"):
  173. if self.aspp_with_sep_conv:
  174. aspp2 = separate_conv(
  175. input,
  176. channel,
  177. 1,
  178. 3,
  179. dilation=aspp_ratios[1],
  180. act=relu)
  181. else:
  182. aspp2 = bn_relu(
  183. conv(
  184. input,
  185. channel,
  186. stride=1,
  187. filter_size=3,
  188. dilation=aspp_ratios[1],
  189. padding=aspp_ratios[1],
  190. param_attr=param_attr))
  191. with scope("aspp3"):
  192. if self.aspp_with_sep_conv:
  193. aspp3 = separate_conv(
  194. input,
  195. channel,
  196. 1,
  197. 3,
  198. dilation=aspp_ratios[2],
  199. act=relu)
  200. else:
  201. aspp3 = bn_relu(
  202. conv(
  203. input,
  204. channel,
  205. stride=1,
  206. filter_size=3,
  207. dilation=aspp_ratios[2],
  208. padding=aspp_ratios[2],
  209. param_attr=param_attr))
  210. with scope("concat"):
  211. data = fluid.layers.concat(
  212. [image_avg, aspp0, aspp1, aspp2, aspp3], axis=1)
  213. data = bn_relu(
  214. conv(
  215. data,
  216. channel,
  217. 1,
  218. 1,
  219. groups=1,
  220. padding=0,
  221. param_attr=param_attr))
  222. data = fluid.layers.dropout(data, 0.9)
  223. return data
  224. def _decoder(self, encode_data, decode_shortcut):
  225. # 解码器配置
  226. # encode_data:编码器输出
  227. # decode_shortcut: 从backbone引出的分支, resize后与encode_data concat
  228. # decoder_use_sep_conv: 默认为真,则concat后连接两个可分离卷积,否则为普通卷积
  229. param_attr = fluid.ParamAttr(
  230. name=name_scope + 'weights',
  231. regularizer=None,
  232. initializer=fluid.initializer.TruncatedNormal(
  233. loc=0.0, scale=0.06))
  234. with scope('decoder'):
  235. with scope('concat'):
  236. decode_shortcut = bn_relu(
  237. conv(
  238. decode_shortcut,
  239. 48,
  240. 1,
  241. 1,
  242. groups=1,
  243. padding=0,
  244. param_attr=param_attr))
  245. decode_shortcut_shape = fluid.layers.shape(decode_shortcut)
  246. encode_data = fluid.layers.resize_bilinear(
  247. encode_data, decode_shortcut_shape[2:])
  248. encode_data = fluid.layers.concat(
  249. [encode_data, decode_shortcut], axis=1)
  250. if self.decoder_use_sep_conv:
  251. with scope("separable_conv1"):
  252. encode_data = separate_conv(
  253. encode_data, 256, 1, 3, dilation=1, act=relu)
  254. with scope("separable_conv2"):
  255. encode_data = separate_conv(
  256. encode_data, 256, 1, 3, dilation=1, act=relu)
  257. else:
  258. with scope("decoder_conv1"):
  259. encode_data = bn_relu(
  260. conv(
  261. encode_data,
  262. 256,
  263. stride=1,
  264. filter_size=3,
  265. dilation=1,
  266. padding=1,
  267. param_attr=param_attr))
  268. with scope("decoder_conv2"):
  269. encode_data = bn_relu(
  270. conv(
  271. encode_data,
  272. 256,
  273. stride=1,
  274. filter_size=3,
  275. dilation=1,
  276. padding=1,
  277. param_attr=param_attr))
  278. return encode_data
  279. def _get_loss(self, logit, label, mask):
  280. avg_loss = 0
  281. if not (self.use_dice_loss or self.use_bce_loss):
  282. avg_loss += softmax_with_loss(
  283. logit,
  284. label,
  285. mask,
  286. num_classes=self.num_classes,
  287. weight=self.class_weight,
  288. ignore_index=self.ignore_index)
  289. else:
  290. if self.use_dice_loss:
  291. avg_loss += dice_loss(logit, label, mask)
  292. if self.use_bce_loss:
  293. avg_loss += bce_loss(
  294. logit, label, mask, ignore_index=self.ignore_index)
  295. return avg_loss
  296. def generate_inputs(self):
  297. inputs = OrderedDict()
  298. if self.fixed_input_shape is not None:
  299. input_shape = [
  300. None, 3, self.fixed_input_shape[1], self.fixed_input_shape[0]
  301. ]
  302. inputs['image'] = fluid.data(
  303. dtype='float32', shape=input_shape, name='image')
  304. else:
  305. inputs['image'] = fluid.data(
  306. dtype='float32', shape=[None, 3, None, None], name='image')
  307. if self.mode == 'train':
  308. inputs['label'] = fluid.data(
  309. dtype='int32', shape=[None, 1, None, None], name='label')
  310. return inputs
  311. def build_net(self, inputs):
  312. # 在两类分割情况下,当loss函数选择dice_loss或bce_loss的时候,最后logit输出通道数设置为1
  313. if self.use_dice_loss or self.use_bce_loss:
  314. self.num_classes = 1
  315. image = inputs['image']
  316. data, decode_shortcuts = self.backbone(image)
  317. decode_shortcut = decode_shortcuts[self.backbone.decode_points]
  318. # 编码器解码器设置
  319. if self.encoder_with_aspp:
  320. data = self._encoder(data)
  321. if self.enable_decoder:
  322. data = self._decoder(data, decode_shortcut)
  323. # 根据类别数设置最后一个卷积层输出,并resize到图片原始尺寸
  324. param_attr = fluid.ParamAttr(
  325. name=name_scope + 'weights',
  326. regularizer=fluid.regularizer.L2DecayRegularizer(
  327. regularization_coeff=0.0),
  328. initializer=fluid.initializer.TruncatedNormal(
  329. loc=0.0, scale=0.01))
  330. with scope('logit'):
  331. with fluid.name_scope('last_conv'):
  332. logit = conv(
  333. data,
  334. self.num_classes,
  335. 1,
  336. stride=1,
  337. padding=0,
  338. bias_attr=True,
  339. param_attr=param_attr)
  340. image_shape = fluid.layers.shape(image)
  341. logit = fluid.layers.resize_bilinear(logit, image_shape[2:])
  342. if self.num_classes == 1:
  343. out = sigmoid_to_softmax(logit)
  344. out = fluid.layers.transpose(out, [0, 2, 3, 1])
  345. else:
  346. out = fluid.layers.transpose(logit, [0, 2, 3, 1])
  347. pred = fluid.layers.argmax(out, axis=3)
  348. pred = fluid.layers.unsqueeze(pred, axes=[3])
  349. if self.mode == 'train':
  350. label = inputs['label']
  351. mask = label != self.ignore_index
  352. return self._get_loss(logit, label, mask)
  353. elif self.mode == 'eval':
  354. label = inputs['label']
  355. mask = label != self.ignore_index
  356. loss = self._get_loss(logit, label, mask)
  357. return loss, pred, label, mask
  358. else:
  359. if self.num_classes == 1:
  360. logit = sigmoid_to_softmax(logit)
  361. else:
  362. logit = fluid.layers.softmax(logit, axis=1)
  363. return pred, logit
  364. return logit