YOLOv3 Loss构建详解

https://blog.csdn.net/wqwqqwqw1231/article/details/90667046添加链接描述
https://blog.csdn.net/weixin_43384257/article/details/100986249
添加链接描述
在这里插入图片描述Loss构建

首先理解一下网络的输出。以y1为例,y1的输出为1313255,表示整张图被分为1313个格子,每个格子预测3个框,每个框的预测信息包括:80个类别+1个框的置信度+2个框的位置偏差+2个框的size偏差。输出可以理解为是1313*(3*(80+1+2+2))。
网格一共是S∗S个,每个网格产生B个候选框anchor box,每个候选框会经过网络最终得到相应的bounding box。最终会得到S∗S∗B个bounding box,那么哪些bounding box会用来计算误差更新权重?又是如何计算误差?需要仔细了解公式。

在这里插入图片描述在这里插入图片描述

首先先看对真值的操作过程。因为真值是框的位置和大小,而要参与计算Loss的真值是框的类别cls,框的真实位置偏移值txy和尺寸偏移值twh。给出target,每一行是一个box的信息:属于batch中的第几张图片(image),类别,位置的尺寸。然后针对不同分辨率的feature map进行处理,以分辨率最小feature map为例:

1、选取box(n个)长宽的真值wh_gt
2、通过与anchor比较,计算IoU,抛去IoU小于一定阈值的框(说明这些框不适用该尺寸的feature map进行预测),留下IoU大于阈值的框(m个)。

以下操作均对留下的框(m个)进行操作(虚线代表的“选取”过程,选取留下的框)

3、提取框位置的真值,并与取整之后的值比较,这个取整后的值对应着feature map中的位置,计算位置偏差的真值(txy)。
4、提取框尺寸的真值,并与对应的anchor的尺寸比较,计算尺寸偏差的真值(twh)
5、记录框的类别真值(cls)
6、记录留下的框对应anchor的id和对应图片的id, 位置取整后的值,这个取整后的值代表着是用13*13中的哪个格子进行预测。(indicies)
在这里插入图片描述
得到要回归的真值之后,与神经网络的输出构建Loss。ouput包含着网络的输出,对应上图1中的y1,y2和y3。图中output[0]对应y1,是经过reshape过后的。output[1]和output[2]做同样处理。下面以output[0]为例,实线箭头代表经过某种操作,过程如下:
1、按照ouput的大小构建tconf,表示框的真实置信度
2、按照真值的indices将对应的某张图片中的某张格子的某个anchor的置信度置1。因为框要由这个图片的这个格子的这个anchor预测,所以这个图片中的这个格子的这个预测的置信度的真值应该为1。
3、将ouput中的值与真值比较构建位置的loss(lxy),尺寸的loss(lwh),类别的loss(lcls),置信度的loss(lconf)。
4、然后加权得到总的Loss
在这里插入图片描述

