hrnet.py 7.0 KB

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