det_db_loss.py 2.8 KB

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