当前位置:   article > 正文

YOLO V7源码解析_yolov7代码

yolov7代码

1.命令行参数介绍

YOLO v7参数与YOLO v5差不多,我就直接将YOLO v5命令行参数搬过来了,偷个懒 

  1. --weights:初始权重
  2. --cfg:模型配置文件
  3. --data:数据配置文件
  4. --hyp:学习率等超参数文件
  5. --epochs:迭代次数
  6. -imgsz:图像大小
  7. --rect:长方形训练策略,不resize成正方形,使用灰条进行图片填充,防止图片失真
  8. --resume:恢复最近的培训,从last.pt开始
  9. --nosave:只保存最后的检查点
  10. --noval:仅在最后一次epochs进行验证
  11. --noautoanchor:禁用AutoAnchor
  12. --noplots:不保存打印文件
  13. --evolve:为x个epochs进化超参数
  14. --bucket:上传操作,这个参数是 yolov5 作者将一些东西放在谷歌云盘,可以进行下载
  15. --cache:在ram或硬盘中缓存数据
  16. --image-weights:测试过程中,图像的那些测试地方不太好,对这些不太好的地方加权重
  17. --single-cls:单类别标签置0
  18. --device:gpu设置
  19. --multi-scale:改变img大小+/-50%,能够被32整除
  20. --optimizer:学习率优化器
  21. --sync-bn:使用SyncBatchNorm,仅在DDP模式中支持,跨gpu时使用
  22. --workers:最大 dataloader 的线程数 (per RANK in DDP mode)
  23. --project:保存文件的地址
  24. --name:保存日志文件的名称
  25. --exist-ok:对项目名字是否进行覆盖
  26. --quad:在dataloader时采用什么样的方式读取我们的数据,1280的大图像可以指定
  27. --cos-lr:余弦学习率调度
  28. --label-smoothing:
  29. --patience:经过多少个epoch损失不再下降,就停止迭代
  30. --freeze:迁移学习,冻结训练
  31. --save-period:每x个周期保存一个检查点(如果<1,则禁用)
  32. --seed:随机种子
  33. --local_rank:gpu编号
  34. --entity:可视化访问信息
  35. --quad:
  36. 四元数据加载器是我们认为的一个实验性功能,它可能允许在较低 --img 尺寸下进行更高 --img 尺寸训练的一些好处。
  37. 此四元整理功能会将批次从 16x3x640x640 重塑为 4x3x1280x1280,这不会产生太大影响 本身,因为它只是重新排列批次中的马赛克,
  38. 但有趣的是允许批次中的某些图像放大 2 倍(每个四边形中的 4 个马赛克中的一个放大 2 倍,其他 3 个马赛克被删除)

2.训练策略 

ema:移动平均法,在更新参数的时候我们希望更平稳一些,考虑的步骤更多一些。公式为:v_{t}=\beta v_{t-1}+(1-\beta)v_{t-1},当系数为\beta时,相当于考虑1/(1-\beta )步更新的梯度,YOLO v7默认\beta

为0.999,相当于考虑1000步更新的梯度

3.网络结构

E-ELAN:

 如下图所示,配置文件的部分就是E-ELAN模块,有四条路径,分别经过1个卷积、1个卷积、3个卷积和5个卷积,其中有3条路径共享了特征图。最后,对四条路径的特征图进行拼接。经过E-ELAN后,相较于输入,特征图通道数加倍。        

  

 

 MPCONV:

        对于MPconv,也分为两条路径,一条经过Maxpooling层,另一条路径经过卷积进行下采样,可以理解为综合考虑卷积和池化的下采样结果,以提升性能。最后,对特征图进行拼接。

SPPCSPC:

        YOLO v7还是采用了SPP的思想,首先对特征图经过3次卷积,然后分别经过5*5,9*9,13*13的池化,需要注意的是,将5*5与9*9最大池化的特征图进行ADD操作,与13*13和原特征图进行拼接,经过不同kenel_size的池化,实现了对不同感受野的特征融合。然后再经过2次卷积,与经过一次卷积的特征图进行拼接。

