hrnet.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. # coding: utf8
  2. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  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 paddle.fluid.initializer import MSRA
  21. from paddle.fluid.param_attr import ParamAttr
  22. from .model_utils.libs import sigmoid_to_softmax
  23. from .model_utils.loss import softmax_with_loss
  24. from .model_utils.loss import dice_loss
  25. from .model_utils.loss import bce_loss
  26. import paddlex
  27. class HRNet(object):
  28. def __init__(self,
  29. num_classes,
  30. input_channel=3,
  31. mode='train',
  32. width=18,
  33. use_bce_loss=False,
  34. use_dice_loss=False,
  35. class_weight=None,
  36. ignore_index=255,
  37. fixed_input_shape=None):
  38. # dice_loss或bce_loss只适用两类分割中
  39. if num_classes > 2 and (use_bce_loss or use_dice_loss):
  40. raise ValueError(
  41. "dice loss and bce loss is only applicable to binary classfication"
  42. )
  43. if class_weight is not None:
  44. if isinstance(class_weight, list):
  45. if len(class_weight) != num_classes:
  46. raise ValueError(
  47. "Length of class_weight should be equal to number of classes"
  48. )
  49. elif isinstance(class_weight, str):
  50. if class_weight.lower() != 'dynamic':
  51. raise ValueError(
  52. "if class_weight is string, must be dynamic!")
  53. else:
  54. raise TypeError(
  55. 'Expect class_weight is a list or string but receive {}'.
  56. format(type(class_weight)))
  57. self.num_classes = num_classes
  58. self.input_channel = input_channel
  59. self.mode = mode
  60. self.use_bce_loss = use_bce_loss
  61. self.use_dice_loss = use_dice_loss
  62. self.class_weight = class_weight
  63. self.ignore_index = ignore_index
  64. self.fixed_input_shape = fixed_input_shape
  65. self.backbone = paddlex.cv.nets.hrnet.HRNet(
  66. width=width, feature_maps="stage4")
  67. def build_net(self, inputs):
  68. if self.use_dice_loss or self.use_bce_loss:
  69. self.num_classes = 1
  70. image = inputs['image']
  71. st4 = self.backbone(image)
  72. # upsample
  73. shape = fluid.layers.shape(st4[0])[-2:]
  74. st4[1] = fluid.layers.resize_bilinear(st4[1], out_shape=shape)
  75. st4[2] = fluid.layers.resize_bilinear(st4[2], out_shape=shape)
  76. st4[3] = fluid.layers.resize_bilinear(st4[3], out_shape=shape)
  77. out = fluid.layers.concat(st4, axis=1)
  78. last_channels = sum(self.backbone.channels[str(self.backbone.width)][
  79. -1])
  80. out = self._conv_bn_layer(
  81. input=out,
  82. filter_size=1,
  83. num_filters=last_channels,
  84. stride=1,
  85. if_act=True,
  86. name='conv-2')
  87. out = fluid.layers.conv2d(
  88. input=out,
  89. num_filters=self.num_classes,
  90. filter_size=1,
  91. stride=1,
  92. padding=0,
  93. act=None,
  94. param_attr=ParamAttr(
  95. initializer=MSRA(), name='conv-1_weights'),
  96. bias_attr=False)
  97. input_shape = fluid.layers.shape(image)[-2:]
  98. logit = fluid.layers.resize_bilinear(out, input_shape)
  99. if self.num_classes == 1:
  100. out = sigmoid_to_softmax(logit)
  101. out = fluid.layers.transpose(out, [0, 2, 3, 1])
  102. else:
  103. out = fluid.layers.transpose(logit, [0, 2, 3, 1])
  104. pred = fluid.layers.argmax(out, axis=3)
  105. pred = fluid.layers.unsqueeze(pred, axes=[3])
  106. if self.mode == 'train':
  107. label = inputs['label']
  108. mask = label != self.ignore_index
  109. return self._get_loss(logit, label, mask)
  110. elif self.mode == 'eval':
  111. label = inputs['label']
  112. mask = label != self.ignore_index
  113. loss = self._get_loss(logit, label, mask)
  114. return loss, pred, label, mask
  115. else:
  116. if self.num_classes == 1:
  117. logit = sigmoid_to_softmax(logit)
  118. else:
  119. logit = fluid.layers.softmax(logit, axis=1)
  120. return pred, logit
  121. def generate_inputs(self):
  122. inputs = OrderedDict()
  123. if self.fixed_input_shape is not None:
  124. input_shape = [
  125. None, self.input_channel, self.fixed_input_shape[1],
  126. self.fixed_input_shape[0]
  127. ]
  128. inputs['image'] = fluid.data(
  129. dtype='float32', shape=input_shape, name='image')
  130. else:
  131. inputs['image'] = fluid.data(
  132. dtype='float32',
  133. shape=[None, self.input_channel, None, None],
  134. name='image')
  135. if self.mode == 'train':
  136. inputs['label'] = fluid.data(
  137. dtype='int32', shape=[None, 1, None, None], name='label')
  138. elif self.mode == 'eval':
  139. inputs['label'] = fluid.data(
  140. dtype='int32', shape=[None, 1, None, None], name='label')
  141. return inputs
  142. def _get_loss(self, logit, label, mask):
  143. avg_loss = 0
  144. if not (self.use_dice_loss or self.use_bce_loss):
  145. avg_loss += softmax_with_loss(
  146. logit,
  147. label,
  148. mask,
  149. num_classes=self.num_classes,
  150. weight=self.class_weight,
  151. ignore_index=self.ignore_index)
  152. else:
  153. if self.use_dice_loss:
  154. avg_loss += dice_loss(logit, label, mask)
  155. if self.use_bce_loss:
  156. avg_loss += bce_loss(
  157. logit, label, mask, ignore_index=self.ignore_index)
  158. return avg_loss
  159. def _conv_bn_layer(self,
  160. input,
  161. filter_size,
  162. num_filters,
  163. stride=1,
  164. padding=1,
  165. num_groups=1,
  166. if_act=True,
  167. name=None):
  168. conv = fluid.layers.conv2d(
  169. input=input,
  170. num_filters=num_filters,
  171. filter_size=filter_size,
  172. stride=stride,
  173. padding=(filter_size - 1) // 2,
  174. groups=num_groups,
  175. act=None,
  176. param_attr=ParamAttr(
  177. initializer=MSRA(), name=name + '_weights'),
  178. bias_attr=False)
  179. bn_name = name + '_bn'
  180. bn = fluid.layers.batch_norm(
  181. input=conv,
  182. param_attr=ParamAttr(
  183. name=bn_name + "_scale",
  184. initializer=fluid.initializer.Constant(1.0)),
  185. bias_attr=ParamAttr(
  186. name=bn_name + "_offset",
  187. initializer=fluid.initializer.Constant(0.0)),
  188. moving_mean_name=bn_name + '_mean',
  189. moving_variance_name=bn_name + '_variance')
  190. if if_act:
  191. bn = fluid.layers.relu(bn)
  192. return bn