ctfocal_loss.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  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. import paddle.nn.functional as F
  19. from paddlex.ppdet.core.workspace import register, serializable
  20. __all__ = ['CTFocalLoss']
  21. @register
  22. @serializable
  23. class CTFocalLoss(object):
  24. """
  25. CTFocalLoss: CornerNet & CenterNet Focal Loss
  26. Args:
  27. loss_weight (float): loss weight
  28. gamma (float): gamma parameter for Focal Loss
  29. """
  30. def __init__(self, loss_weight=1., gamma=2.0):
  31. self.loss_weight = loss_weight
  32. self.gamma = gamma
  33. def __call__(self, pred, target):
  34. """
  35. Calculate the loss
  36. Args:
  37. pred (Tensor): heatmap prediction
  38. target (Tensor): target for positive samples
  39. Return:
  40. ct_focal_loss (Tensor): Focal Loss used in CornerNet & CenterNet.
  41. Note that the values in target are in [0, 1] since gaussian is
  42. used to reduce the punishment and we treat [0, 1) as neg example.
  43. """
  44. fg_map = paddle.cast(target == 1, 'float32')
  45. fg_map.stop_gradient = True
  46. bg_map = paddle.cast(target < 1, 'float32')
  47. bg_map.stop_gradient = True
  48. neg_weights = paddle.pow(1 - target, 4) * bg_map
  49. pos_loss = 0 - paddle.log(pred) * paddle.pow(1 - pred,
  50. self.gamma) * fg_map
  51. neg_loss = 0 - paddle.log(1 - pred) * paddle.pow(
  52. pred, self.gamma) * neg_weights
  53. pos_loss = paddle.sum(pos_loss)
  54. neg_loss = paddle.sum(neg_loss)
  55. fg_num = paddle.sum(fg_map)
  56. ct_focal_loss = (pos_loss + neg_loss) / (
  57. fg_num + paddle.cast(fg_num == 0, 'float32'))
  58. return ct_focal_loss * self.loss_weight