det_east_loss.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import paddle
  18. from paddle import nn
  19. from .det_basic_loss import DiceLoss
  20. class EASTLoss(nn.Layer):
  21. """
  22. """
  23. def __init__(self,
  24. eps=1e-6,
  25. **kwargs):
  26. super(EASTLoss, self).__init__()
  27. self.dice_loss = DiceLoss(eps=eps)
  28. def forward(self, predicts, labels):
  29. l_score, l_geo, l_mask = labels[1:]
  30. f_score = predicts['f_score']
  31. f_geo = predicts['f_geo']
  32. dice_loss = self.dice_loss(f_score, l_score, l_mask)
  33. #smoooth_l1_loss
  34. channels = 8
  35. l_geo_split = paddle.split(
  36. l_geo, num_or_sections=channels + 1, axis=1)
  37. f_geo_split = paddle.split(f_geo, num_or_sections=channels, axis=1)
  38. smooth_l1 = 0
  39. for i in range(0, channels):
  40. geo_diff = l_geo_split[i] - f_geo_split[i]
  41. abs_geo_diff = paddle.abs(geo_diff)
  42. smooth_l1_sign = paddle.less_than(abs_geo_diff, l_score)
  43. smooth_l1_sign = paddle.cast(smooth_l1_sign, dtype='float32')
  44. in_loss = abs_geo_diff * abs_geo_diff * smooth_l1_sign + \
  45. (abs_geo_diff - 0.5) * (1.0 - smooth_l1_sign)
  46. out_loss = l_geo_split[-1] / channels * in_loss * l_score
  47. smooth_l1 += out_loss
  48. smooth_l1_loss = paddle.mean(smooth_l1 * l_score)
  49. dice_loss = dice_loss * 0.01
  50. total_loss = dice_loss + smooth_l1_loss
  51. losses = {"loss":total_loss, \
  52. "dice_loss":dice_loss,\
  53. "smooth_l1_loss":smooth_l1_loss}
  54. return losses