首頁 > 軟體

YOLOV5程式碼詳解之損失函數的計算

2022-03-28 13:00:43

摘要:

神經網路的訓練的主要流程包括影象輸入神經網路, 得到模型的輸出結果,計算模型的輸出與真實值的損失, 計算損失值的梯度,最後用梯度下降演演算法更新模型引數。損失函數值的計算是非常關鍵的一個步驟。

本部落格將對yolov5損失值的計算過程程式碼的實現做簡要的理解。

def compute_loss(p, targets, model):  # predictions, targets, model
    device = targets.device
    lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
    tcls, tbox, indices, anchors = build_targets(p, targets, model)  # targets
    h = model.hyp  # hyperparameters

    # Define criteria
    BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.Tensor([h['cls_pw']])).to(device)
    BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.Tensor([h['obj_pw']])).to(device)

    # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
    cp, cn = smooth_BCE(eps=0.0)

    # Focal loss
    g = h['fl_gamma']  # focal loss gamma
    if g > 0:
        BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
   。。。。。。

yolov5程式碼用IOU指標評價目標框和預測框的位置損失損失。yolov5程式碼用nn.BCEWithLogitsLoss或FocalLoss評價目標框和預測框的類損失和置信度損失 .

yolov5程式碼用寬高比選擇對應真實框的預測框,且每一個真實框對應三個預測框 。

1、位置損失

yolov5程式碼用IOU值評價預測框和真實框的位置損失, 本文介紹CIoU指標.

公式如下截圖:

公式中引數代表的意義如下:

IOU: 預測框和真實框的叫並比

v是衡量長寬比一致性的引數,我們也可以定義為:

程式碼實現:

iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True)  # iou(prediction, target)
            lbox += (1.0 - iou).mean()  # iou loss
def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-9):
    # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4
    box2 = box2.T

    # Get the coordinates of bounding boxes
    if x1y1x2y2:  # x1, y1, x2, y2 = box1
        b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
        b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
    else:  # transform from xywh to xyxy
        b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2
        b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2
        b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2
        b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2

    # Intersection area
    inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * 
            (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)

    # Union Area
    w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
    w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
    union = w1 * h1 + w2 * h2 - inter + eps

    iou = inter / union
    if GIoU or DIoU or CIoU:
        cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1)  # convex (smallest enclosing box) width
        ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1)  # convex height
        if CIoU or DIoU:  # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
            c2 = cw ** 2 + ch ** 2 + eps  # convex diagonal squared
            rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 +
                    (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4  # center distance squared
            if DIoU:
                return iou - rho2 / c2  # DIoU
            elif CIoU:  # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
                v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)
                with torch.no_grad():
                    alpha = v / ((1 + eps) - iou + v)
                return iou - (rho2 / c2 + v * alpha)  # CIoU
        else:  # GIoU https://arxiv.org/pdf/1902.09630.pdf
            c_area = cw * ch + eps  # convex area
            return iou - (c_area - union) / c_area  # GIoU
    else:
        return iou  # IoU

2、置信度損失和類損失

yolov5程式碼用nn.BCEWithLogitsLoss或FocalLoss評價目標框和預測框的類損失和置信度損失,本節一一介紹這兩個損失函數。

  • nn.BCEWithLogitsLoss:

首先對預測輸出作sigmoid變換,然後求變換後的結果與真實值的二值交叉熵.

假設預測輸出是3分類,預測輸出:

預測輸出sigmoid變換:

假設真實輸出是:

兩者的二值交叉熵的計算方法:

介面函數驗證下上面的結果:

  • FocalLoss損失:

FocalLoss損失考慮的是:目標檢測中正負樣本嚴重不均衡的一種策略。該損失函數的設計思想類似於boosting,降低容易分類的樣本對損失函數的影響,注重較難分類的樣本的訓練.

簡而言之,FocalLoss更加關注的是比較難分的樣本,何謂難分?若某一個真實類預測的概率只有0.2,我們認為它比較難分,相反若該真實類的預測概率是0.95,則容易分類.

FocalLoss通過提高難分類別的損失函數來實現,公式如下:

影象如下:

可以看出預測真實類概率越大,則損失函數越小,即實現了之前的想法.

為了能夠平衡正負樣本的重要性,我們可以給各個類別新增一個權重常數 α ,比如想使正樣本初始權重為0.8,負樣本就為0.2.
程式碼實現為:

class FocalLoss(nn.Module):
    # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
    def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
        super(FocalLoss, self).__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)
        # 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
        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

其中成員函數loss_fcn為nn.BCEWithLogitsLoss。

總結

到此這篇關於YOLOV5程式碼詳解之損失函數計算的文章就介紹到這了,更多相關YOLOV5損失函數計算內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com