deeplabv3p.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. import paddlex.utils.logging as logging
  29. from paddlex.cv.nets.xception import Xception
  30. from paddlex.cv.nets.mobilenet_v2 import MobileNetV2
  31. class DeepLabv3p(object):
  32. """实现DeepLabv3+模型
  33. `"Encoder-Decoder with Atrous Separable Convolution for Semantic Image Segmentation"
  34. <https://arxiv.org/abs/1802.02611>`
  35. Args:
  36. num_classes (int): 类别数。
  37. backbone (paddlex.cv.nets): 神经网络,实现DeepLabv3+特征图的计算。
  38. mode (str): 网络运行模式,根据mode构建网络的输入和返回。
  39. 当mode为'train'时,输入为image(-1, 3, -1, -1)和label (-1, 1, -1, -1) 返回loss。
  40. 当mode为'train'时,输入为image (-1, 3, -1, -1)和label (-1, 1, -1, -1),返回loss,
  41. pred (与网络输入label 相同大小的预测结果,值代表相应的类别),label,mask(非忽略值的mask,
  42. 与label相同大小,bool类型)。
  43. 当mode为'test'时,输入为image(-1, 3, -1, -1)返回pred (-1, 1, -1, -1)和
  44. logit (-1, num_classes, -1, -1) 通道维上代表每一类的概率值。
  45. output_stride (int): backbone 输出特征图相对于输入的下采样倍数,一般取值为8或16。
  46. aspp_with_sep_conv (bool): 在asspp模块是否采用separable convolutions。
  47. decoder_use_sep_conv (bool): decoder模块是否采用separable convolutions。
  48. encoder_with_aspp (bool): 是否在encoder阶段采用aspp模块。
  49. enable_decoder (bool): 是否使用decoder模块。
  50. use_bce_loss (bool): 是否使用bce loss作为网络的损失函数,只能用于两类分割。可与dice loss同时使用。
  51. use_dice_loss (bool): 是否使用dice loss作为网络的损失函数,只能用于两类分割,可与bce loss同时使用。
  52. 当use_bce_loss和use_dice_loss都为False时,使用交叉熵损失函数。
  53. class_weight (list/str): 交叉熵损失函数各类损失的权重。当class_weight为list的时候,长度应为
  54. num_classes。当class_weight为str时, weight.lower()应为'dynamic',这时会根据每一轮各类像素的比重
  55. 自行计算相应的权重,每一类的权重为:每类的比例 * num_classes。class_weight取默认值None是,各类的权重1,
  56. 即平时使用的交叉熵损失函数。
  57. ignore_index (int): label上忽略的值,label为ignore_index的像素不参与损失函数的计算。
  58. fixed_input_shape (list): 长度为2,维度为1的list,如:[640,720],用来固定模型输入:'image'的shape,默认为None。
  59. Raises:
  60. ValueError: use_bce_loss或use_dice_loss为真且num_calsses > 2。
  61. ValueError: class_weight为list, 但长度不等于num_class。
  62. class_weight为str, 但class_weight.low()不等于dynamic。
  63. TypeError: class_weight不为None时,其类型不是list或str。
  64. """
  65. def __init__(self,
  66. num_classes,
  67. backbone,
  68. mode='train',
  69. output_stride=16,
  70. aspp_with_sep_conv=True,
  71. decoder_use_sep_conv=True,
  72. encoder_with_aspp=True,
  73. enable_decoder=True,
  74. use_bce_loss=False,
  75. use_dice_loss=False,
  76. class_weight=None,
  77. ignore_index=255,
  78. fixed_input_shape=None):
  79. # dice_loss或bce_loss只适用两类分割中
  80. if num_classes > 2 and (use_bce_loss or use_dice_loss):
  81. raise ValueError(
  82. "dice loss and bce loss is only applicable to binary classfication"
  83. )
  84. if class_weight is not None:
  85. if isinstance(class_weight, list):
  86. if len(class_weight) != num_classes:
  87. raise ValueError(
  88. "Length of class_weight should be equal to number of classes"
  89. )
  90. elif isinstance(class_weight, str):
  91. if class_weight.lower() != 'dynamic':
  92. raise ValueError(
  93. "if class_weight is string, must be dynamic!")
  94. else:
  95. raise TypeError(
  96. 'Expect class_weight is a list or string but receive {}'.
  97. format(type(class_weight)))
  98. self.num_classes = num_classes
  99. self.backbone = backbone
  100. self.mode = mode
  101. self.use_bce_loss = use_bce_loss
  102. self.use_dice_loss = use_dice_loss
  103. self.class_weight = class_weight
  104. self.ignore_index = ignore_index
  105. self.output_stride = output_stride
  106. self.aspp_with_sep_conv = aspp_with_sep_conv
  107. self.decoder_use_sep_conv = decoder_use_sep_conv
  108. self.encoder_with_aspp = encoder_with_aspp
  109. self.enable_decoder = enable_decoder
  110. self.fixed_input_shape = fixed_input_shape
  111. def _encoder(self, input):
  112. # 编码器配置,采用ASPP架构,pooling + 1x1_conv + 三个不同尺度的空洞卷积并行, concat后1x1conv
  113. # ASPP_WITH_SEP_CONV:默认为真,使用depthwise可分离卷积,否则使用普通卷积
  114. # OUTPUT_STRIDE: 下采样倍数,8或16,决定aspp_ratios大小
  115. # aspp_ratios:ASPP模块空洞卷积的采样率
  116. if self.output_stride == 16:
  117. aspp_ratios = [6, 12, 18]
  118. elif self.output_stride == 8:
  119. aspp_ratios = [12, 24, 36]
  120. else:
  121. raise Exception("DeepLabv3p only support stride 8 or 16")
  122. param_attr = fluid.ParamAttr(
  123. name=name_scope + 'weights',
  124. regularizer=None,
  125. initializer=fluid.initializer.TruncatedNormal(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(
  142. image_avg, 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(loc=0.0, scale=0.06))
  233. with scope('decoder'):
  234. with scope('concat'):
  235. decode_shortcut = bn_relu(
  236. conv(
  237. decode_shortcut,
  238. 48,
  239. 1,
  240. 1,
  241. groups=1,
  242. padding=0,
  243. param_attr=param_attr))
  244. decode_shortcut_shape = fluid.layers.shape(decode_shortcut)
  245. encode_data = fluid.layers.resize_bilinear(
  246. encode_data, decode_shortcut_shape[2:])
  247. encode_data = fluid.layers.concat(
  248. [encode_data, decode_shortcut], axis=1)
  249. if self.decoder_use_sep_conv:
  250. with scope("separable_conv1"):
  251. encode_data = separate_conv(
  252. encode_data, 256, 1, 3, dilation=1, act=relu)
  253. with scope("separable_conv2"):
  254. encode_data = separate_conv(
  255. encode_data, 256, 1, 3, dilation=1, act=relu)
  256. else:
  257. with scope("decoder_conv1"):
  258. encode_data = bn_relu(
  259. conv(
  260. encode_data,
  261. 256,
  262. stride=1,
  263. filter_size=3,
  264. dilation=1,
  265. padding=1,
  266. param_attr=param_attr))
  267. with scope("decoder_conv2"):
  268. encode_data = bn_relu(
  269. conv(
  270. encode_data,
  271. 256,
  272. stride=1,
  273. filter_size=3,
  274. dilation=1,
  275. padding=1,
  276. param_attr=param_attr))
  277. return encode_data
  278. def _get_loss(self, logit, label, mask):
  279. avg_loss = 0
  280. if not (self.use_dice_loss or self.use_bce_loss):
  281. avg_loss += softmax_with_loss(
  282. logit,
  283. label,
  284. mask,
  285. num_classes=self.num_classes,
  286. weight=self.class_weight,
  287. ignore_index=self.ignore_index)
  288. else:
  289. if self.use_dice_loss:
  290. avg_loss += dice_loss(logit, label, mask)
  291. if self.use_bce_loss:
  292. avg_loss += bce_loss(
  293. logit, label, mask, ignore_index=self.ignore_index)
  294. return avg_loss
  295. def generate_inputs(self):
  296. inputs = OrderedDict()
  297. if self.fixed_input_shape is not None:
  298. input_shape =[None, 3, self.fixed_input_shape[0], self.fixed_input_shape[1]]
  299. inputs['image'] = fluid.data(
  300. dtype='float32', shape=input_shape, name='image')
  301. else:
  302. inputs['image'] = fluid.data(
  303. dtype='float32', shape=[None, 3, None, None], name='image')
  304. if self.mode == 'train':
  305. inputs['label'] = fluid.data(
  306. dtype='int32', shape=[None, 1, None, None], name='label')
  307. elif self.mode == 'eval':
  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(loc=0.0, scale=0.01))
  329. with scope('logit'):
  330. with fluid.name_scope('last_conv'):
  331. logit = conv(
  332. data,
  333. self.num_classes,
  334. 1,
  335. stride=1,
  336. padding=0,
  337. bias_attr=True,
  338. param_attr=param_attr)
  339. image_shape = fluid.layers.shape(image)
  340. logit = fluid.layers.resize_bilinear(logit, image_shape[2:])
  341. if self.num_classes == 1:
  342. out = sigmoid_to_softmax(logit)
  343. out = fluid.layers.transpose(out, [0, 2, 3, 1])
  344. else:
  345. out = fluid.layers.transpose(logit, [0, 2, 3, 1])
  346. pred = fluid.layers.argmax(out, axis=3)
  347. pred = fluid.layers.unsqueeze(pred, axes=[3])
  348. if self.mode == 'train':
  349. label = inputs['label']
  350. mask = label != self.ignore_index
  351. return self._get_loss(logit, label, mask)
  352. elif self.mode == 'eval':
  353. label = inputs['label']
  354. mask = label != self.ignore_index
  355. loss = self._get_loss(logit, label, mask)
  356. return loss, pred, label, mask
  357. else:
  358. if self.num_classes == 1:
  359. logit = sigmoid_to_softmax(logit)
  360. else:
  361. logit = fluid.layers.softmax(logit, axis=1)
  362. return pred, logit
  363. return logit