yolov5核心代码: anchor匹配策略,compute_loss和build_targets理解

9 篇文章 0 订阅
3 篇文章 0 订阅

yolov5核心代码理解: anchor匹配策略-跨网格预测,compute_loss(p, targets, model)和build_targets(p, targets, model)理解

本文主要讲述yolov5anchor匹配策略-跨网格预测以及损失函数计算的核心过程理解,网络部分相对容易这里不再赘述。

1. yolov5跨网格匹配策略

yolov5最重要的便是跨网格进行预测,从当前网格的上、下、左、右的四个网格中找到离目标中心点最近的两个网格,再加上当前网格共三个网格进行匹配。增大正样本的数量,加快模型收敛。

 j, k = ((gxy % 1. < g) & (gxy > 1.)).T
 l, m = ((gxy % 1. > (1 - g)) & (gxy < (gain[[2, 3]] - 1.))).T
 # a:anchor索引值,包含添加的正样本(让近于当前网格中心点的上下左右中的两个网格充当正样本)信息
 # t: gt框信息, 包含添加的正样本
 # offsets: 每个框中心点的偏移值
 a, t = torch.cat((a, a[j], a[k], a[l], a[m]), 0), torch.cat((t, t[j], t[k], t[l], t[m]), 0)
 offsets = torch.cat((z, z[j] + off[0], z[k] + off[1], z[l] + off[2], z[m] + off[3]), 0) * g

yolov5预测bbox公式如下:
在这里插入图片描述

  • tx,ty,tw,th:预测的坐标信息
  • bx,xy,bw,bh: 最终预测坐标信息
  • б:表示sigmoid,将坐标归一化到0~1
  • cx,cy: 中心点所在的网格的左上角坐标
  • pw,py: anchor框的大小

代码如下:

pxy = ps[:, :2].sigmoid() * 2. - 0.5
pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]

2. yolov5核心代码compute_loss和build_targets理解


def compute_loss(p, targets, model):  # predictions, targets, model
    # p 预测结果, list[torch.tensor * 3], p[i] = (b, 3, h, w, nc + 5[x,y,w,h,conf])  --- h,w (80, 80)、(40, 40)、 (20, 20)

    ft = torch.cuda.FloatTensor if p[0].is_cuda else torch.Tensor
    lcls, lbox, lobj = ft([0]), ft([0]), ft([0])
    tcls, tbox, indices, anchors = build_targets(p, targets, model)  # 类别,box, 索引, anchors
    h = model.hyp  # hyperparameters
    red = 'mean'  # Loss reduction (sum or mean)

    # Define criteria, 类别和目标损失
    BCEcls = nn.BCEWithLogitsLoss(pos_weight=ft([h['cls_pw']]), reduction=red)
    BCEobj = nn.BCEWithLogitsLoss(pos_weight=ft([h['obj_pw']]), reduction=red)

    # 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)

    # per output
    nt = 0  # targets
    for i, pi in enumerate(p):  # layer index, layer predictions
        b, a, gj, gi = indices[i]  # image, anchor, gridy, gridx
        tobj = torch.zeros_like(pi[..., 0])  # target obj

        nb = b.shape[0]  # number of targets
        if nb:
            nt += nb  # cumulative targets
            # 取出对应位置预测值
            ps = pi[b, a, gj, gi]  # prediction subset corresponding to targets

            # GIoU
            pxy = ps[:, :2].sigmoid() * 2. - 0.5
            pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]
            pbox = torch.cat((pxy, pwh), 1)  # predicted box
            giou = bbox_iou(pbox.t(), tbox[i], x1y1x2y2=False, GIoU=True)  # giou(prediction, target)
            lbox += (1.0 - giou).sum() if red == 'sum' else (1.0 - giou).mean()  # giou loss

            # Obj 有物体的conf分支权重
            tobj[b, a, gj, gi] = (1.0 - model.gr) + model.gr * giou.detach().clamp(0).type(tobj.dtype)  # giou ratio

            # Class
            if model.nc > 1:  # cls loss (only if multiple classes)
                t = torch.full_like(ps[:, 5:], cn)  # targets
                t[range(nb), tcls[i]] = cp
                lcls += BCEcls(ps[:, 5:], t)  # BCE 每个类单独计算Loss

            # 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)]

        lobj += BCEobj(pi[..., 4], tobj)  # obj loss

    lbox *= h['giou']
    lobj *= h['obj']
    lcls *= h['cls']
    bs = tobj.shape[0]  # batch size
    if red == 'sum':
        g = 3.0  # loss gain
        lobj *= g / bs
        if nt:
            lcls *= g / nt / model.nc
            lbox *= g / nt

    loss = lbox + lobj + lcls
    return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()


