loss.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. # Loss functions
  2. import torch
  3. import torch.nn as nn
  4. import numpy as np
  5. from utils.general import bbox_iou
  6. from utils.torch_utils import is_parallel
  7. def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
  8. # return positive, negative label smoothing BCE targets
  9. return 1.0 - 0.5 * eps, 0.5 * eps
  10. class BCEBlurWithLogitsLoss(nn.Module):
  11. # BCEwithLogitLoss() with reduced missing label effects.
  12. def __init__(self, alpha=0.05):
  13. super(BCEBlurWithLogitsLoss, self).__init__()
  14. self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss()
  15. self.alpha = alpha
  16. def forward(self, pred, true):
  17. loss = self.loss_fcn(pred, true)
  18. pred = torch.sigmoid(pred) # prob from logits
  19. dx = pred - true # reduce only missing label effects
  20. # dx = (pred - true).abs() # reduce missing label and false label effects
  21. alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
  22. loss *= alpha_factor
  23. return loss.mean()
  24. class FocalLoss(nn.Module):
  25. # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
  26. def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
  27. super(FocalLoss, self).__init__()
  28. self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
  29. self.gamma = gamma
  30. self.alpha = alpha
  31. self.reduction = loss_fcn.reduction
  32. self.loss_fcn.reduction = 'none' # required to apply FL to each element
  33. def forward(self, pred, true):
  34. loss = self.loss_fcn(pred, true)
  35. # p_t = torch.exp(-loss)
  36. # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
  37. # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
  38. pred_prob = torch.sigmoid(pred) # prob from logits
  39. p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
  40. alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
  41. modulating_factor = (1.0 - p_t) ** self.gamma
  42. loss *= alpha_factor * modulating_factor
  43. if self.reduction == 'mean':
  44. return loss.mean()
  45. elif self.reduction == 'sum':
  46. return loss.sum()
  47. else: # 'none'
  48. return loss
  49. class QFocalLoss(nn.Module):
  50. # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
  51. def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
  52. super(QFocalLoss, self).__init__()
  53. self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
  54. self.gamma = gamma
  55. self.alpha = alpha
  56. self.reduction = loss_fcn.reduction
  57. self.loss_fcn.reduction = 'none' # required to apply FL to each element
  58. def forward(self, pred, true):
  59. loss = self.loss_fcn(pred, true)
  60. pred_prob = torch.sigmoid(pred) # prob from logits
  61. alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
  62. modulating_factor = torch.abs(true - pred_prob) ** self.gamma
  63. loss *= alpha_factor * modulating_factor
  64. if self.reduction == 'mean':
  65. return loss.mean()
  66. elif self.reduction == 'sum':
  67. return loss.sum()
  68. else: # 'none'
  69. return loss
  70. class WingLoss(nn.Module):
  71. def __init__(self, w=10, e=2):
  72. super(WingLoss, self).__init__()
  73. # https://arxiv.org/pdf/1711.06753v4.pdf Figure 5
  74. self.w = w
  75. self.e = e
  76. self.C = self.w - self.w * np.log(1 + self.w / self.e)
  77. def forward(self, x, t, sigma=1):
  78. weight = torch.ones_like(t)
  79. weight[torch.where(t==-1)] = 0
  80. diff = weight * (x - t)
  81. abs_diff = diff.abs()
  82. flag = (abs_diff.data < self.w).float()
  83. y = flag * self.w * torch.log(1 + abs_diff / self.e) + (1 - flag) * (abs_diff - self.C)
  84. return y.sum()
  85. class LandmarksLoss(nn.Module):
  86. # BCEwithLogitLoss() with reduced missing label effects.
  87. def __init__(self, alpha=1.0):
  88. super(LandmarksLoss, self).__init__()
  89. self.loss_fcn = WingLoss()#nn.SmoothL1Loss(reduction='sum')
  90. self.alpha = alpha
  91. def forward(self, pred, truel, mask):
  92. loss = self.loss_fcn(pred*mask, truel*mask)
  93. return loss / (torch.sum(mask) + 10e-14)
  94. def compute_loss(p, targets, model): # predictions, targets, model
  95. device = targets.device
  96. lcls, lbox, lobj, lmark = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
  97. tcls, tbox, indices, anchors, tlandmarks, lmks_mask = build_targets(p, targets, model) # targets
  98. h = model.hyp # hyperparameters
  99. # Define criteria
  100. BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device)) # weight=model.class_weights)
  101. BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
  102. landmarks_loss = LandmarksLoss(1.0)
  103. # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
  104. cp, cn = smooth_BCE(eps=0.0)
  105. # Focal loss
  106. g = h['fl_gamma'] # focal loss gamma
  107. if g > 0:
  108. BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
  109. # Losses
  110. nt = 0 # number of targets
  111. no = len(p) # number of outputs
  112. balance = [4.0, 1.0, 0.4] if no == 3 else [4.0, 1.0, 0.4, 0.1] # P3-5 or P3-6
  113. for i, pi in enumerate(p): # layer index, layer predictions
  114. b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
  115. tobj = torch.zeros_like(pi[..., 0], device=device) # target obj
  116. n = b.shape[0] # number of targets
  117. if n:
  118. nt += n # cumulative targets
  119. ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
  120. # Regression
  121. pxy = ps[:, :2].sigmoid() * 2. - 0.5
  122. pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]
  123. pbox = torch.cat((pxy, pwh), 1) # predicted box
  124. iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target)
  125. lbox += (1.0 - iou).mean() # iou loss
  126. # Objectness
  127. tobj[b, a, gj, gi] = (1.0 - model.gr) + model.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio
  128. # Classification
  129. if model.nc > 1: # cls loss (only if multiple classes)
  130. t = torch.full_like(ps[:, 13:], cn, device=device) # targets
  131. t[range(n), tcls[i]] = cp
  132. lcls += BCEcls(ps[:, 13:], t) # BCE
  133. # Append targets to text file
  134. # with open('targets.txt', 'a') as file:
  135. # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
  136. #landmarks loss
  137. #plandmarks = ps[:,5:13].sigmoid() * 8. - 4.
  138. plandmarks = ps[:,5:13]
  139. plandmarks[:, 0:2] = plandmarks[:, 0:2] * anchors[i]
  140. plandmarks[:, 2:4] = plandmarks[:, 2:4] * anchors[i]
  141. plandmarks[:, 4:6] = plandmarks[:, 4:6] * anchors[i]
  142. plandmarks[:, 6:8] = plandmarks[:, 6:8] * anchors[i]
  143. # plandmarks[:, 8:10] = plandmarks[:,8:10] * anchors[i]
  144. lmark += landmarks_loss(plandmarks, tlandmarks[i], lmks_mask[i])
  145. lobj += BCEobj(pi[..., 4], tobj) * balance[i] # obj loss
  146. s = 3 / no # output count scaling
  147. lbox *= h['box'] * s
  148. lobj *= h['obj'] * s * (1.4 if no == 4 else 1.)
  149. lcls *= h['cls'] * s
  150. lmark *= h['landmark'] * s
  151. bs = tobj.shape[0] # batch size
  152. loss = lbox + lobj + lcls + lmark
  153. return loss * bs, torch.cat((lbox, lobj, lcls, lmark, loss)).detach()
  154. def build_targets(p, targets, model):
  155. # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
  156. det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module
  157. na, nt = det.na, targets.shape[0] # number of anchors, targets
  158. tcls, tbox, indices, anch, landmarks, lmks_mask = [], [], [], [], [], []
  159. #gain = torch.ones(7, device=targets.device) # normalized to gridspace gain
  160. gain = torch.ones(15, device=targets.device)
  161. ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
  162. targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
  163. g = 0.5 # bias
  164. off = torch.tensor([[0, 0],
  165. [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
  166. # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
  167. ], device=targets.device).float() * g # offsets
  168. for i in range(det.nl):
  169. anchors, shape = det.anchors[i], p[i].shape
  170. gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
  171. #landmarks 10
  172. gain[6:14] = torch.tensor(p[i].shape)[[3, 2, 3, 2, 3, 2, 3, 2]] # xyxy gain
  173. # Match targets to anchors
  174. t = targets * gain
  175. if nt:
  176. # Matches
  177. r = t[:, :, 4:6] / anchors[:, None] # wh ratio
  178. j = torch.max(r, 1. / r).max(2)[0] < model.hyp['anchor_t'] # compare
  179. # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
  180. t = t[j] # filter
  181. # Offsets
  182. gxy = t[:, 2:4] # grid xy
  183. gxi = gain[[2, 3]] - gxy # inverse
  184. j, k = ((gxy % 1. < g) & (gxy > 1.)).T
  185. l, m = ((gxi % 1. < g) & (gxi > 1.)).T
  186. j = torch.stack((torch.ones_like(j), j, k, l, m))
  187. t = t.repeat((5, 1, 1))[j]
  188. offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
  189. else:
  190. t = targets[0]
  191. offsets = 0
  192. # Define
  193. b, c = t[:, :2].long().T # image, class
  194. gxy = t[:, 2:4] # grid xy
  195. gwh = t[:, 4:6] # grid wh
  196. gij = (gxy - offsets).long()
  197. gi, gj = gij.T # grid xy indices
  198. # Append
  199. a = t[:, 14].long() # anchor indices
  200. #indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
  201. indices.append((b, a, gj.clamp_(0, shape[2] - 1), gi.clamp_(0, shape[3] - 1))) # image, anchor, grid
  202. tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
  203. anch.append(anchors[a]) # anchors
  204. tcls.append(c) # class
  205. #landmarks
  206. lks = t[:,6:14]
  207. #lks_mask = lks > 0
  208. #lks_mask = lks_mask.float()
  209. lks_mask = torch.where(lks < 0, torch.full_like(lks, 0.), torch.full_like(lks, 1.0))
  210. #应该是关键点的坐标除以anch的宽高才对,便于模型学习。使用gwh会导致不同关键点的编码不同,没有统一的参考标准
  211. lks[:, [0, 1]] = (lks[:, [0, 1]] - gij)
  212. lks[:, [2, 3]] = (lks[:, [2, 3]] - gij)
  213. lks[:, [4, 5]] = (lks[:, [4, 5]] - gij)
  214. lks[:, [6, 7]] = (lks[:, [6, 7]] - gij)
  215. # lks[:, [8, 9]] = (lks[:, [8, 9]] - gij)
  216. '''
  217. #anch_w = torch.ones(5, device=targets.device).fill_(anchors[0][0])
  218. #anch_wh = torch.ones(5, device=targets.device)
  219. anch_f_0 = (a == 0).unsqueeze(1).repeat(1, 5)
  220. anch_f_1 = (a == 1).unsqueeze(1).repeat(1, 5)
  221. anch_f_2 = (a == 2).unsqueeze(1).repeat(1, 5)
  222. lks[:, [0, 2, 4, 6, 8]] = torch.where(anch_f_0, lks[:, [0, 2, 4, 6, 8]] / anchors[0][0], lks[:, [0, 2, 4, 6, 8]])
  223. lks[:, [0, 2, 4, 6, 8]] = torch.where(anch_f_1, lks[:, [0, 2, 4, 6, 8]] / anchors[1][0], lks[:, [0, 2, 4, 6, 8]])
  224. lks[:, [0, 2, 4, 6, 8]] = torch.where(anch_f_2, lks[:, [0, 2, 4, 6, 8]] / anchors[2][0], lks[:, [0, 2, 4, 6, 8]])
  225. lks[:, [1, 3, 5, 7, 9]] = torch.where(anch_f_0, lks[:, [1, 3, 5, 7, 9]] / anchors[0][1], lks[:, [1, 3, 5, 7, 9]])
  226. lks[:, [1, 3, 5, 7, 9]] = torch.where(anch_f_1, lks[:, [1, 3, 5, 7, 9]] / anchors[1][1], lks[:, [1, 3, 5, 7, 9]])
  227. lks[:, [1, 3, 5, 7, 9]] = torch.where(anch_f_2, lks[:, [1, 3, 5, 7, 9]] / anchors[2][1], lks[:, [1, 3, 5, 7, 9]])
  228. #new_lks = lks[lks_mask>0]
  229. #print('new_lks: min --- ', torch.min(new_lks), ' max --- ', torch.max(new_lks))
  230. lks_mask_1 = torch.where(lks < -3, torch.full_like(lks, 0.), torch.full_like(lks, 1.0))
  231. lks_mask_2 = torch.where(lks > 3, torch.full_like(lks, 0.), torch.full_like(lks, 1.0))
  232. lks_mask_new = lks_mask * lks_mask_1 * lks_mask_2
  233. lks_mask_new[:, 0] = lks_mask_new[:, 0] * lks_mask_new[:, 1]
  234. lks_mask_new[:, 1] = lks_mask_new[:, 0] * lks_mask_new[:, 1]
  235. lks_mask_new[:, 2] = lks_mask_new[:, 2] * lks_mask_new[:, 3]
  236. lks_mask_new[:, 3] = lks_mask_new[:, 2] * lks_mask_new[:, 3]
  237. lks_mask_new[:, 4] = lks_mask_new[:, 4] * lks_mask_new[:, 5]
  238. lks_mask_new[:, 5] = lks_mask_new[:, 4] * lks_mask_new[:, 5]
  239. lks_mask_new[:, 6] = lks_mask_new[:, 6] * lks_mask_new[:, 7]
  240. lks_mask_new[:, 7] = lks_mask_new[:, 6] * lks_mask_new[:, 7]
  241. lks_mask_new[:, 8] = lks_mask_new[:, 8] * lks_mask_new[:, 9]
  242. lks_mask_new[:, 9] = lks_mask_new[:, 8] * lks_mask_new[:, 9]
  243. '''
  244. lks_mask_new = lks_mask
  245. lmks_mask.append(lks_mask_new)
  246. landmarks.append(lks)
  247. #print('lks: ', lks.size())
  248. return tcls, tbox, indices, anch, landmarks, lmks_mask