代码如下: 

  1. class SPPCSPC(nn.Module):
  2. # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks
  3. def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5, k=(5, 9, 13)):
  4. super(SPPCSPC, self).__init__()
  5. c_ = int(2 * c2 * e) # hidden channels
  6. self.cv1 = Conv(c1, c_, 1, 1)
  7. self.cv2 = Conv(c1, c_, 1, 1)
  8. self.cv3 = Conv(c_, c_, 3, 1)
  9. self.cv4 = Conv(c_, c_, 1, 1)
  10. self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
  11. self.cv5 = Conv(4 * c_, c_, 1, 1)
  12. self.cv6 = Conv(c_, c_, 3, 1)
  13. self.cv7 = Conv(2 * c_, c2, 1, 1)
  14. def forward(self, x):
  15. x1 = self.cv4(self.cv3(self.cv1(x)))
  16. y1 = self.cv6(self.cv5(torch.cat([x1] + [m(x1) for m in self.m], 1)))
  17. y2 = self.cv2(x)
  18. return self.cv7(torch.cat((y1, y2), dim=1))

PAN:

         yolo v7还是采用了YOLO v5的PAN,经过SPPCSPC层后的特征图不断进行上采样,并与低层信息进行融合,实现了低层信息和高层信息的特征融合,然后进行下采样,与低层进行特征融合,实现了高层信息与低层信息的特征融合。

HEAD:

        head部分首先经过一层repconv,由3条路径组成,1层1*1的卷积、1层3*3的卷积和1层BN层。 经过repconv后,经过输出层输出结果

