CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hukaixuan19970627

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: hukaixuan19970627/yolov5_obb
Path: blob/master/utils/loss.py
Views: 475
1
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
"""
3
Loss functions
4
"""
5
6
import torch
7
import torch.nn as nn
8
9
from utils.metrics import bbox_iou
10
from utils.torch_utils import is_parallel
11
12
13
def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
14
# return positive, negative label smoothing BCE targets
15
return 1.0 - 0.5 * eps, 0.5 * eps
16
17
18
class BCEBlurWithLogitsLoss(nn.Module):
19
# BCEwithLogitLoss() with reduced missing label effects.
20
def __init__(self, alpha=0.05):
21
super().__init__()
22
self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss()
23
self.alpha = alpha
24
25
def forward(self, pred, true):
26
loss = self.loss_fcn(pred, true)
27
pred = torch.sigmoid(pred) # prob from logits
28
dx = pred - true # reduce only missing label effects
29
# dx = (pred - true).abs() # reduce missing label and false label effects
30
alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
31
loss *= alpha_factor
32
return loss.mean()
33
34
35
class FocalLoss(nn.Module):
36
# Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
37
def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
38
super().__init__()
39
self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
40
self.gamma = gamma
41
self.alpha = alpha
42
self.reduction = loss_fcn.reduction
43
self.loss_fcn.reduction = 'none' # required to apply FL to each element
44
45
def forward(self, pred, true):
46
loss = self.loss_fcn(pred, true)
47
# p_t = torch.exp(-loss)
48
# loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
49
50
# TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
51
pred_prob = torch.sigmoid(pred) # prob from logits
52
p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
53
alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
54
modulating_factor = (1.0 - p_t) ** self.gamma
55
loss *= alpha_factor * modulating_factor
56
57
if self.reduction == 'mean':
58
return loss.mean()
59
elif self.reduction == 'sum':
60
return loss.sum()
61
else: # 'none'
62
return loss
63
64
65
class QFocalLoss(nn.Module):
66
# Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
67
def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
68
super().__init__()
69
self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
70
self.gamma = gamma
71
self.alpha = alpha
72
self.reduction = loss_fcn.reduction
73
self.loss_fcn.reduction = 'none' # required to apply FL to each element
74
75
def forward(self, pred, true):
76
loss = self.loss_fcn(pred, true)
77
78
pred_prob = torch.sigmoid(pred) # prob from logits
79
alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
80
modulating_factor = torch.abs(true - pred_prob) ** self.gamma
81
loss *= alpha_factor * modulating_factor
82
83
if self.reduction == 'mean':
84
return loss.mean()
85
elif self.reduction == 'sum':
86
return loss.sum()
87
else: # 'none'
88
return loss
89
90
91
class ComputeLoss:
92
# Compute losses
93
def __init__(self, model, autobalance=False):
94
self.sort_obj_iou = False
95
device = next(model.parameters()).device # get model device
96
h = model.hyp # hyperparameters
97
98
# Define criteria
99
BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
100
BCEtheta = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['theta_pw']], device=device))
101
BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
102
103
# Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
104
self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
105
106
# Focal loss
107
g = h['fl_gamma'] # focal loss gamma
108
if g > 0:
109
BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
110
BCEtheta = FocalLoss(BCEtheta, g)
111
112
det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module
113
self.stride = det.stride # tensor([8., 16., 32., ...])
114
self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, 0.02]) # P3-P7
115
# self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index
116
self.ssi = list(self.stride).index(16) if autobalance else 0 # stride 16 index
117
self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance
118
self.BCEtheta = BCEtheta
119
for k in 'na', 'nc', 'nl', 'anchors':
120
setattr(self, k, getattr(det, k))
121
122
def __call__(self, p, targets): # predictions, targets, model
123
"""
124
Args:
125
p (list[P3_out,...]): torch.Size(b, self.na, h_i, w_i, self.no), self.na means the number of anchors scales
126
targets (tensor): (n_gt_all_batch, [img_index clsid cx cy l s theta gaussian_θ_labels])
127
128
Return:
129
total_loss * bs (tensor): [1]
130
torch.cat((lbox, lobj, lcls, ltheta)).detach(): [4]
131
"""
132
device = targets.device
133
lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
134
ltheta = torch.zeros(1, device=device)
135
# tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets
136
tcls, tbox, indices, anchors, tgaussian_theta = self.build_targets(p, targets) # targets
137
138
# Losses
139
for i, pi in enumerate(p): # layer index, layer predictions
140
b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
141
tobj = torch.zeros_like(pi[..., 0], device=device) # target obj
142
143
n = b.shape[0] # number of targets
144
if n:
145
ps = pi[b, a, gj, gi] # prediction subset corresponding to targets, (n_targets, self.no)
146
147
# Regression
148
pxy = ps[:, :2].sigmoid() * 2 - 0.5
149
pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i] # featuremap pixel
150
pbox = torch.cat((pxy, pwh), 1) # predicted box
151
iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target)
152
lbox += (1.0 - iou).mean() # iou loss
153
154
# Objectness
155
score_iou = iou.detach().clamp(0).type(tobj.dtype)
156
if self.sort_obj_iou:
157
sort_id = torch.argsort(score_iou)
158
b, a, gj, gi, score_iou = b[sort_id], a[sort_id], gj[sort_id], gi[sort_id], score_iou[sort_id]
159
tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * score_iou # iou ratio
160
161
# Classification
162
class_index = 5 + self.nc
163
if self.nc > 1: # cls loss (only if multiple classes)
164
# t = torch.full_like(ps[:, 5:], self.cn, device=device) # targets
165
t = torch.full_like(ps[:, 5:class_index], self.cn, device=device) # targets
166
t[range(n), tcls[i]] = self.cp
167
# lcls += self.BCEcls(ps[:, 5:], t) # BCE
168
lcls += self.BCEcls(ps[:, 5:class_index], t) # BCE
169
170
# theta Classification by Circular Smooth Label
171
t_theta = tgaussian_theta[i].type(ps.dtype) # target theta_gaussian_labels
172
ltheta += self.BCEtheta(ps[:, class_index:], t_theta)
173
174
# Append targets to text file
175
# with open('targets.txt', 'a') as file:
176
# [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
177
178
obji = self.BCEobj(pi[..., 4], tobj)
179
lobj += obji * self.balance[i] # obj loss
180
if self.autobalance:
181
self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
182
183
if self.autobalance:
184
self.balance = [x / self.balance[self.ssi] for x in self.balance]
185
lbox *= self.hyp['box']
186
lobj *= self.hyp['obj']
187
lcls *= self.hyp['cls']
188
ltheta *= self.hyp['theta']
189
bs = tobj.shape[0] # batch size
190
191
# return (lbox + lobj + lcls) * bs, torch.cat((lbox, lobj, lcls)).detach()
192
return (lbox + lobj + lcls + ltheta) * bs, torch.cat((lbox, lobj, lcls, ltheta)).detach()
193
194
def build_targets(self, p, targets):
195
"""
196
Args:
197
p (list[P3_out,...]): torch.Size(b, self.na, h_i, w_i, self.no), self.na means the number of anchors scales
198
targets (tensor): (n_gt_all_batch, [img_index clsid cx cy l s theta gaussian_θ_labels]) pixel
199
200
Return:non-normalized data
201
tcls (list[P3_out,...]): len=self.na, tensor.size(n_filter2)
202
tbox (list[P3_out,...]): len=self.na, tensor.size(n_filter2, 4) featuremap pixel
203
indices (list[P3_out,...]): len=self.na, tensor.size(4, n_filter2) [b, a, gj, gi]
204
anch (list[P3_out,...]): len=self.na, tensor.size(n_filter2, 2)
205
tgaussian_theta (list[P3_out,...]): len=self.na, tensor.size(n_filter2, hyp['cls_theta'])
206
# ttheta (list[P3_out,...]): len=self.na, tensor.size(n_filter2)
207
"""
208
# Build targets for compute_loss()
209
na, nt = self.na, targets.shape[0] # number of anchors, targets
210
tcls, tbox, indices, anch = [], [], [], []
211
# ttheta, tgaussian_theta = [], []
212
tgaussian_theta = []
213
# gain = torch.ones(7, device=targets.device) # normalized to gridspace gain
214
feature_wh = torch.ones(2, device=targets.device) # feature_wh
215
ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
216
# targets (tensor): (n_gt_all_batch, c) -> (na, n_gt_all_batch, c) -> (na, n_gt_all_batch, c+1)
217
# targets (tensor): (na, n_gt_all_batch, [img_index, clsid, cx, cy, l, s, theta, gaussian_θ_labels, anchor_index]])
218
targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
219
220
g = 0.5 # bias
221
off = torch.tensor([[0, 0], # tensor: (5, 2)
222
[1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
223
# [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
224
], device=targets.device).float() * g # offsets
225
226
for i in range(self.nl):
227
anchors = self.anchors[i]
228
# gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain=[1, 1, w, h, w, h, 1, 1]
229
feature_wh[0:2] = torch.tensor(p[i].shape)[[3, 2]] # xyxy gain=[w_f, h_f]
230
231
# Match targets to anchors
232
# t = targets * gain # xywh featuremap pixel
233
t = targets.clone() # (na, n_gt_all_batch, c+1)
234
t[:, :, 2:6] /= self.stride[i] # xyls featuremap pixel
235
if nt:
236
# Matches
237
r = t[:, :, 4:6] / anchors[:, None] # edge_ls ratio, torch.size(na, n_gt_all_batch, 2)
238
j = torch.max(r, 1 / r).max(2)[0] < self.hyp['anchor_t'] # compare, torch.size(na, n_gt_all_batch)
239
# j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
240
t = t[j] # filter; Tensor.size(n_filter1, c+1)
241
242
# Offsets
243
gxy = t[:, 2:4] # grid xy; (n_filter1, 2)
244
# gxi = gain[[2, 3]] - gxy # inverse
245
gxi = feature_wh[[0, 1]] - gxy # inverse
246
j, k = ((gxy % 1 < g) & (gxy > 1)).T
247
l, m = ((gxi % 1 < g) & (gxi > 1)).T
248
j = torch.stack((torch.ones_like(j), j, k, l, m)) # (5, n_filter1)
249
t = t.repeat((5, 1, 1))[j] # (n_filter1, c+1) -> (5, n_filter1, c+1) -> (n_filter2, c+1)
250
offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j] # (5, n_filter1, 2) -> (n_filter2, 2)
251
else:
252
t = targets[0] # (n_gt_all_batch, c+1)
253
offsets = 0
254
255
# Define, t (tensor): (n_filter2, [img_index, clsid, cx, cy, l, s, theta, gaussian_θ_labels, anchor_index])
256
b, c = t[:, :2].long().T # image, class; (n_filter2)
257
gxy = t[:, 2:4] # grid xy
258
gwh = t[:, 4:6] # grid wh
259
# theta = t[:, 6]
260
gaussian_theta_labels = t[:, 7:-1]
261
gij = (gxy - offsets).long()
262
gi, gj = gij.T # grid xy indices
263
264
# Append
265
a = t[:, -1].long() # anchor indices 取整
266
# indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
267
indices.append((b, a, gj.clamp_(0, feature_wh[1] - 1), gi.clamp_(0, feature_wh[0] - 1))) # image, anchor, grid indices
268
tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
269
anch.append(anchors[a]) # anchors
270
tcls.append(c) # class
271
# ttheta.append(theta) # theta, θ∈[-pi/2, pi/2)
272
tgaussian_theta.append(gaussian_theta_labels)
273
274
# return tcls, tbox, indices, anch
275
return tcls, tbox, indices, anch, tgaussian_theta #, ttheta
276
277