ctfocal_loss.py 2.3 KB

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