代码如下:

  1. class RepConv(nn.Module):
  2. # Represented convolution
  3. # https://arxiv.org/abs/2101.03697
  4. def __init__(self, c1, c2, k=3, s=1, p=None, g=1, act=True, deploy=False):
  5. super(RepConv, self).__init__()
  6. self.deploy = deploy
  7. self.groups = g
  8. self.in_channels = c1
  9. self.out_channels = c2
  10. assert k == 3
  11. assert autopad(k, p) == 1
  12. padding_11 = autopad(k, p) - k // 2
  13. self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
  14. if deploy:
  15. self.rbr_reparam = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=True)
  16. else:
  17. self.rbr_identity = (nn.BatchNorm2d(num_features=c1) if c2 == c1 and s == 1 else None)
  18. self.rbr_dense = nn.Sequential(
  19. nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False),
  20. nn.BatchNorm2d(num_features=c2),
  21. )
  22. self.rbr_1x1 = nn.Sequential(
  23. nn.Conv2d( c1, c2, 1, s, padding_11, groups=g, bias=False),
  24. nn.BatchNorm2d(num_features=c2),
  25. )
  26. def forward(self, inputs):
  27. if hasattr(self, "rbr_reparam"):
  28. return self.act(self.rbr_reparam(inputs))
  29. if self.rbr_identity is None:
  30. id_out = 0
  31. else:
  32. id_out = self.rbr_identity(inputs)
  33. return self.act(self.rbr_dense(inputs) + self.rbr_1x1(inputs) + id_out)
  34. def get_equivalent_kernel_bias(self):
  35. kernel3x3, bias3x3 = self._fuse_bn_tensor(self.rbr_dense)
  36. kernel1x1, bias1x1 = self._fuse_bn_tensor(self.rbr_1x1)
  37. kernelid, biasid = self._fuse_bn_tensor(self.rbr_identity)
  38. return (
  39. kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid,
  40. bias3x3 + bias1x1 + biasid,
  41. )
  42. def _pad_1x1_to_3x3_tensor(self, kernel1x1):
  43. if kernel1x1 is None:
  44. return 0
  45. else:
  46. return nn.functional.pad(kernel1x1, [1, 1, 1, 1])
  47. def _fuse_bn_tensor(self, branch):
  48. if branch is None:
  49. return 0, 0
  50. if isinstance(branch, nn.Sequential):
  51. kernel = branch[0].weight
  52. running_mean = branch[1].running_mean
  53. running_var = branch[1].running_var
  54. gamma = branch[1].weight
  55. beta = branch[1].bias
  56. eps = branch[1].eps
  57. else:
  58. assert isinstance(branch, nn.BatchNorm2d)
  59. if not hasattr(self, "id_tensor"):
  60. input_dim = self.in_channels // self.groups
  61. kernel_value = np.zeros(
  62. (self.in_channels, input_dim, 3, 3), dtype=np.float32
  63. )
  64. for i in range(self.in_channels):
  65. kernel_value[i, i % input_dim, 1, 1] = 1
  66. self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)
  67. kernel = self.id_tensor
  68. running_mean = branch.running_mean
  69. running_var = branch.running_var
  70. gamma = branch.weight
  71. beta = branch.bias
  72. eps = branch.eps
  73. std = (running_var + eps).sqrt()
  74. t = (gamma / std).reshape(-1, 1, 1, 1)
  75. return kernel * t, beta - running_mean * gamma / std
  76. def repvgg_convert(self):
  77. kernel, bias = self.get_equivalent_kernel_bias()
  78. return (
  79. kernel.detach().cpu().numpy(),
  80. bias.detach().cpu().numpy(),
  81. )
  82. def fuse_conv_bn(self, conv, bn):
  83. std = (bn.running_var + bn.eps).sqrt()
  84. bias = bn.bias - bn.running_mean * bn.weight / std
  85. t = (bn.weight / std).reshape(-1, 1, 1, 1)
  86. weights = conv.weight * t
  87. bn = nn.Identity()
  88. conv = nn.Conv2d(in_channels = conv.in_channels,
  89. out_channels = conv.out_channels,
  90. kernel_size = conv.kernel_size,
  91. stride=conv.stride,
  92. padding = conv.padding,
  93. dilation = conv.dilation,
  94. groups = conv.groups,
  95. bias = True,
  96. padding_mode = conv.padding_mode)
  97. conv.weight = torch.nn.Parameter(weights)
  98. conv.bias = torch.nn.Parameter(bias)
  99. return conv
  100. def fuse_repvgg_block(self):
  101. if self.deploy:
  102. return
  103. print(f"RepConv.fuse_repvgg_block")
  104. self.rbr_dense = self.fuse_conv_bn(self.rbr_dense[0], self.rbr_dense[1])
  105. self.rbr_1x1 = self.fuse_conv_bn(self.rbr_1x1[0], self.rbr_1x1[1])
  106. rbr_1x1_bias = self.rbr_1x1.bias
  107. weight_1x1_expanded = torch.nn.functional.pad(self.rbr_1x1.weight, [1, 1, 1, 1])
  108. # Fuse self.rbr_identity
  109. if (isinstance(self.rbr_identity, nn.BatchNorm2d) or isinstance(self.rbr_identity, nn.modules.batchnorm.SyncBatchNorm)):
  110. # print(f"fuse: rbr_identity == BatchNorm2d or SyncBatchNorm")
  111. identity_conv_1x1 = nn.Conv2d(
  112. in_channels=self.in_channels,
  113. out_channels=self.out_channels,
  114. kernel_size=1,
  115. stride=1,
  116. padding=0,
  117. groups=self.groups,
  118. bias=False)
  119. identity_conv_1x1.weight.data = identity_conv_1x1.weight.data.to(self.rbr_1x1.weight.data.device)
  120. identity_conv_1x1.weight.data = identity_conv_1x1.weight.data.squeeze().squeeze()
  121. # print(f" identity_conv_1x1.weight = {identity_conv_1x1.weight.shape}")
  122. identity_conv_1x1.weight.data.fill_(0.0)
  123. identity_conv_1x1.weight.data.fill_diagonal_(1.0)
  124. identity_conv_1x1.weight.data = identity_conv_1x1.weight.data.unsqueeze(2).unsqueeze(3)
  125. # print(f" identity_conv_1x1.weight = {identity_conv_1x1.weight.shape}")
  126. identity_conv_1x1 = self.fuse_conv_bn(identity_conv_1x1, self.rbr_identity)
  127. bias_identity_expanded = identity_conv_1x1.bias
  128. weight_identity_expanded = torch.nn.functional.pad(identity_conv_1x1.weight, [1, 1, 1, 1])
  129. else:
  130. # print(f"fuse: rbr_identity != BatchNorm2d, rbr_identity = {self.rbr_identity}")
  131. bias_identity_expanded = torch.nn.Parameter( torch.zeros_like(rbr_1x1_bias) )
  132. weight_identity_expanded = torch.nn.Parameter( torch.zeros_like(weight_1x1_expanded) )
  133. #print(f"self.rbr_1x1.weight = {self.rbr_1x1.weight.shape}, ")
  134. #print(f"weight_1x1_expanded = {weight_1x1_expanded.shape}, ")
  135. #print(f"self.rbr_dense.weight = {self.rbr_dense.weight.shape}, ")
  136. self.rbr_dense.weight = torch.nn.Parameter(self.rbr_dense.weight + weight_1x1_expanded + weight_identity_expanded)
  137. self.rbr_dense.bias = torch.nn.Parameter(self.rbr_dense.bias + rbr_1x1_bias + bias_identity_expanded)
  138. self.rbr_reparam = self.rbr_dense
  139. self.deploy = True
  140. if self.rbr_identity is not None:
  141. del self.rbr_identity
  142. self.rbr_identity = None
  143. if self.rbr_1x1 is not None:
  144. del self.rbr_1x1
  145. self.rbr_1x1 = None
  146. if self.rbr_dense is not None:
  147. del self.rbr_dense
  148. self.rbr_dense = None