def build_targets(p, targets, model):
    # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
    # 获取检测层
    det = model.module.model[-1] if type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel) \
        else model.model[-1]  # Detect() module
    na, nt = det.na, targets.shape[0]  # number of anchors, targets
    tcls, tbox, indices, anch = [], [], [], []
    gain = torch.ones(6, device=targets.device)  # normalized to gridspace gain
    # 上下左右四个网格
    off = torch.tensor([[1, 0], [0, 1], [-1, 0], [0, -1]], device=targets.device).float()  # overlap offsets
    # anchor索引,表示当前bbox和当前层哪个anchor匹配
    at = torch.arange(na).view(na, 1).repeat(1, nt)  # anchor tensor, same as .repeat_interleave(nt)

    style = 'rect4'
    #   处理每个检测层(三个)
    for i in range(det.nl):
        # 三个anchors,已经除以当前特征图对应的stride
        anchors = det.anchors[i]
        # 将target中归一化后的xywh映射到三个尺度(80,80, 40,40, 20,20)的输出需要的系数
        gain[2:] = torch.tensor(p[i].shape)[[3, 2, 3, 2]]  # xyxy gain

        # Match targets to anchors
        # t 将标签框的xywh从基于0-1映射到基于特征图,target的xywh本身是归一化尺度,需要变成特征图尺寸
        # t GT框 shape:(nt, 6) , 6 = icxywh, i 指第i+1张图片,c为类别
        a, t, offsets = [], targets * gain, 0
        # 判断是否存在目标
        if nt:
            # 计算当前tartget的wh和anchor的wh比值
            # 如果最大比值大于预设值model.hyp['anchor_t']=4,则当前target和anchor匹配度不高,不强制回归,而把target丢弃
            r = t[None, :, 4:6] / anchors[:, None]  # wh ratio
            # 筛选满足条件1/hyp['anchor_t] < target_wh / anchor_wh < hyp['anchor_t]的框
            #.max(2)对第三维度的值进行max
            j = torch.max(r, 1. / r).max(2)[0] < model.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.repeat(na, 1, 1)是的t内的gtbox信息与at索引相对应, repeat(3,1,1)第一维度重复三次
            # a 筛选后的gtbox的anchor索引, 筛选后的gtbox信息
            a, t = at[j], t.repeat(na, 1, 1)[j]  # filter

            # overlaps
            gxy = t[:, 2:4]  # grid xy,label的中心点坐标
            z = torch.zeros_like(gxy)
            # 取得上下左右四个网格中近于当前网格中心点中的其中两个
            """把相对于各个网格左上角x<0.5,y<0.5和相对于右下角的x<0.5,y<0.5的框提取出来,就是j,k,l,m
            在选取gij(标签分配的网格)的时候对这四个部分都做一个偏移(加去上面的off),
            """
            if style == 'rect2':
                g = 0.2  # offset
                j, k = ((gxy % 1. < g) & (gxy > 1.)).T
                a, t = torch.cat((a, a[j], a[k]), 0), torch.cat((t, t[j], t[k]), 0)
                offsets = torch.cat((z, z[j] + off[0], z[k] + off[1]), 0) * g

            elif style == 'rect4':
                g = 0.5  # offset
                # 对于筛选后的bbox,计算其落在哪个网格内,同时找出邻近的网格,将这些网格都认为是负责预测该bbox的网格
                # 浮点数取模的数学定义:对于两个浮点数a和b: a / b = a - n * b , 其中n为不超过 a/b的最大整数
                # gxy > 1.和gxy < (gain[[2, 3]] - 1.)判断中心点是否落在四个角,如果落在四个角,就不取界外的框(因为超出了边界)
                j, k = ((gxy % 1. < g) & (gxy > 1.)).T
                l, m = ((gxy % 1. > (1 - g)) & (gxy < (gain[[2, 3]] - 1.))).T
                # a:anchor索引值,包含添加的正样本(让近于当前网格中心点的上下左右中的两个网格充当正样本)信息
                # t: gt框信息, 包含添加的正样本
                # offsets: 每个框中心点的偏移值

                a, t = torch.cat((a, a[j], a[k], a[l], a[m]), 0), torch.cat((t, t[j], t[k], t[l], t[m]), 0)
                offsets = torch.cat((z, z[j] + off[0], z[k] + off[1], z[l] + off[2], z[m] + off[3]), 0) * g

        # Define
        """
        对每个bbox找出对应的正样本anchor。
        a 表示当前bbox和当前层的第几个anchor匹配
        b 表示当前bbox属于batch内部的第几张图片,
        c 是该bbox的类别
        gi,gj 是对应的负责预测该bbox的网格坐标
        gxy 负责预测网格中心点坐标xy
        gwh 是对应的bbox的wh
        """
        b, c = t[:, :2].long().T  # image, class
        gxy = t[:, 2:4]  # grid xy
        gwh = t[:, 4:6]  # grid wh
        # 当前label落在哪个网格上
        gij = (gxy - offsets).long()
        gi, gj = gij.T  # grid xy indices

        # Append 添加索引,方便计算损失的时候去除对应位置的输出
        indices.append((b, a, gj, gi))  # image, anchor, grid indices
        # gxy - gij: 预测中心点坐标相对于gi,gj的偏移值
        tbox.append(torch.cat((gxy - gij, gwh), 1))  # box
        anch.append(anchors[a])  # anchors,使用哪个anchor尺寸
        tcls.append(c)  # class

    return tcls, tbox, indices, anch

3. 总结

yolov5增加正样本的方法,最多可增大到原来的三倍,大大增加了正样本的数量,加速了模型的收敛。
目标检测重中之重可以理解为anchor的匹配策略,当下流行的anchor-free不过换了一种匹配策略罢了。
我想当下真正可创新之处在于更优的匹配策略。
鄙人拙见,请不吝指教。

  • 5
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值