giou_loss.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. # Copyright (c) 2019 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 numpy as np
  18. from paddle import fluid
  19. from ppdet.core.workspace import register, serializable
  20. __all__ = ['GiouLoss']
  21. @register
  22. @serializable
  23. class GiouLoss(object):
  24. '''
  25. Generalized Intersection over Union, see https://arxiv.org/abs/1902.09630
  26. Args:
  27. loss_weight (float): diou loss weight, default as 10 in faster-rcnn
  28. is_cls_agnostic (bool): flag of class-agnostic
  29. num_classes (int): class num
  30. do_average (bool): whether to average the loss
  31. use_class_weight(bool): whether to use class weight
  32. '''
  33. __shared__ = ['num_classes']
  34. def __init__(self,
  35. loss_weight=10.,
  36. is_cls_agnostic=False,
  37. num_classes=81,
  38. do_average=True,
  39. use_class_weight=True):
  40. super(GiouLoss, self).__init__()
  41. self.loss_weight = loss_weight
  42. self.is_cls_agnostic = is_cls_agnostic
  43. self.num_classes = num_classes
  44. self.do_average = do_average
  45. self.class_weight = 2 if is_cls_agnostic else num_classes
  46. self.use_class_weight = use_class_weight
  47. # deltas: NxMx4
  48. def bbox_transform(self, deltas, weights):
  49. wx, wy, ww, wh = weights
  50. deltas = fluid.layers.reshape(deltas, shape=(0, -1, 4))
  51. dx = fluid.layers.slice(deltas, axes=[2], starts=[0], ends=[1]) * wx
  52. dy = fluid.layers.slice(deltas, axes=[2], starts=[1], ends=[2]) * wy
  53. dw = fluid.layers.slice(deltas, axes=[2], starts=[2], ends=[3]) * ww
  54. dh = fluid.layers.slice(deltas, axes=[2], starts=[3], ends=[4]) * wh
  55. dw = fluid.layers.clip(dw, -1.e10, np.log(1000. / 16))
  56. dh = fluid.layers.clip(dh, -1.e10, np.log(1000. / 16))
  57. pred_ctr_x = dx
  58. pred_ctr_y = dy
  59. pred_w = fluid.layers.exp(dw)
  60. pred_h = fluid.layers.exp(dh)
  61. x1 = pred_ctr_x - 0.5 * pred_w
  62. y1 = pred_ctr_y - 0.5 * pred_h
  63. x2 = pred_ctr_x + 0.5 * pred_w
  64. y2 = pred_ctr_y + 0.5 * pred_h
  65. x1 = fluid.layers.reshape(x1, shape=(-1, ))
  66. y1 = fluid.layers.reshape(y1, shape=(-1, ))
  67. x2 = fluid.layers.reshape(x2, shape=(-1, ))
  68. y2 = fluid.layers.reshape(y2, shape=(-1, ))
  69. return x1, y1, x2, y2
  70. def __call__(self,
  71. x,
  72. y,
  73. inside_weight=None,
  74. outside_weight=None,
  75. bbox_reg_weight=[0.1, 0.1, 0.2, 0.2],
  76. loc_reweight=None,
  77. use_transform=True):
  78. eps = 1.e-10
  79. if use_transform:
  80. x1, y1, x2, y2 = self.bbox_transform(x, bbox_reg_weight)
  81. x1g, y1g, x2g, y2g = self.bbox_transform(y, bbox_reg_weight)
  82. else:
  83. x1, y1, x2, y2 = fluid.layers.split(x, num_or_sections=4, dim=1)
  84. x1g, y1g, x2g, y2g = fluid.layers.split(y, num_or_sections=4, dim=1)
  85. x2 = fluid.layers.elementwise_max(x1, x2)
  86. y2 = fluid.layers.elementwise_max(y1, y2)
  87. xkis1 = fluid.layers.elementwise_max(x1, x1g)
  88. ykis1 = fluid.layers.elementwise_max(y1, y1g)
  89. xkis2 = fluid.layers.elementwise_min(x2, x2g)
  90. ykis2 = fluid.layers.elementwise_min(y2, y2g)
  91. xc1 = fluid.layers.elementwise_min(x1, x1g)
  92. yc1 = fluid.layers.elementwise_min(y1, y1g)
  93. xc2 = fluid.layers.elementwise_max(x2, x2g)
  94. yc2 = fluid.layers.elementwise_max(y2, y2g)
  95. intsctk = (xkis2 - xkis1) * (ykis2 - ykis1)
  96. intsctk = intsctk * fluid.layers.greater_than(
  97. xkis2, xkis1) * fluid.layers.greater_than(ykis2, ykis1)
  98. unionk = (x2 - x1) * (y2 - y1) + (x2g - x1g) * (y2g - y1g
  99. ) - intsctk + eps
  100. iouk = intsctk / unionk
  101. area_c = (xc2 - xc1) * (yc2 - yc1) + eps
  102. miouk = iouk - ((area_c - unionk) / area_c)
  103. iou_weights = 1
  104. if inside_weight is not None and outside_weight is not None:
  105. inside_weight = fluid.layers.reshape(inside_weight, shape=(-1, 4))
  106. outside_weight = fluid.layers.reshape(outside_weight, shape=(-1, 4))
  107. inside_weight = fluid.layers.reduce_mean(inside_weight, dim=1)
  108. outside_weight = fluid.layers.reduce_mean(outside_weight, dim=1)
  109. iou_weights = inside_weight * outside_weight
  110. elif outside_weight is not None:
  111. iou_weights = outside_weight
  112. if loc_reweight is not None:
  113. loc_reweight = fluid.layers.reshape(loc_reweight, shape=(-1, 1))
  114. loc_thresh = 0.9
  115. giou = 1 - (1 - loc_thresh
  116. ) * miouk - loc_thresh * miouk * loc_reweight
  117. else:
  118. giou = 1 - miouk
  119. if self.do_average:
  120. miouk = fluid.layers.reduce_mean(giou * iou_weights)
  121. else:
  122. iou_distance = fluid.layers.elementwise_mul(
  123. giou, iou_weights, axis=0)
  124. miouk = fluid.layers.reduce_sum(iou_distance)
  125. if self.use_class_weight:
  126. miouk = miouk * self.class_weight
  127. return miouk * self.loss_weight