输出层: 

        对于输出层,YOLO v7采用了yoloR的思想,首先对于经过repconv的特征图,经过ImplicitA层,我个人的理解是,ImplicitA相当于就是各个通道一个偏置项,以丰富各个通道所提取的信息,同时这个偏置项是可以学习的。经过ImplicitA后的特征馈送到输出层中,将输出的结果ImplicitM层,ImplicitM层我的理解是他对输出结果进行了放缩,能够更好的进行回归框的预测。

  1. class ImplicitA(nn.Module):
  2. def __init__(self, channel, mean=0., std=.02):
  3. super(ImplicitA, self).__init__()
  4. self.channel = channel
  5. self.mean = mean
  6. self.std = std
  7. self.implicit = nn.Parameter(torch.zeros(1, channel, 1, 1))
  8. nn.init.normal_(self.implicit, mean=self.mean, std=self.std)
  9. def forward(self, x):
  10. return self.implicit + x
  11. class ImplicitM(nn.Module):
  12. def __init__(self, channel, mean=1., std=.02):
  13. super(ImplicitM, self).__init__()
  14. self.channel = channel
  15. self.mean = mean
  16. self.std = std
  17. self.implicit = nn.Parameter(torch.ones(1, channel, 1, 1))
  18. nn.init.normal_(self.implicit, mean=self.mean, std=self.std)
  19. def forward(self, x):
  20. return self.implicit * x

 4.损失函数

        损失函数的输入有3个部分,第一个是预测值,第二个是标签,第三个是图像img

        预测值即为上面模型的输出,而对于标签target, 维度为物体数量*6,对于第二个维度,第一列为标签的索引,第二列为物体所属类别,而后面四列为物体检测框。

候选框的偏移

        首先,对target进行变换,让target包含anchor的索引,此时target维度为

 number of anchors,number of targets,7,最后一个维度7的组成为:batch索引,类别,x,y,w,h,anchor索引。

        对于偏移,偏移的思想是应对正负样本不均衡的问题,通常来说,负样本远远多于正样本。因此,通过偏移,可以构建更多的正样本。对于样本的中心点,只要目标的中心点偏移后位于附近的网格,也认为这个目标属于这个网格,对应的锚框的区域为正样本

        具体过程为:

  •  输入target标签为相对坐标,将x,y,w,h映射到特征图上
  • 计算锚框与真实框的宽高比,筛选出宽高比在1/r~r(默认为4),其他相差太大的锚框全部,去除,这样可以保证回归结果
  • 分别以左上角为原点和右下角为原点得到中心点的坐标
  • 对于每一个网格,选出中心点离网格中心点左、上小于0.5的target,并且不能是边界,例如:当中心点距离网格左边的距离小于0.5时,中心点左移0.5,此时,该网格左边的网格对应的锚框也为正样本。

