iou_loss.py 9.2 KB

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