iou_loss.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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 numpy as np
  18. from paddle import fluid
  19. from ppdet.core.workspace import register, serializable
  20. __all__ = ['IouLoss']
  21. @register
  22. @serializable
  23. class IouLoss(object):
  24. """
  25. iou loss, see https://arxiv.org/abs/1908.03851
  26. loss = 1.0 - iou * iou
  27. Args:
  28. loss_weight (float): iou loss weight, default is 2.5
  29. max_height (int): max height of input to support random shape input
  30. max_width (int): max width of input to support random shape input
  31. ciou_term (bool): whether to add ciou_term
  32. loss_square (bool): whether to square the iou term
  33. """
  34. def __init__(self,
  35. loss_weight=2.5,
  36. max_height=608,
  37. max_width=608,
  38. ciou_term=False,
  39. loss_square=True):
  40. self._loss_weight = loss_weight
  41. self._MAX_HI = max_height
  42. self._MAX_WI = max_width
  43. self.ciou_term = ciou_term
  44. self.loss_square = loss_square
  45. def __call__(self,
  46. x,
  47. y,
  48. w,
  49. h,
  50. tx,
  51. ty,
  52. tw,
  53. th,
  54. anchors,
  55. downsample_ratio,
  56. batch_size,
  57. scale_x_y=1.,
  58. ioup=None,
  59. eps=1.e-10):
  60. '''
  61. Args:
  62. x | y | w | h ([Variables]): the output of yolov3 for encoded x|y|w|h
  63. tx |ty |tw |th ([Variables]): the target of yolov3 for encoded x|y|w|h
  64. anchors ([float]): list of anchors for current output layer
  65. downsample_ratio (float): the downsample ratio for current output layer
  66. batch_size (int): training batch size
  67. eps (float): the decimal to prevent the denominator eqaul zero
  68. '''
  69. pred = self._bbox_transform(x, y, w, h, anchors, downsample_ratio,
  70. batch_size, False, scale_x_y, eps)
  71. gt = self._bbox_transform(tx, ty, tw, th, anchors, downsample_ratio,
  72. batch_size, True, scale_x_y, eps)
  73. iouk = self._iou(pred, gt, ioup, eps)
  74. if self.loss_square:
  75. loss_iou = 1. - iouk * iouk
  76. else:
  77. loss_iou = 1. - iouk
  78. loss_iou = loss_iou * self._loss_weight
  79. return loss_iou
  80. def _iou(self, pred, gt, ioup=None, eps=1.e-10):
  81. x1, y1, x2, y2 = pred
  82. x1g, y1g, x2g, y2g = gt
  83. x2 = fluid.layers.elementwise_max(x1, x2)
  84. y2 = fluid.layers.elementwise_max(y1, y2)
  85. xkis1 = fluid.layers.elementwise_max(x1, x1g)
  86. ykis1 = fluid.layers.elementwise_max(y1, y1g)
  87. xkis2 = fluid.layers.elementwise_min(x2, x2g)
  88. ykis2 = fluid.layers.elementwise_min(y2, y2g)
  89. intsctk = (xkis2 - xkis1) * (ykis2 - ykis1)
  90. intsctk = intsctk * fluid.layers.greater_than(
  91. xkis2, xkis1) * fluid.layers.greater_than(ykis2, ykis1)
  92. unionk = (x2 - x1) * (y2 - y1) + (x2g - x1g) * (y2g - y1g
  93. ) - intsctk + eps
  94. iouk = intsctk / unionk
  95. if self.ciou_term:
  96. ciou = self.get_ciou_term(pred, gt, iouk, eps)
  97. iouk = iouk - ciou
  98. return iouk
  99. def get_ciou_term(self, pred, gt, iouk, eps):
  100. x1, y1, x2, y2 = pred
  101. x1g, y1g, x2g, y2g = gt
  102. cx = (x1 + x2) / 2
  103. cy = (y1 + y2) / 2
  104. w = (x2 - x1) + fluid.layers.cast((x2 - x1) == 0, 'float32')
  105. h = (y2 - y1) + fluid.layers.cast((y2 - y1) == 0, 'float32')
  106. cxg = (x1g + x2g) / 2
  107. cyg = (y1g + y2g) / 2
  108. wg = x2g - x1g
  109. hg = y2g - y1g
  110. # A or B
  111. xc1 = fluid.layers.elementwise_min(x1, x1g)
  112. yc1 = fluid.layers.elementwise_min(y1, y1g)
  113. xc2 = fluid.layers.elementwise_max(x2, x2g)
  114. yc2 = fluid.layers.elementwise_max(y2, y2g)
  115. # DIOU term
  116. dist_intersection = (cx - cxg) * (cx - cxg) + (cy - cyg) * (cy - cyg)
  117. dist_union = (xc2 - xc1) * (xc2 - xc1) + (yc2 - yc1) * (yc2 - yc1)
  118. diou_term = (dist_intersection + eps) / (dist_union + eps)
  119. # CIOU term
  120. ciou_term = 0
  121. ar_gt = wg / hg
  122. ar_pred = w / h
  123. arctan = fluid.layers.atan(ar_gt) - fluid.layers.atan(ar_pred)
  124. ar_loss = 4. / np.pi / np.pi * arctan * arctan
  125. alpha = ar_loss / (1 - iouk + ar_loss + eps)
  126. alpha.stop_gradient = True
  127. ciou_term = alpha * ar_loss
  128. return diou_term + ciou_term
  129. def _bbox_transform(self, dcx, dcy, dw, dh, anchors, downsample_ratio,
  130. batch_size, is_gt, scale_x_y, eps):
  131. grid_x = int(self._MAX_WI / downsample_ratio)
  132. grid_y = int(self._MAX_HI / downsample_ratio)
  133. an_num = len(anchors) // 2
  134. shape_fmp = fluid.layers.shape(dcx)
  135. shape_fmp.stop_gradient = True
  136. # generate the grid_w x grid_h center of feature map
  137. idx_i = np.array([[i for i in range(grid_x)]])
  138. idx_j = np.array([[j for j in range(grid_y)]]).transpose()
  139. gi_np = np.repeat(idx_i, grid_y, axis=0)
  140. gi_np = np.reshape(gi_np, newshape=[1, 1, grid_y, grid_x])
  141. gi_np = np.tile(gi_np, reps=[batch_size, an_num, 1, 1])
  142. gj_np = np.repeat(idx_j, grid_x, axis=1)
  143. gj_np = np.reshape(gj_np, newshape=[1, 1, grid_y, grid_x])
  144. gj_np = np.tile(gj_np, reps=[batch_size, an_num, 1, 1])
  145. gi_max = self._create_tensor_from_numpy(gi_np.astype(np.float32))
  146. gi = fluid.layers.crop(x=gi_max, shape=dcx)
  147. gi.stop_gradient = True
  148. gj_max = self._create_tensor_from_numpy(gj_np.astype(np.float32))
  149. gj = fluid.layers.crop(x=gj_max, shape=dcx)
  150. gj.stop_gradient = True
  151. grid_x_act = fluid.layers.cast(shape_fmp[3], dtype="float32")
  152. grid_x_act.stop_gradient = True
  153. grid_y_act = fluid.layers.cast(shape_fmp[2], dtype="float32")
  154. grid_y_act.stop_gradient = True
  155. if is_gt:
  156. cx = fluid.layers.elementwise_add(dcx, gi) / grid_x_act
  157. cx.gradient = True
  158. cy = fluid.layers.elementwise_add(dcy, gj) / grid_y_act
  159. cy.gradient = True
  160. else:
  161. dcx_sig = fluid.layers.sigmoid(dcx)
  162. dcy_sig = fluid.layers.sigmoid(dcy)
  163. if (abs(scale_x_y - 1.0) > eps):
  164. dcx_sig = scale_x_y * dcx_sig - 0.5 * (scale_x_y - 1)
  165. dcy_sig = scale_x_y * dcy_sig - 0.5 * (scale_x_y - 1)
  166. cx = fluid.layers.elementwise_add(dcx_sig, gi) / grid_x_act
  167. cy = fluid.layers.elementwise_add(dcy_sig, gj) / grid_y_act
  168. anchor_w_ = [anchors[i] for i in range(0, len(anchors)) if i % 2 == 0]
  169. anchor_w_np = np.array(anchor_w_)
  170. anchor_w_np = np.reshape(anchor_w_np, newshape=[1, an_num, 1, 1])
  171. anchor_w_np = np.tile(anchor_w_np, reps=[batch_size, 1, grid_y, grid_x])
  172. anchor_w_max = self._create_tensor_from_numpy(
  173. anchor_w_np.astype(np.float32))
  174. anchor_w = fluid.layers.crop(x=anchor_w_max, shape=dcx)
  175. anchor_w.stop_gradient = True
  176. anchor_h_ = [anchors[i] for i in range(0, len(anchors)) if i % 2 == 1]
  177. anchor_h_np = np.array(anchor_h_)
  178. anchor_h_np = np.reshape(anchor_h_np, newshape=[1, an_num, 1, 1])
  179. anchor_h_np = np.tile(anchor_h_np, reps=[batch_size, 1, grid_y, grid_x])
  180. anchor_h_max = self._create_tensor_from_numpy(
  181. anchor_h_np.astype(np.float32))
  182. anchor_h = fluid.layers.crop(x=anchor_h_max, shape=dcx)
  183. anchor_h.stop_gradient = True
  184. # e^tw e^th
  185. exp_dw = fluid.layers.exp(dw)
  186. exp_dh = fluid.layers.exp(dh)
  187. pw = fluid.layers.elementwise_mul(exp_dw, anchor_w) / \
  188. (grid_x_act * downsample_ratio)
  189. ph = fluid.layers.elementwise_mul(exp_dh, anchor_h) / \
  190. (grid_y_act * downsample_ratio)
  191. if is_gt:
  192. exp_dw.stop_gradient = True
  193. exp_dh.stop_gradient = True
  194. pw.stop_gradient = True
  195. ph.stop_gradient = True
  196. x1 = cx - 0.5 * pw
  197. y1 = cy - 0.5 * ph
  198. x2 = cx + 0.5 * pw
  199. y2 = cy + 0.5 * ph
  200. if is_gt:
  201. x1.stop_gradient = True
  202. y1.stop_gradient = True
  203. x2.stop_gradient = True
  204. y2.stop_gradient = True
  205. return x1, y1, x2, y2
  206. def _create_tensor_from_numpy(self, numpy_array):
  207. paddle_array = fluid.layers.create_global_var(
  208. shape=numpy_array.shape, value=0., dtype=numpy_array.dtype)
  209. fluid.layers.assign(numpy_array, paddle_array)
  210. return paddle_array