loss
loss部分的代码虽然很少,但是它的难度很大,要结合yolov5的损失函数一起去查看,这样会更加容易理解。
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Loss functions
"""
import torch
import torch.nn as nn
from utils.metrics import bbox_iou
from utils.torch_utils import de_parallel
def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
# return positive, negative label smoothing BCE targets
"""
普通的BCE损失非常依赖样本标记的正确率,如果某个样本标记错误,比如把正样本标记成负样本,那么会带来很大的误差。
而smoothBCE可以有效的减少由于样本标记错误带来的误差。如果看过SVM算法的话,感觉有点类似于硬间隔和软间隔
# 可以看这篇博客讲解label_smooth https://blog.csdn.net/racesu/article/details/107214035?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0-107214035-blog-123999241.pc_relevant_default&spm=1001.2101.3001.4242.1&utm_relevant_index=2
"""
return 1.0 - 0.5 * eps, 0.5 * eps
class BCEBlurWithLogitsLoss(nn.Module):
# BCEwithLogitLoss() with reduced missing label effects.
def __init__(self, alpha=0.05):
super().__init__()
self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss()
self.alpha = alpha
def forward(self, pred, true):
loss = self.loss_fcn(pred, true)
pred = torch.sigmoid(pred) # prob from logits
dx = pred - true # reduce only missing label effects
# dx = (pred - true).abs() # reduce missing label and false label effects
alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
loss *= alpha_factor
return loss.mean()
class FocalLoss(nn.Module):
# Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
# FocalLoss 可以先看这篇博客把focalloss理解了,再来看以下的代码 https://blog.csdn.net/qq_42363032/article/details/121573416
"""
在focalloss里面,我们关注两个参数,alpha和gamma 一个用来控制正负样本的权重,一个用来控制易难样本的权重
"""
def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
super().__init__()
# sigmoid+BCELOSS
self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
self.gamma = gamma
self.alpha = alpha
self.reduction = loss_fcn.reduction
"""
当使用的参数为 mean(在pytorch1.7.1中elementwise_mean已经弃用)会对N个样本的loss进行平均之后返回
当使用的参数为 sum会对N个样本的loss求和
表示直接返回n分样本的loss
"""
self.loss_fcn.reduction = 'none' # required to apply FL to each element
def forward(self, pred, true):
loss = self.loss_fcn(pred, true)
# p_t = torch.exp(-loss)
# loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
# TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
# 只要把公式理解了,这里就是对公式进行代码的编写
pred_prob = torch.sigmoid(pred) # prob from logits
# 对pt进行代码编写 true是真实的便签,别被其他语言 搞混了
p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
modulating_factor = (1.0 - p_t) ** self.gamma
loss *= alpha_factor * modulating_factor
if self.reduction == 'mean':
return loss.mean()
elif self.reduction == 'sum':
return loss.sum()
else: # 'none'
return loss
class QFocalLoss(nn.Module):
# Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
# QFocalLoss我没有看过,可以看完论文之后再来看这里的代码
def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
super().__init__()
self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
self.gamma = gamma
self.alpha = alpha
self.reduction = loss_fcn.reduction
self.loss_fcn.reduction = 'none' # required to apply FL to each element
def forward(self, pred, true):
loss = self.loss_fcn(pred, true)
pred_prob = torch.sigmoid(pred) # prob from logits
alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
modulating_factor = torch.abs(true - pred_prob) ** self.gamma
loss *= alpha_factor * modulating_factor
if self.reduction == 'mean':
return loss.mean()
elif self.reduction == 'sum':
return loss.sum()
else: # 'none'
return loss
class ComputeLoss:
sort_obj_iou = False
# Compute losses
def __init__(self, model, autobalance=False):
device = next(model.parameters()).device # get model device
h = model.hyp # hyperparameters
# Define criteria
# 如果正负样本不均衡,我们可以给正负样本不同的权重,pos_weight代表的是正样本的权重
BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
# Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
# 这里使用的就是label_smooth损失,比起BCE的效果要好
self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
# Focal loss
# 获取fl_gamma参数,如果大于0的时候采用focalloss,否则使用BCE
g = h['fl_gamma'] # focal loss gamma
if g > 0:
BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
m = de_parallel(model).model[-1] # Detect() module
#
self.balance = {3: [4.0, 1.0, 0.4]}.get(m.nl, [4.0, 1.0, 0.25, 0.06, 0.02]) # P3-P7
self.ssi = list(m.stride).index(16) if autobalance else 0 # stride 16 index
self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance
self.na = m.na # number of anchors
self.nc = m.nc # number of classes
self.nl = m.nl # number of layers 检测头的个数,默认是三个检测头
self.anchors = m.anchors
self.device = device
def __call__(self, p, targets): # predictions, targets
lcls = torch.zeros(1, device=self.device) # class loss
lbox = torch.zeros(1, device=self.device) # box loss
lobj = torch.zeros(1, device=self.device) # object loss
tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets
# Losses
for i, pi in enumerate(p): # layer index, layer predictions
b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
tobj = torch.zeros(pi.shape[:4], dtype=pi.dtype, device=self.device) # target obj
n = b.shape[0] # number of targets
if n:
# pxy, pwh, _, pcls = pi[b, a, gj, gi].tensor_split((2, 4, 5), dim=1) # faster, requires torch 1.8.0
pxy, pwh, _, pcls = pi[b, a, gj, gi].split((2, 2, 1, self.nc), 1) # target-subset of predictions
# Regression
# 有目标的情况,我们对obj计算误差
# bx = (2*σ(offsetX)−0.5)+gridX
# by = (2*σ(offsetY)−0.5)+gridY
pxy = pxy.sigmoid() * 2 - 0.5
# 计算bw和bh 由于这是 pwh = (pwh.sigmoid() * 2) ** 2 的值域范围在-4~4之间
pwh = (pwh.sigmoid() * 2) ** 2 * anchors[i]
pbox = torch.cat((pxy, pwh), 1) # predicted box
iou = bbox_iou(pbox, tbox[i], CIoU=True).squeeze() # iou(prediction, target)
lbox += (1.0 - iou).mean() # iou loss
# Objectness
# iou不更新梯度,它只是我们选择的一个标准
iou = iou.detach().clamp(0).type(tobj.dtype)
if self.sort_obj_iou:
j = iou.argsort()
b, a, gj, gi, iou = b[j], a[j], gj[j], gi[j], iou[j]
if self.gr < 1:
iou = (1.0 - self.gr) + self.gr * iou
tobj[b, a, gj, gi] = iou # iou ratio
# Classification
if self.nc > 1: # cls loss (only if multiple classes)
t = torch.full_like(pcls, self.cn, device=self.device) # targets
t[range(n), tcls[i]] = self.cp
lcls += self.BCEcls(pcls, t) # BCE
# Append targets to text file
# with open('targets.txt', 'a') as file:
# [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
obji = self.BCEobj(pi[..., 4], tobj)
lobj += obji * self.balance[i] # obj loss
if self.autobalance:
self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
if self.autobalance:
self.balance = [x / self.balance[self.ssi] for x in self.balance]
# 根据超参数对各个loss进行平衡
lbox *= self.hyp['box']
lobj *= self.hyp['obj']
lcls *= self.hyp['cls']
bs = tobj.shape[0] # batch size
# loss的参数不需要梯度传播,网络只是通过loss的值来进行更新参数
return (lbox + lobj + lcls) * bs, torch.cat((lbox, lobj, lcls)).detach()
def build_targets(self, p, targets):
"""
return
tcls, 预测的cls
tbox, 预测的box
indices,
anch, 预测框
"""
# nt: [image_index,class ,x, y, w, h]
na, nt = self.na, targets.shape[0] # number of anchors, targets
tcls, tbox, indices, anch = [], [], [], []
gain = torch.ones(7, device=self.device) # normalized to gridspace gain
# ai 维度 = [na, nt] 并且是从0->na 即 ai[0,:]全为零 ai[1,:]全为一,相当于给ai一个anchor索引,
# x.repeat(a,b) 先把列乘以b倍,再把行乘以a倍
ai = torch.arange(na, device=self.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
# targets = [na, nt, 7]
# x.repeat(a,b,c) 同列先把第三维度乘以c倍,再把第二维度乘以b倍,再把第一位都乘以a倍
# ai[..., None] 相当于给增加最后一维 ai [na, nt]->[na, ne, 1] 之后再使用cat拼接,dim=2
"""
targets.repeat(na, 1, 1) targets[22,6],因为他是从后往前执行的,如果维度不够会自动扩充维度。[na,1,1(2)]先把6这个维度进行乘以1(2)倍,因为维度足够,再把第一次结果的值因为维度没有变化还是[22,6]([22,12])乘以1倍,最后因为维度不够,需要扩充维度再乘以na倍,所以经过处理过后
targets.repeat(na, 1, 1)-> [na,nt,6]
ai[..., None])->[na,nt,1]
torch.cat((targets.repeat(na, 1, 1), ai[..., None]), 2)->[na, nt,7]
"""
targets = torch.cat((targets.repeat(na, 1, 1), ai[..., None]), 2) # append anchor indices
g = 0.5 # bias
# 这个偏移是为了预测误差时候用的,因为在yolov5当中,不单单是一个网格来预测,而是在他的上下左右一起来预测
off = torch.tensor(
[
[0, 0],
[1, 0],
[0, 1],
[-1, 0],
[0, -1], # j,k,l,m
# [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
],
device=self.device).float() * g # offsets
for i in range(self.nl):
# 别搞混, Detect层有三个检测头,每个检测头有三个候选框
# 当前feature map 所对应的anchors 每个anchors[w,h]
# yoloV5 为3个anchors 即 anchors = [3,2]
anchors = self.anchors[i]
# 现在gain [1,1,w,h,w,h,1]
# p代表当前特征层的shape,默认是80*80, 40*40, 20*20
gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
# Match targets to anchors
# 将targets给缩放一下,之前是归一化的结果,现在直接相乘,便得到了在改网格下的结果 注意,这里使用了python的广播机制
t = targets * gain # shape(3,n,7)
if nt:
# Matches
# anchors[:,None] = [3,1,2] 把正样本与宽高做比较(w/w, h/h)
r = t[..., 4:6] / anchors[:, None] # wh ratio
# .max(2) 返回两个值,一个是value 一个是index
# 筛选掉一些不满足的预测框
j = torch.max(r, 1 / r).max(2)[0] < self.hyp['anchor_t'] # compare
# j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
t = t[j] # 过滤掉比预设小的样本
# Offsets
gxy = t[:, 2:4] # target中心点的相对于左上角的坐标
gxi = gain[[2, 3]] - gxy # target中心点相对于右下角的坐标
# 判断是否把 左,上格子 也当作该目标进行训练
j, k = ((gxy % 1 < g) & (gxy > 1)).T
# 判断是否把 右,下格子 也当作该目标进行训练
l, m = ((gxi % 1 < g) & (gxi > 1)).T
# (torch.ones_like(j)中心网格的格子,永远为正,j,k,l,m 分别代表左上右下的格子
j = torch.stack((torch.ones_like(j), j, k, l, m))
# repeat函数 第一个参数是重复的次数, 第二个是列重复的倍数,第三个是行重复的倍数
# 现在就是将t给重复五遍,分别得到中心,左,上,右,下
t = t.repeat((5, 1, 1))[j]
# offsets代表中心,左上右下的偏移量
offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
else:
t = targets[0]
offsets = 0
# Define
# a表示了是属于哪一个预测框
bc, gxy, gwh, a = t.chunk(4, 1) # (image, class), grid xy, grid wh, anchors
a, (b, c) = a.long().view(-1), bc.long().T # anchors, image, class
gij = (gxy - offsets).long()
gi, gj = gij.T # grid indices
# Append
# gj.clamp_(min,max) 把gj压缩到min和max这个区间范围之内
# b: img_index a: anchors gj和gi表示相对于左上角的h,w
indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
anch.append(anchors[a]) # anchors
tcls.append(c) # class
return tcls, tbox, indices, anch