在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
yolov5 loss.py 代码详解 yolov5 loss.py 是 YOLOv5 模型中的一个关键文件,主要负责计算模型的损失函数。下面是该文件的代码详解: 1. 导入必要的库 ```python import torch import torch.nn.functional as F from torch import nn ``` 2. 定义损失函数类 ```python class YOLOv5Loss(nn.Module): def __init__(self, anchors, strides, iou_threshold, num_classes, img_size): super(YOLOv5Loss, self).__init__() self.anchors = anchors self.strides = strides self.iou_threshold = iou_threshold self.num_classes = num_classes self.img_size = img_size ``` 该类继承自 nn.Module,包含了一些必要的参数,如 anchors,strides,iou_threshold,num_classes 和 img_size。 3. 定义计算损失函数的方法 ```python def forward(self, x, targets=None): bs, _, ny, nx = x.shape # batch size, channels, grid size na = self.anchors.shape[] # number of anchors stride = self.img_size / max(ny, nx) # compute stride yolo_out, grid = [], [] for i in range(3): yolo_out.append(x[i].view(bs, na, self.num_classes + 5, ny, nx).permute(, 1, 3, 4, 2).contiguous()) grid.append(torch.meshgrid(torch.arange(ny), torch.arange(nx))) ny, nx = ny // 2, nx // 2 loss, nGT, nCorrect, mask = , , , torch.zeros(bs, na, ny, nx) for i in range(3): y, g = yolo_out[i], grid[i] y[..., :2] = (y[..., :2].sigmoid() + g) * stride # xy y[..., 2:4] = y[..., 2:4].exp() * self.anchors[i].to(x.device) # wh y[..., :4] *= mask.unsqueeze(-1).to(x.device) y[..., 4:] = y[..., 4:].sigmoid() if targets is not None: na_t, _, _, _, _ = targets.shape t = targets[..., 2:6] * stride gxy = g.unsqueeze().unsqueeze(-1).to(x.device) gi, gj = gxy[..., ], gxy[..., 1] b = t[..., :4] iou = box_iou(b, y[..., :4]) # iou iou_max, _ = iou.max(2) # Match targets to anchors a = torch.arange(na_t).view(-1, 1).repeat(1, na) t = targets[a, iou_max >= self.iou_threshold] # select targets # Compute losses if len(t): # xy loss xy = y[..., :2] - gxy xy_loss = (torch.abs(xy) - .5).pow(2) * mask.unsqueeze(-1).to(x.device) # wh loss wh = torch.log(y[..., 2:4] / self.anchors[i].to(x.device) + 1e-16) wh_loss = F.huber_loss(wh, t[..., 2:4], reduction='none') * mask.unsqueeze(-1).to(x.device) # class loss tcls = t[..., ].long() tcls_onehot = torch.zeros_like(y[..., 5:]) tcls_onehot[torch.arange(len(t)), tcls] = 1 cls_loss = F.binary_cross_entropy(y[..., 5:], tcls_onehot, reduction='none') * mask.unsqueeze(-1).to(x.device) # objectness loss obj_loss = F.binary_cross_entropy(y[..., 4:5], iou_max.unsqueeze(-1), reduction='none') * mask.to(x.device) # total loss loss += (xy_loss + wh_loss + cls_loss + obj_loss).sum() nGT += len(t) nCorrect += (iou_max >= self.iou_threshold).sum().item() mask = torch.zeros(bs, na, ny, nx) if targets is not None: t = targets[..., 2:6] * stride gi, gj = g[..., ], g[..., 1] a = targets[..., 1].long() mask[torch.arange(bs), a, gj, gi] = 1 return loss, nGT, nCorrect ``` 该方法接受输入 x 和 targets,其中 x 是模型的输出,targets 是真实标签。该方法首先根据输入 x 的形状计算出 batch size,channels,grid size 和 number of anchors 等参数,然后根据这些参数计算出 stride 和 grid。接着,该方法将输入 x 分成三个部分,每个部分都包含了 na 个 anchors 和 self.num_classes + 5 个通道。然后,该方法将每个部分的输出转换成合适的形状,并计算出每个 anchor 的中心点坐标和宽高。接着,该方法根据 targets 计算出损失函数,包括 xy loss,wh loss,class loss 和 objectness loss。最后,该方法返回损失函数的值,以及 nGT 和 nCorrect。 4. 定义计算 box iou 的方法 ```python def box_iou(box1, box2): """ Returns the IoU of two bounding boxes """ b1_x1, b1_y1, b1_x2, b1_y2 = box1[..., ], box1[..., 1], box1[..., 2], box1[..., 3] b2_x1, b2_y1, b2_x2, b2_y2 = box2[..., ], box2[..., 1], box2[..., 2], box2[..., 3] inter_rect_x1 = torch.max(b1_x1, b2_x1) inter_rect_y1 = torch.max(b1_y1, b2_y1) inter_rect_x2 = torch.min(b1_x2, b2_x2) inter_rect_y2 = torch.min(b1_y2, b2_y2) inter_area = torch.clamp(inter_rect_x2 - inter_rect_x1 + 1, min=) * torch.clamp(inter_rect_y2 - inter_rect_y1 + 1, min=) b1_area = (b1_x2 - b1_x1 + 1) * (b1_y2 - b1_y1 + 1) b2_area = (b2_x2 - b2_x1 + 1) * (b2_y2 - b2_y1 + 1) iou = inter_area / (b1_area + b2_area - inter_area + 1e-16) return iou ``` 该方法接受两个参数 box1 和 box2,分别表示两个 bounding box 的坐标。该方法首先计算出两个 bounding box 的交集和并集,然后计算出它们的 IoU。 以上就是 yolov5 loss.py 代码的详解
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值