Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

180 lines
7.2KB

  1. # Loss functions
  2. import torch
  3. import torch.nn as nn
  4. from utils.general import bbox_iou
  5. from utils.torch_utils import is_parallel
  6. def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
  7. # return positive, negative label smoothing BCE targets
  8. return 1.0 - 0.5 * eps, 0.5 * eps
  9. class BCEBlurWithLogitsLoss(nn.Module):
  10. # BCEwithLogitLoss() with reduced missing label effects.
  11. def __init__(self, alpha=0.05):
  12. super(BCEBlurWithLogitsLoss, self).__init__()
  13. self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss()
  14. self.alpha = alpha
  15. def forward(self, pred, true):
  16. loss = self.loss_fcn(pred, true)
  17. pred = torch.sigmoid(pred) # prob from logits
  18. dx = pred - true # reduce only missing label effects
  19. # dx = (pred - true).abs() # reduce missing label and false label effects
  20. alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
  21. loss *= alpha_factor
  22. return loss.mean()
  23. class FocalLoss(nn.Module):
  24. # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
  25. def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
  26. super(FocalLoss, self).__init__()
  27. self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
  28. self.gamma = gamma
  29. self.alpha = alpha
  30. self.reduction = loss_fcn.reduction
  31. self.loss_fcn.reduction = 'none' # required to apply FL to each element
  32. def forward(self, pred, true):
  33. loss = self.loss_fcn(pred, true)
  34. # p_t = torch.exp(-loss)
  35. # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
  36. # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
  37. pred_prob = torch.sigmoid(pred) # prob from logits
  38. p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
  39. alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
  40. modulating_factor = (1.0 - p_t) ** self.gamma
  41. loss *= alpha_factor * modulating_factor
  42. if self.reduction == 'mean':
  43. return loss.mean()
  44. elif self.reduction == 'sum':
  45. return loss.sum()
  46. else: # 'none'
  47. return loss
  48. def compute_loss(p, targets, model): # predictions, targets, model
  49. device = targets.device
  50. lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
  51. tcls, tbox, indices, anchors = build_targets(p, targets, model) # targets
  52. h = model.hyp # hyperparameters
  53. # Define criteria
  54. BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.Tensor([h['cls_pw']])).to(device)
  55. BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.Tensor([h['obj_pw']])).to(device)
  56. # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
  57. cp, cn = smooth_BCE(eps=0.0)
  58. # Focal loss
  59. g = h['fl_gamma'] # focal loss gamma
  60. if g > 0:
  61. BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
  62. # Losses
  63. nt = 0 # number of targets
  64. no = len(p) # number of outputs
  65. balance = [4.0, 1.0, 0.4] if no == 3 else [4.0, 1.0, 0.4, 0.1] # P3-5 or P3-6
  66. for i, pi in enumerate(p): # layer index, layer predictions
  67. b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
  68. tobj = torch.zeros_like(pi[..., 0], device=device) # target obj
  69. n = b.shape[0] # number of targets
  70. if n:
  71. nt += n # cumulative targets
  72. ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
  73. # Regression
  74. pxy = ps[:, :2].sigmoid() * 2. - 0.5
  75. pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]
  76. pbox = torch.cat((pxy, pwh), 1).to(device) # predicted box
  77. iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target)
  78. lbox += (1.0 - iou).mean() # iou loss
  79. # Objectness
  80. tobj[b, a, gj, gi] = (1.0 - model.gr) + model.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio
  81. # Classification
  82. if model.nc > 1: # cls loss (only if multiple classes)
  83. t = torch.full_like(ps[:, 5:], cn, device=device) # targets
  84. t[range(n), tcls[i]] = cp
  85. lcls += BCEcls(ps[:, 5:], t) # BCE
  86. # Append targets to text file
  87. # with open('targets.txt', 'a') as file:
  88. # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
  89. lobj += BCEobj(pi[..., 4], tobj) * balance[i] # obj loss
  90. s = 3 / no # output count scaling
  91. lbox *= h['box'] * s
  92. lobj *= h['obj'] * s * (1.4 if no == 4 else 1.)
  93. lcls *= h['cls'] * s
  94. bs = tobj.shape[0] # batch size
  95. loss = lbox + lobj + lcls
  96. return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()
  97. def build_targets(p, targets, model):
  98. # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
  99. det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module
  100. na, nt = det.na, targets.shape[0] # number of anchors, targets
  101. tcls, tbox, indices, anch = [], [], [], []
  102. gain = torch.ones(7, device=targets.device) # normalized to gridspace gain
  103. ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
  104. targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
  105. g = 0.5 # bias
  106. off = torch.tensor([[0, 0],
  107. [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
  108. # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
  109. ], device=targets.device).float() * g # offsets
  110. for i in range(det.nl):
  111. anchors = det.anchors[i]
  112. gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
  113. # Match targets to anchors
  114. t = targets * gain
  115. if nt:
  116. # Matches
  117. r = t[:, :, 4:6] / anchors[:, None] # wh ratio
  118. j = torch.max(r, 1. / r).max(2)[0] < model.hyp['anchor_t'] # compare
  119. # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
  120. t = t[j] # filter
  121. # Offsets
  122. gxy = t[:, 2:4] # grid xy
  123. gxi = gain[[2, 3]] - gxy # inverse
  124. j, k = ((gxy % 1. < g) & (gxy > 1.)).T
  125. l, m = ((gxi % 1. < g) & (gxi > 1.)).T
  126. j = torch.stack((torch.ones_like(j), j, k, l, m))
  127. t = t.repeat((5, 1, 1))[j]
  128. offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
  129. else:
  130. t = targets[0]
  131. offsets = 0
  132. # Define
  133. b, c = t[:, :2].long().T # image, class
  134. gxy = t[:, 2:4] # grid xy
  135. gwh = t[:, 4:6] # grid wh
  136. gij = (gxy - offsets).long()
  137. gi, gj = gij.T # grid xy indices
  138. # Append
  139. a = t[:, 6].long() # anchor indices
  140. indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
  141. tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
  142. anch.append(anchors[a]) # anchors
  143. tcls.append(c) # class
  144. return tcls, tbox, indices, anch