hrnet.py 7.3 KB

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