det_db_loss.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. from paddle import nn
  18. from .det_basic_loss import BalanceLoss, MaskL1Loss, DiceLoss
  19. class DBLoss(nn.Layer):
  20. """
  21. Differentiable Binarization (DB) Loss Function
  22. args:
  23. param (dict): the super paramter for DB Loss
  24. """
  25. def __init__(self,
  26. balance_loss=True,
  27. main_loss_type='DiceLoss',
  28. alpha=5,
  29. beta=10,
  30. ohem_ratio=3,
  31. eps=1e-6,
  32. **kwargs):
  33. super(DBLoss, self).__init__()
  34. self.alpha = alpha
  35. self.beta = beta
  36. self.dice_loss = DiceLoss(eps=eps)
  37. self.l1_loss = MaskL1Loss(eps=eps)
  38. self.bce_loss = BalanceLoss(
  39. balance_loss=balance_loss,
  40. main_loss_type=main_loss_type,
  41. negative_ratio=ohem_ratio)
  42. def forward(self, predicts, labels):
  43. predict_maps = predicts['maps']
  44. label_threshold_map, label_threshold_mask, label_shrink_map, label_shrink_mask = labels[
  45. 1:]
  46. shrink_maps = predict_maps[:, 0, :, :]
  47. threshold_maps = predict_maps[:, 1, :, :]
  48. binary_maps = predict_maps[:, 2, :, :]
  49. loss_shrink_maps = self.bce_loss(shrink_maps, label_shrink_map,
  50. label_shrink_mask)
  51. loss_threshold_maps = self.l1_loss(threshold_maps, label_threshold_map,
  52. label_threshold_mask)
  53. loss_binary_maps = self.dice_loss(binary_maps, label_shrink_map,
  54. label_shrink_mask)
  55. loss_shrink_maps = self.alpha * loss_shrink_maps
  56. loss_threshold_maps = self.beta * loss_threshold_maps
  57. loss_all = loss_shrink_maps + loss_threshold_maps \
  58. + loss_binary_maps
  59. losses = {'loss': loss_all, \
  60. "loss_shrink_maps": loss_shrink_maps, \
  61. "loss_threshold_maps": loss_threshold_maps, \
  62. "loss_binary_maps": loss_binary_maps}
  63. return losses