通过,偏移,增加了正样本的数量,返回整数作为中心点所在网格的索引,最终得到存储batch_indices, anchor_indices, grid indices的索引矩阵和对应的anchors

代码如下: 

  1. def find_3_positive(self, p, targets):
  2. # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
  3. na, nt = self.na, targets.shape[0] # number of anchors, targets
  4. indices, anch = [], []
  5. gain = torch.ones(7, device=targets.device).long() # normalized to gridspace gain
  6. #---------------------------------------------------------------------------------#
  7. # number of anchors,number of targets
  8. # 表示哪个target属于哪个anchor
  9. #---------------------------------------------------------------------------------#
  10. ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
  11. # ---------------------------------------------------------------------------------#
  12. # number of anchors,number of targets,7
  13. # 最后一个维度7的组成为:batch索引,类别,x,y,w,h,anchor索引
  14. # ---------------------------------------------------------------------------------#
  15. targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
  16. # ---------------------------------------------------------------------------------#
  17. # 对于样本的中心点,只要目标的中心点偏移后位于附近的网格,也认为这个目标属于这个网格,对应的锚框的区域为正样本
  18. # ---------------------------------------------------------------------------------#
  19. g = 0.5 # bias
  20. off = torch.tensor([[0, 0],
  21. [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
  22. # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
  23. ], device=targets.device).float() * g # offsets
  24. for i in range(self.nl):
  25. anchors = self.anchors[i]
  26. # 特征图的h,w
  27. gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
  28. # Match targets to anchors
  29. # target标签为相对坐标,将x,y,w,h映射到特征图上
  30. t = targets * gain
  31. if nt:
  32. # Matches
  33. # 计算锚框与真实框的宽高比,筛选出宽高比在1/r~r(默认为4),其他相差太大的锚框全部
  34. # 去除,这样可以保证回归结果
  35. r = t[:, :, 4:6] / anchors[:, None] # wh ratio
  36. j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare
  37. # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
  38. t = t[j] # filter 去除相差太大的锚框
  39. # Offsets 偏移操作
  40. # 到左上角的距离,相当于就是以左上角为原点
  41. gxy = t[:, 2:4] # grid xy
  42. # 到右下角的距离,相当于就是以右下角为原点
  43. gxi = gain[[2, 3]] - gxy # inverse
  44. # 对于每一个网格,选出中心点离网格中心点左上角小于0.5的target,并且不能是边界
  45. # 例如:有两个真实框,需要判断,第一个物体是否满足要求,第二个物体是否满足要求,
  46. # 将所得的的矩阵转置,j代表在H维度是否满足要求,k代表在w维度是否满足要求
  47. j, k = ((gxy % 1. < g) & (gxy > 1.)).T
  48. # 对于每一个网格,选出中心点离网格中心点右下角小于0.5的target,并且不能是边界
  49. l, m = ((gxi % 1. < g) & (gxi > 1.)).T
  50. # 对应于上面的五个偏移
  51. j = torch.stack((torch.ones_like(j), j, k, l, m))
  52. # target重复五次对应于五个偏移,然后判断能否进行偏移,比如,到网格左边的距离小于0.5,就向左进行偏移,
  53. # 需要注意的是,上面给的+1,但是下面操作是减,因此到网格左边的距离小于0.5,就向左进行偏移
  54. t = t.repeat((5, 1, 1))[j]
  55. offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
  56. else:
  57. t = targets[0]
  58. offsets = 0
  59. # Define batch_indice,class
  60. b, c = t[:, :2].long().T # image, class
  61. gxy = t[:, 2:4] # grid xy
  62. gwh = t[:, 4:6] # grid wh
  63. # 执行偏移操作
  64. gij = (gxy - offsets).long()
  65. gi, gj = gij.T # grid xy indices
  66. # Append
  67. a = t[:, 6].long() # anchor indices
  68. indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
  69. anch.append(anchors[a]) # anchors
  70. return indices, anch

候选框的筛选分析:

        yolo v7的候选框的筛选跟YOLO v5和YOLO X均不相同,对于上面候选框的偏移,我们最终得到了9个锚框,然后分别计算这9个锚框的类别损失和IOU损失之和。

        具体过程为: 首先对候选框进行初筛,取出初筛的索引及对应的预测结果,计算出对应的x,y和w,h。需要注意的是,计算过程与初赛过程相对应。对于x,y的计算,若x,y分别为相对于网格的距离,范围为0~1,经过偏移后,x,y的取值范围为-0.5~1.5。对w和h也进行限制,初筛的时候,我们将宽高比大于4的都去掉了,因此,预测的范围也为0-4。然后计算预测框和真实框的iou,取出iou损失中最小的topk,如果多于10个候选框,取10个,少于10个候选框,全部取。然后 对topk的iou进行累加操作,最后取[iou之和]个候选框,相当于iou很小的候选框统统不要,最小为1个,其目的去除iou很小的候选框。并计算出iou损失,和分类损失进行加权,根据加权的结果筛选出对应的候选框。如果出现多个真实框匹配到了同一候选框的情况,此时对应的anchor_matching_gt > 1。比较哪一个真实框跟这个候选框的损失最小,损失最小的真实框匹配上该候选框,其他地方置为0。最后对信息进行汇总,返回batch索引,anchor索引,网格索引,对应的真实标签信息和锚框,并按照输出层进行统计。

 代码如下:

  1. def build_targets(self, p, targets, imgs):
  2. #indices, anch = self.find_positive(p, targets)
  3. indices, anch = self.find_3_positive(p, targets)
  4. #indices, anch = self.find_4_positive(p, targets)
  5. #indices, anch = self.find_5_positive(p, targets)
  6. #indices, anch = self.find_9_positive(p, targets)
  7. matching_bs = [[] for pp in p]
  8. matching_as = [[] for pp in p]
  9. matching_gjs = [[] for pp in p]
  10. matching_gis = [[] for pp in p]
  11. matching_targets = [[] for pp in p]
  12. matching_anchs = [[] for pp in p]
  13. nl = len(p)
  14. for batch_idx in range(p[0].shape[0]):
  15. # 取出batch对应的target
  16. b_idx = targets[:, 0]==batch_idx
  17. this_target = targets[b_idx]
  18. if this_target.shape[0] == 0:
  19. continue
  20. # 取出对应的真实框,转换为x1,y1,x2,y2
  21. txywh = this_target[:, 2:6] * imgs[batch_idx].shape[1]
  22. txyxy = xywh2xyxy(txywh)
  23. pxyxys = []
  24. p_cls = []
  25. p_obj = []
  26. from_which_layer = []
  27. all_b = []
  28. all_a = []
  29. all_gj = []
  30. all_gi = []
  31. all_anch = []
  32. for i, pi in enumerate(p):
  33. # 有时候index会为空,代表某一层没有对应的锚框
  34. # b代表batch_index,a代表anchor_indices,
  35. # gj,gi代表网格索引
  36. b, a, gj, gi = indices[i]
  37. idx = (b == batch_idx)
  38. b, a, gj, gi = b[idx], a[idx], gj[idx], gi[idx]
  39. all_b.append(b)
  40. all_a.append(a)
  41. all_gj.append(gj)
  42. all_gi.append(gi)
  43. all_anch.append(anch[i][idx])
  44. # size为初筛后的候选框数量,值为输出层的索引
  45. from_which_layer.append(torch.ones(size=(len(b),)) * i) # 来自哪个输出层
  46. fg_pred = pi[b, a, gj, gi] # 对应网格的预测结果
  47. p_obj.append(fg_pred[:, 4:5])
  48. p_cls.append(fg_pred[:, 5:])
  49. grid = torch.stack([gi, gj], dim=1) # 网格坐标
  50. # 与候选框的偏移相对应,若x,y分别为相对于网格的距离,范围为0~1,经过偏移后,x,y的取值范围为-0.5~1.5
  51. # 而下面的预测结果经过sigmoid后的范围为0~1,最终计算的范围为-0.5~1.5
  52. pxy = (fg_pred[:, :2].sigmoid() * 2. - 0.5 + grid) * self.stride[i] #/ 8.
  53. #pxy = (fg_pred[:, :2].sigmoid() * 3. - 1. + grid) * self.stride[i]
  54. # 对w和h也进行限制,初筛的时候,我们将宽高比大于4的都去掉了,因此,预测的范围也为0-4
  55. pwh = (fg_pred[:, 2:4].sigmoid() * 2) ** 2 * anch[i][idx] * self.stride[i] #/ 8.
  56. pxywh = torch.cat([pxy, pwh], dim=-1)
  57. pxyxy = xywh2xyxy(pxywh) # 转换为x,y,w,h
  58. pxyxys.append(pxyxy)
  59. pxyxys = torch.cat(pxyxys, dim=0)
  60. if pxyxys.shape[0] == 0:
  61. continue
  62. # 对三层的结果进行汇总,可能有些层结果为空
  63. p_obj = torch.cat(p_obj, dim=0)
  64. p_cls = torch.cat(p_cls, dim=0)
  65. from_which_layer = torch.cat(from_which_layer, dim=0)
  66. all_b = torch.cat(all_b, dim=0)
  67. all_a = torch.cat(all_a, dim=0)
  68. all_gj = torch.cat(all_gj, dim=0)
  69. all_gi = torch.cat(all_gi, dim=0)
  70. all_anch = torch.cat(all_anch, dim=0)
  71. # 计算ciou损失
  72. pair_wise_iou = box_iou(txyxy, pxyxys)
  73. pair_wise_iou_loss = -torch.log(pair_wise_iou + 1e-8)
  74. # 取出iou损失中最小的topk,如果多于10个候选框,取10个,少于10个候选框,全部取
  75. top_k, _ = torch.topk(pair_wise_iou, min(10, pair_wise_iou.shape[1]), dim=1)
  76. # 对iou进行累加操作,最后取[iou之和]个候选框,相当于iou很小的候选框统统不要,最小为1
  77. dynamic_ks = torch.clamp(top_k.sum(1).int(), min=1)
  78. # 将类别转换为one_hot编码格式
  79. gt_cls_per_image = (
  80. F.one_hot(this_target[:, 1].to(torch.int64), self.nc)
  81. .float()
  82. .unsqueeze(1)
  83. .repeat(1, pxyxys.shape[0], 1)
  84. )
  85. # 真实框目标的个数
  86. num_gt = this_target.shape[0]
  87. # 预测概率:p_obj*p_cls
  88. cls_preds_ = (
  89. p_cls.float().unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()
  90. * p_obj.unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()
  91. )
  92. y = cls_preds_.sqrt_()
  93. pair_wise_cls_loss = F.binary_cross_entropy_with_logits(
  94. torch.log(y/(1-y)) , gt_cls_per_image, reduction="none"
  95. ).sum(-1)
  96. del cls_preds_
  97. # 总损失:cls_loss+iou_loss
  98. cost = (
  99. pair_wise_cls_loss
  100. + 3.0 * pair_wise_iou_loss
  101. )
  102. matching_matrix = torch.zeros_like(cost)
  103. # 取出损失最小的候选框的索引
  104. for gt_idx in range(num_gt):
  105. _, pos_idx = torch.topk(
  106. cost[gt_idx], k=dynamic_ks[gt_idx].item(), largest=False
  107. )
  108. matching_matrix[gt_idx][pos_idx] = 1.0
  109. del top_k, dynamic_ks
  110. # 竖着加
  111. anchor_matching_gt = matching_matrix.sum(0)
  112. # 处理多个真实框匹配到了同一候选框的情况,此时对应的anchor_matching_gt > 1
  113. if (anchor_matching_gt > 1).sum() > 0:
  114. # 比较哪一个真实框跟这个候选框的损失最小
  115. _, cost_argmin = torch.min(cost[:, anchor_matching_gt > 1], dim=0)
  116. matching_matrix[:, anchor_matching_gt > 1] *= 0.0
  117. # 损失最小的真实框匹配上该候选框,其他地方置为0
  118. matching_matrix[cost_argmin, anchor_matching_gt > 1] = 1.0
  119. # 正样本索引
  120. fg_mask_inboxes = matching_matrix.sum(0) > 0.0
  121. # 正样本对应真实框的索引
  122. matched_gt_inds = matching_matrix[:, fg_mask_inboxes].argmax(0)
  123. # 汇总
  124. from_which_layer = from_which_layer[fg_mask_inboxes]
  125. all_b = all_b[fg_mask_inboxes]
  126. all_a = all_a[fg_mask_inboxes]
  127. all_gj = all_gj[fg_mask_inboxes]
  128. all_gi = all_gi[fg_mask_inboxes]
  129. all_anch = all_anch[fg_mask_inboxes]
  130. # 真实框
  131. this_target = this_target[matched_gt_inds]
  132. # 按照三个输出层合并信息
  133. for i in range(nl):
  134. layer_idx = from_which_layer == i
  135. matching_bs[i].append(all_b[layer_idx])
  136. matching_as[i].append(all_a[layer_idx])
  137. matching_gjs[i].append(all_gj[layer_idx])
  138. matching_gis[i].append(all_gi[layer_idx])
  139. matching_targets[i].append(this_target[layer_idx])
  140. matching_anchs[i].append(all_anch[layer_idx])
  141. # 按照输出层,汇总整个batch的信息
  142. for i in range(nl):
  143. if matching_targets[i] != []:
  144. matching_bs[i] = torch.cat(matching_bs[i], dim=0)
  145. matching_as[i] = torch.cat(matching_as[i], dim=0)
  146. matching_gjs[i] = torch.cat(matching_gjs[i], dim=0)
  147. matching_gis[i] = torch.cat(matching_gis[i], dim=0)
  148. matching_targets[i] = torch.cat(matching_targets[i], dim=0)
  149. matching_anchs[i] = torch.cat(matching_anchs[i], dim=0)
  150. else:
  151. matching_bs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
  152. matching_as[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
  153. matching_gjs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
  154. matching_gis[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
  155. matching_targets[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
  156. matching_anchs[i] = torch.tensor([], device='cuda:0', dtype=torch.int64)
  157. return matching_bs, matching_as, matching_gjs, matching_gis, matching_targets, matching_anchs

损失函数:

        损失函数与YOLO v5 r6.1版本并无变化,主要包含分类损失、存在物体置信度损失以及边界框回归损失。分类损失和置信度损失均使用交叉熵损失。回归损失使用C-IOU损失。 

辅助头网络结构:

    当添加辅助输出时,网络结构的输入为1280*1280,第一层需要对图片进行下采样,作者考虑到节省参数,第一层下采样采取间隔采样的做法。     

代码如下:

  1. class ReOrg(nn.Module):
  2. def __init__(self):
  3. super(ReOrg, self).__init__()
  4. def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
  5. return torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1)

        对于辅助输出,一共有八层,对于辅助输出,在损失函数的处理上有所区别,在标签分配上,辅助输出的偏移量为1,因此一共有5个网格,另外,在候选框的初步筛选上,辅助头的top_k为20。这一系列的处理,能够提升辅助头输出的召回率。因此,辅助头更加关注召回率。在损失函数上,辅助头的损失计算用0.25进行缩放。

 

模型的重参数化: 

        卷积和bn的重参数化:bn层的公式如图所示,可以变换为wx+b的形式

 

                 因此,可以得到bn层w和b的权重矩阵。

 

        将卷积公式带入其中,最终得到融合的权重矩阵和偏差的计算公式。 

 

 

 对于1*1和3*3卷积的参数化,将1*1的卷积核周围用0填充和3*3的卷积核相加

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/130965
推荐阅读
相关标签
  

闽ICP备14008679号