睿智的目标检测52——Keras搭建YoloX目标检测平台

不念不忘少年蓝@ 2022-09-09 14:45 381阅读 0赞

睿智的目标检测52——Keras搭建YoloX目标检测平台

  • 学习前言
  • 源码下载
  • YoloX改进的部分(不完全)
  • YoloX实现思路
    • 一、整体结构解析
    • 二、网络结构解析
      • 1、主干网络CSPDarknet介绍
      • 2、构建FPN特征金字塔进行加强特征提取
      • 3、利用Yolo Head获得预测结果
    • 三、预测结果的解码
      • 1、获得预测框与得分
      • 2、得分筛选与非极大抑制
    • 四、训练部分
      • 1、计算loss所需内容
      • 2、正样本特征点的必要条件
      • 3、SimOTA动态匹配正样本
      • 4、计算Loss
  • 训练自己的YoloX模型
    • 一、数据集的准备
    • 二、数据集的处理
    • 三、开始网络训练
    • 四、训练结果预测

学习前言

旷视新提出了YoloX,感觉蛮有意思,复现一下哈哈。
在这里插入图片描述

源码下载

https://github.com/bubbliiiing/yolox-keras
喜欢的可以点个star噢。

YoloX改进的部分(不完全)

1、主干部分:使用了Focus网络结构,这个结构是在YoloV5里面使用到比较有趣的网络结构,具体操作是在一张图片中每隔一个像素拿到一个值,这个时候获得了四个独立的特征层,然后将四个独立的特征层进行堆叠,此时宽高信息就集中到了通道信息,输入通道扩充了四倍。

2、分类回归层:Decoupled Head,以前版本的Yolo所用的解耦头是一起的,也就是分类和回归在一个1X1卷积里实现,YoloX认为这给网络的识别带来了不利影响。在YoloX中,Yolo Head被分为了两部分,分别实现,最后预测的时候才整合在一起。

3、数据增强:Mosaic数据增强、Mosaic利用了四张图片进行拼接实现数据中增强,根据论文所说其拥有一个巨大的优点是丰富检测物体的背景!且在BN计算的时候一下子会计算四张图片的数据!

4、Anchor Free:不使用先验框。

5、SimOTA :为不同大小的目标动态匹配正样本。

以上并非全部的改进部分,还存在一些其它的改进,这里只列出来了一些我比较感兴趣,而且非常有效的改进。

YoloX实现思路

一、整体结构解析

在这里插入图片描述

在学习YoloX之前,我们需要对YoloX所作的工作有一定的了解,这有助于我们后面去了解网络的细节。

和之前版本的Yolo类似,整个YoloX可以依然可以分为三个部分,分别是CSPDarknet,FPN以及Yolo Head

CSPDarknet可以被称作YoloX的主干特征提取网络,输入的图片首先会在CSPDarknet里面进行特征提取,提取到的特征可以被称作特征层,是输入图片的特征集合。在主干部分,我们获取了三个特征层进行下一步网络的构建,这三个特征层我称它为有效特征层

FPN可以被称作YoloX的加强特征提取网络,在主干部分获得的三个有效特征层会在这一部分进行特征融合,特征融合的目的是结合不同尺度的特征信息。在FPN部分,已经获得的有效特征层被用于继续提取特征。在YoloX里面同样使用了YoloV4中用到的Panet的结构,我们不仅会对特征进行上采样实现特征融合,还会对特征再次进行下采样实现特征融合。

Yolo Head是YoloX的分类器与回归器,通过CSPDarknet和FPN,我们已经可以获得三个加强过的有效特征层。每一个特征层都有宽、高和通道数,此时我们可以将特征图看作一个又一个特征点的集合每一个特征点都有通道数个特征。Yolo Head实际上所做的工作就是对特征点进行判断,判断特征点是否有物体与其对应。以前版本的Yolo所用的解耦头是一起的,也就是分类和回归在一个1X1卷积里实现,YoloX认为这给网络的识别带来了不利影响。在YoloX中,Yolo Head被分为了两部分,分别实现,最后预测的时候才整合在一起。

因此,整个YoloX网络所作的工作就是 特征提取-特征加强-预测特征点对应的物体情况

二、网络结构解析

1、主干网络CSPDarknet介绍

在这里插入图片描述
YoloX所使用的主干特征提取网络为CSPDarknet,它具有五个重要特点:
1、使用了残差网络Residual,CSPDarknet中的残差卷积可以分为两个部分,主干部分是一次1X1的卷积和一次3X3的卷积;残差边部分不做任何处理,直接将主干的输入与输出结合。整个YoloV3的主干部分都由残差卷积构成

  1. def Bottleneck(x, out_channels, shortcut=True, name = ""):
  2. y = compose(
  3. DarknetConv2D_BN_SiLU(out_channels, (1,1), name = name + '.conv1'),
  4. DarknetConv2D_BN_SiLU(out_channels, (3,3), name = name + '.conv2'))(x)
  5. if shortcut:
  6. y = Add()([x, y])
  7. return y

在这里插入图片描述
残差网络的特点是容易优化,并且能够通过增加相当的深度来提高准确率。其内部的残差块使用了跳跃连接,缓解了在深度神经网络中增加深度带来的梯度消失问题。

2、使用CSPnet网络结构,CSPnet结构并不算复杂,就是将原来的残差块的堆叠进行了一个拆分,拆成左右两部分:主干部分继续进行原来的残差块的堆叠另一部分则像一个残差边一样,经过少量处理直接连接到最后。因此可以认为CSP中存在一个大的残差边。在这里插入图片描述

  1. def CSPLayer(x, num_filters, num_blocks, shortcut=True, expansion=0.5, name=""):
  2. hidden_channels = int(num_filters * expansion) # hidden channels
  3. #----------------------------------------------------------------#
  4. # 主干部分会对num_blocks进行循环,循环内部是残差结构。
  5. #----------------------------------------------------------------#
  6. x_1 = DarknetConv2D_BN_SiLU(hidden_channels, (1,1), name = name + '.conv1')(x)
  7. #--------------------------------------------------------------------#
  8. # 然后建立一个大的残差边shortconv、这个大残差边绕过了很多的残差结构
  9. #--------------------------------------------------------------------#
  10. x_2 = DarknetConv2D_BN_SiLU(hidden_channels, (1,1), name = name + '.conv2')(x)
  11. for i in range(num_blocks):
  12. x_1 = Bottleneck(x_1, hidden_channels, shortcut, name = name + '.m.' + str(i))
  13. #----------------------------------------------------------------#
  14. # 将大残差边再堆叠回来
  15. #----------------------------------------------------------------#
  16. route = Concatenate()([x_1, x_2])
  17. #----------------------------------------------------------------#
  18. # 最后对通道数进行整合
  19. #----------------------------------------------------------------#
  20. return DarknetConv2D_BN_SiLU(num_filters, (1,1), name = name + '.conv3')(route)

3、使用了Focus网络结构,这个网络结构是在YoloV5里面使用到比较有趣的网络结构,具体操作是在一张图片中每隔一个像素拿到一个值,这个时候获得了四个独立的特征层,然后将四个独立的特征层进行堆叠,此时宽高信息就集中到了通道信息,输入通道扩充了四倍。拼接起来的特征层相对于原先的三通道变成了十二个通道,下图很好的展示了Focus结构,一看就能明白。
在这里插入图片描述

  1. class Focus(Layer):
  2. def __init__(self):
  3. super(Focus, self).__init__()
  4. def compute_output_shape(self, input_shape):
  5. return (input_shape[0], input_shape[1] // 2 if input_shape[1] != None else input_shape[1], input_shape[2] // 2 if input_shape[2] != None else input_shape[2], input_shape[3] * 4)
  6. def call(self, x):
  7. return tf.concat(
  8. [x[..., ::2, ::2, :],
  9. x[..., 1::2, ::2, :],
  10. x[..., ::2, 1::2, :],
  11. x[..., 1::2, 1::2, :]],
  12. axis=-1
  13. )

4、使用了SiLU激活函数,SiLU是Sigmoid和ReLU的改进版。SiLU具备无上界有下界、平滑、非单调的特性。SiLU在深层模型上的效果优于 ReLU。可以看做是平滑的ReLU激活函数。
f ( x ) = x ⋅ sigmoid ( x ) f(x) = x · \text{sigmoid}(x) f(x)=x⋅sigmoid(x)
在这里插入图片描述

  1. class SiLU(Layer):
  2. def __init__(self, **kwargs):
  3. super(SiLU, self).__init__(**kwargs)
  4. self.supports_masking = True
  5. def call(self, inputs):
  6. return inputs * K.sigmoid(inputs)
  7. def get_config(self):
  8. config = super(SiLU, self).get_config()
  9. return config
  10. def compute_output_shape(self, input_shape):
  11. return input_shape

5、使用了SPP结构,通过不同池化核大小的最大池化进行特征提取,提高网络的感受野。在YoloV4中,SPP是用在FPN里面的,在YoloX中,SPP模块被用在了主干特征提取网络中。

  1. def SPPBottleneck(x, out_channels, name = ""):
  2. #---------------------------------------------------#
  3. # 使用了SPP结构,即不同尺度的最大池化后堆叠。
  4. #---------------------------------------------------#
  5. x = DarknetConv2D_BN_SiLU(out_channels // 2, (1,1), name = name + '.conv1')(x)
  6. maxpool1 = MaxPooling2D(pool_size=(5,5), strides=(1,1), padding='same')(x)
  7. maxpool2 = MaxPooling2D(pool_size=(9,9), strides=(1,1), padding='same')(x)
  8. maxpool3 = MaxPooling2D(pool_size=(13,13), strides=(1,1), padding='same')(x)
  9. x = Concatenate()([x, maxpool1, maxpool2, maxpool3])
  10. x = DarknetConv2D_BN_SiLU(out_channels, (1,1), name = name + '.conv2')(x)
  11. return x

整个主干实现代码为:

  1. from functools import wraps
  2. from re import X
  3. import tensorflow as tf
  4. from keras import backend as K
  5. from keras.initializers import random_normal
  6. from keras.layers import (Add, BatchNormalization, Concatenate, Conv2D, Layer,
  7. MaxPooling2D, ZeroPadding2D)
  8. from keras.layers.normalization import BatchNormalization
  9. from keras.regularizers import l2
  10. from utils.utils import compose
  11. class SiLU(Layer):
  12. def __init__(self, **kwargs):
  13. super(SiLU, self).__init__(**kwargs)
  14. self.supports_masking = True
  15. def call(self, inputs):
  16. return inputs * K.sigmoid(inputs)
  17. def get_config(self):
  18. config = super(SiLU, self).get_config()
  19. return config
  20. def compute_output_shape(self, input_shape):
  21. return input_shape
  22. class Focus(Layer):
  23. def __init__(self):
  24. super(Focus, self).__init__()
  25. def compute_output_shape(self, input_shape):
  26. return (input_shape[0], input_shape[1] // 2 if input_shape[1] != None else input_shape[1], input_shape[2] // 2 if input_shape[2] != None else input_shape[2], input_shape[3] * 4)
  27. def call(self, x):
  28. return tf.concat(
  29. [x[..., ::2, ::2, :],
  30. x[..., 1::2, ::2, :],
  31. x[..., ::2, 1::2, :],
  32. x[..., 1::2, 1::2, :]],
  33. axis=-1
  34. )
  35. #------------------------------------------------------#
  36. # 单次卷积DarknetConv2D
  37. # 如果步长为2则自己设定padding方式。
  38. #------------------------------------------------------#
  39. @wraps(Conv2D)
  40. def DarknetConv2D(*args, **kwargs):
  41. darknet_conv_kwargs = {
  42. 'kernel_initializer' : random_normal(stddev=0.02)}
  43. darknet_conv_kwargs['padding'] = 'valid' if kwargs.get('strides')==(2,2) else 'same'
  44. darknet_conv_kwargs.update(kwargs)
  45. return Conv2D(*args, **darknet_conv_kwargs)
  46. #---------------------------------------------------#
  47. # 卷积块 -> 卷积 + 标准化 + 激活函数
  48. # DarknetConv2D + BatchNormalization + SiLU
  49. #---------------------------------------------------#
  50. def DarknetConv2D_BN_SiLU(*args, **kwargs):
  51. no_bias_kwargs = {
  52. 'use_bias': False}
  53. no_bias_kwargs.update(kwargs)
  54. if "name" in kwargs.keys():
  55. no_bias_kwargs['name'] = kwargs['name'] + '.conv'
  56. return compose(
  57. DarknetConv2D(*args, **no_bias_kwargs),
  58. BatchNormalization(name = kwargs['name'] + '.bn'),
  59. SiLU())
  60. def SPPBottleneck(x, out_channels, name = ""):
  61. #---------------------------------------------------#
  62. # 使用了SPP结构,即不同尺度的最大池化后堆叠。
  63. #---------------------------------------------------#
  64. x = DarknetConv2D_BN_SiLU(out_channels // 2, (1,1), name = name + '.conv1')(x)
  65. maxpool1 = MaxPooling2D(pool_size=(5,5), strides=(1,1), padding='same')(x)
  66. maxpool2 = MaxPooling2D(pool_size=(9,9), strides=(1,1), padding='same')(x)
  67. maxpool3 = MaxPooling2D(pool_size=(13,13), strides=(1,1), padding='same')(x)
  68. x = Concatenate()([x, maxpool1, maxpool2, maxpool3])
  69. x = DarknetConv2D_BN_SiLU(out_channels, (1,1), name = name + '.conv2')(x)
  70. return x
  71. def Bottleneck(x, out_channels, shortcut=True, name = ""):
  72. y = compose(
  73. DarknetConv2D_BN_SiLU(out_channels, (1,1), name = name + '.conv1'),
  74. DarknetConv2D_BN_SiLU(out_channels, (3,3), name = name + '.conv2'))(x)
  75. if shortcut:
  76. y = Add()([x, y])
  77. return y
  78. def CSPLayer(x, num_filters, num_blocks, shortcut=True, expansion=0.5, name=""):
  79. hidden_channels = int(num_filters * expansion) # hidden channels
  80. #----------------------------------------------------------------#
  81. # 主干部分会对num_blocks进行循环,循环内部是残差结构。
  82. #----------------------------------------------------------------#
  83. x_1 = DarknetConv2D_BN_SiLU(hidden_channels, (1,1), name = name + '.conv1')(x)
  84. #--------------------------------------------------------------------#
  85. # 然后建立一个大的残差边shortconv、这个大残差边绕过了很多的残差结构
  86. #--------------------------------------------------------------------#
  87. x_2 = DarknetConv2D_BN_SiLU(hidden_channels, (1,1), name = name + '.conv2')(x)
  88. for i in range(num_blocks):
  89. x_1 = Bottleneck(x_1, hidden_channels, shortcut, name = name + '.m.' + str(i))
  90. #----------------------------------------------------------------#
  91. # 将大残差边再堆叠回来
  92. #----------------------------------------------------------------#
  93. route = Concatenate()([x_1, x_2])
  94. #----------------------------------------------------------------#
  95. # 最后对通道数进行整合
  96. #----------------------------------------------------------------#
  97. return DarknetConv2D_BN_SiLU(num_filters, (1,1), name = name + '.conv3')(route)
  98. def resblock_body(x, num_filters, num_blocks, shortcut=True, expansion=0.5, last = False, name = ""):
  99. #----------------------------------------------------------------#
  100. # 利用ZeroPadding2D和一个步长为2x2的卷积块进行高和宽的压缩
  101. #----------------------------------------------------------------#
  102. x = ZeroPadding2D(((1,1),(1,1)))(x)
  103. #----------------------------------------------------------------#
  104. # 利用ZeroPadding2D和一个步长为2x2的卷积块进行高和宽的压缩
  105. #----------------------------------------------------------------#
  106. x = DarknetConv2D_BN_SiLU(num_filters, (3,3), strides=(2,2), name = name + '.0')(x)
  107. if last:
  108. x = SPPBottleneck(x, num_filters, name = name + '.1')
  109. return CSPLayer(x, num_filters, num_blocks, shortcut=shortcut, expansion=expansion, name = name + '.1' if not last else name + '.2')
  110. #---------------------------------------------------#
  111. # CSPdarknet53 的主体部分
  112. # 输入为一张416x416x3的图片
  113. # 输出为三个有效特征层
  114. #---------------------------------------------------#
  115. def darknet_body(x, dep_mul, wid_mul):
  116. base_channels = int(wid_mul * 64) # 64
  117. base_depth = max(round(dep_mul * 3), 1) # 3
  118. x = Focus()(x)
  119. x = DarknetConv2D_BN_SiLU(base_channels, (3,3), name = 'backbone.backbone.stem.conv')(x)
  120. x = resblock_body(x, base_channels * 2, base_depth, name = 'backbone.backbone.dark2')
  121. x = resblock_body(x, base_channels * 4, base_depth * 3, name = 'backbone.backbone.dark3')
  122. feat1 = x
  123. x = resblock_body(x, base_channels * 8, base_depth * 3, name = 'backbone.backbone.dark4')
  124. feat2 = x
  125. x = resblock_body(x, base_channels * 16, base_depth, last = True, name = 'backbone.backbone.dark5')
  126. feat3 = x
  127. return feat1,feat2,feat3

2、构建FPN特征金字塔进行加强特征提取

在这里插入图片描述
在特征利用部分,YoloX提取多特征层进行目标检测,一共提取三个特征层
三个特征层位于主干部分CSPdarknet的不同位置,分别位于中间层,中下层,底层,当输入为(640,640,3)的时候,三个特征层的shape分别为feat1=(80,80,256)、feat2=(40,40,512)、feat3=(20,20,1024)。

在获得三个有效特征层后,我们利用这三个有效特征层进行FPN层的构建,构建方式为:

  1. feat3=(20,20,1024)的特征层进行1次1X1卷积调整通道后获得P5,P5进行上采样UmSampling2d后与feat2=(40,40,512)特征层进行结合,然后使用CSPLayer进行特征提取获得P5_upsample,此时获得的特征层为(40,40,512)。
  2. P5_upsample=(40,40,512)的特征层进行1次1X1卷积调整通道后获得P4,P4进行上采样UmSampling2d后与feat1=(80,80,256)特征层进行结合,然后使用CSPLayer进行特征提取P3_out,此时获得的特征层为(80,80,256)。
  3. P3_out=(80,80,256)的特征层进行一次3x3卷积进行下采样,下采样后与P4堆叠,然后使用CSPLayer进行特征提取P4_out,此时获得的特征层为(40,40,512)。
  4. P4_out=(40,40,512)的特征层进行一次3x3卷积进行下采样,下采样后与P5堆叠,然后使用CSPLayer进行特征提取P5_out,此时获得的特征层为(20,20,1024)。

特征金字塔可以将不同shape的特征层进行特征融合,有利于提取出更好的特征

  1. from keras.layers import (Concatenate, Input, Lambda, UpSampling2D,
  2. ZeroPadding2D)
  3. from keras.layers.convolutional import UpSampling2D
  4. from keras.models import Model
  5. from nets.CSPdarknet53 import (CSPLayer, DarknetConv2D, DarknetConv2D_BN_SiLU,
  6. darknet_body)
  7. from nets.yolo_training import get_yolo_loss
  8. #---------------------------------------------------#
  9. # Panet网络的构建,并且获得预测结果
  10. #---------------------------------------------------#
  11. def yolo_body(input_shape, num_classes, phi):
  12. depth_dict = {
  13. 's' : 0.33, 'm' : 0.67, 'l' : 1.00, 'x' : 1.33,}
  14. width_dict = {
  15. 's' : 0.50, 'm' : 0.75, 'l' : 1.00, 'x' : 1.25,}
  16. depth, width = depth_dict[phi], width_dict[phi]
  17. in_channels = [256, 512, 1024]
  18. inputs = Input(input_shape)
  19. feat1, feat2, feat3 = darknet_body(inputs, depth, width)
  20. P5 = DarknetConv2D_BN_SiLU(int(in_channels[1] * width), (1, 1), name = 'backbone.lateral_conv0')(feat3)
  21. P5_upsample = UpSampling2D()(P5) # 512/16
  22. P5_upsample = Concatenate(axis = -1)([P5_upsample, feat2]) # 512->1024/16
  23. P5_upsample = CSPLayer(P5_upsample, int(in_channels[1] * width), round(3 * depth), shortcut = False, name = 'backbone.C3_p4') # 1024->512/16
  24. P4 = DarknetConv2D_BN_SiLU(int(in_channels[0] * width), (1, 1), name = 'backbone.reduce_conv1')(P5_upsample) # 512->256/16
  25. P4_upsample = UpSampling2D()(P4) # 256/8
  26. P4_upsample = Concatenate(axis = -1)([P4_upsample, feat1]) # 256->512/8
  27. P3_out = CSPLayer(P4_upsample, int(in_channels[0] * width), round(3 * depth), shortcut = False, name = 'backbone.C3_p3') # 1024->512/16
  28. P3_downsample = ZeroPadding2D(((1,1),(1,1)))(P3_out)
  29. P3_downsample = DarknetConv2D_BN_SiLU(int(in_channels[0] * width), (3, 3), strides = (2, 2), name = 'backbone.bu_conv2')(P3_downsample) # 256->256/16
  30. P3_downsample = Concatenate(axis = -1)([P3_downsample, P4]) # 256->512/16
  31. P4_out = CSPLayer(P3_downsample, int(in_channels[1] * width), round(3 * depth), shortcut = False, name = 'backbone.C3_n3') # 1024->512/16
  32. P4_downsample = ZeroPadding2D(((1,1),(1,1)))(P4_out)
  33. P4_downsample = DarknetConv2D_BN_SiLU(int(in_channels[1] * width), (3, 3), strides = (2, 2), name = 'backbone.bu_conv1')(P4_downsample) # 256->256/16
  34. P4_downsample = Concatenate(axis = -1)([P4_downsample, P5]) # 512->1024/32
  35. P5_out = CSPLayer(P4_downsample, int(in_channels[2] * width), round(3 * depth), shortcut = False, name = 'backbone.C3_n4') # 1024->512/16

3、利用Yolo Head获得预测结果

在这里插入图片描述
利用FPN特征金字塔,我们可以获得三个加强特征,这三个加强特征的shape分别为(20,20,1024)、(40,40,512)、(80,80,256),然后我们利用这三个shape的特征层传入Yolo Head获得预测结果。

YoloX中的YoloHead与之前版本的YoloHead不同。以前版本的Yolo所用的解耦头是一起的,也就是分类和回归在一个1X1卷积里实现,YoloX认为这给网络的识别带来了不利影响。在YoloX中,Yolo Head被分为了两部分,分别实现,最后预测的时候才整合在一起。
在这里插入图片描述对于每一个特征层,我们可以获得三个预测结果,分别是:
1、Reg(h,w,4)用于判断每一个特征点的回归参数,回归参数调整后可以获得预测框。
2、Obj(h,w,1)用于判断每一个特征点是否包含物体。
3、Cls(h,w,num_classes)用于判断每一个特征点所包含的物体种类。
将三个预测结果进行堆叠,每个特征层获得的结果为:
Out(h,w,4+1+num_classses)前四个参数用于判断每一个特征点的回归参数,回归参数调整后可以获得预测框;第五个参数用于判断每一个特征点是否包含物体;最后num_classes个参数用于判断每一个特征点所包含的物体种类。

实现代码如下:

  1. fpn_outs = [P3_out, P4_out, P5_out]
  2. yolo_outs = []
  3. for i, out in enumerate(fpn_outs):
  4. stem = DarknetConv2D_BN_SiLU(int(256 * width), (1, 1), strides = (1, 1), name = 'head.stems.' + str(i))(out)
  5. cls_conv = DarknetConv2D_BN_SiLU(int(256 * width), (3, 3), strides = (1, 1), name = 'head.cls_convs.' + str(i) + '.0')(stem)
  6. cls_conv = DarknetConv2D_BN_SiLU(int(256 * width), (3, 3), strides = (1, 1), name = 'head.cls_convs.' + str(i) + '.1')(cls_conv)
  7. cls_pred = DarknetConv2D(num_classes, (1, 1), strides = (1, 1), name = 'head.cls_preds.' + str(i))(cls_conv)
  8. reg_conv = DarknetConv2D_BN_SiLU(int(256 * width), (3, 3), strides = (1, 1), name = 'head.reg_convs.' + str(i) + '.0')(stem)
  9. reg_conv = DarknetConv2D_BN_SiLU(int(256 * width), (3, 3), strides = (1, 1), name = 'head.reg_convs.' + str(i) + '.1')(reg_conv)
  10. reg_pred = DarknetConv2D(4, (1, 1), strides = (1, 1), name = 'head.reg_preds.' + str(i))(reg_conv)
  11. obj_pred = DarknetConv2D(1, (1, 1), strides = (1, 1), name = 'head.obj_preds.' + str(i))(reg_conv)
  12. output = Concatenate(axis = -1)([reg_pred, obj_pred, cls_pred])
  13. yolo_outs.append(output)
  14. return Model(inputs, yolo_outs)

三、预测结果的解码

1、获得预测框与得分

在对预测结果进行解码之前,我们再来看看预测结果代表了什么,预测结果可以分为3个部分:

通过上一步,我们获得了每个特征层的三个预测结果。

本文以(20,20,1024)对应的三个预测结果为例:

1、Reg预测结果,此时卷积的通道数为4,最终结果为(20,20,4)。其中的4可以分为两个2,第一个2是预测框的中心点相较于该特征点的偏移情况,第二个2是预测框的宽高相较于对数指数的参数
2、Obj预测结果,此时卷积的通道数为1,最终结果为(20,20,1),代表每一个特征点预测框内部包含物体的概率。
3、Cls预测结果,此时卷积的通道数为num_classes,最终结果为(20,20,num_classes),代表每一个特征点对应某类物体的概率,最后一维度num_classes中的预测值代表属于每一个类的概率;

该特征层相当于将图像划分成20x20个特征点,如果某个特征点落在物体的对应框内,就用于预测该物体。

如图所示,蓝色的点为20x20的特征点,此时我们对左图红色的三个点进行解码操作演示:
1、进行中心预测点的计算,利用Regression预测结果前两个序号的内容对特征点坐标进行偏移,左图红色的三个特征点偏移后是右图绿色的三个点;
2、进行预测框宽高的计算,利用Regression预测结果后两个序号的内容求指数后获得预测框的宽高;
3、此时获得的预测框就可以绘制在图片上了。
在这里插入图片描述
除去这样的解码操作,还有非极大抑制的操作需要进行,防止同一种类的框的堆积。

  1. #---------------------------------------------------#
  2. # 图片预测
  3. #---------------------------------------------------#
  4. def DecodeBox(outputs,
  5. num_classes,
  6. image_shape,
  7. input_shape,
  8. max_boxes = 100,
  9. confidence = 0.5,
  10. nms_iou = 0.3,
  11. letterbox_image = True):
  12. bs = K.shape(outputs[0])[0]
  13. grids = []
  14. strides = []
  15. hw = [K.shape(x)[1:3] for x in outputs]
  16. outputs = tf.concat([tf.reshape(x, [bs, -1, 5 + num_classes]) for x in outputs], axis = 1)
  17. for i in range(len(hw)):
  18. #---------------------------#
  19. # 根据特征层生成网格点
  20. #---------------------------#
  21. grid_x, grid_y = tf.meshgrid(K.arange(hw[i][1]), K.arange(hw[i][0]))
  22. grid = tf.reshape(tf.stack((grid_x, grid_y), 2), (1, -1, 2))
  23. shape = tf.shape(grid)[:2]
  24. grids.append(tf.cast(grid, K.dtype(outputs)))
  25. strides.append(tf.ones((shape[0], shape[1], 1)) * input_shape[0] / tf.cast(hw[i][0], K.dtype(outputs)))
  26. #---------------------------#
  27. # 将网格点堆叠到一起
  28. #---------------------------#
  29. grids = tf.concat(grids, axis=1)
  30. strides = tf.concat(strides, axis=1)
  31. #------------------------#
  32. # 根据网格点进行解码
  33. #------------------------#
  34. box_xy = (outputs[..., :2] + grids) * strides / K.cast(input_shape[::-1], K.dtype(outputs))
  35. box_wh = tf.exp(outputs[..., 2:4]) * strides / K.cast(input_shape[::-1], K.dtype(outputs))
  36. box_confidence = K.sigmoid(outputs[..., 4:5])
  37. box_class_probs = K.sigmoid(outputs[..., 5: ])
  38. #------------------------------------------------------------------------------------------------------------#
  39. # 在图像传入网络预测前会进行letterbox_image给图像周围添加灰条,因此生成的box_xy, box_wh是相对于有灰条的图像的
  40. # 我们需要对其进行修改,去除灰条的部分。 将box_xy、和box_wh调节成y_min,y_max,xmin,xmax
  41. # 如果没有使用letterbox_image也需要将归一化后的box_xy, box_wh调整成相对于原图大小的
  42. #------------------------------------------------------------------------------------------------------------#
  43. boxes = yolo_correct_boxes(box_xy, box_wh, input_shape, image_shape, letterbox_image)

2、得分筛选与非极大抑制

得到最终的预测结果后还要进行得分排序与非极大抑制筛选

得分筛选就是筛选出得分满足confidence置信度的预测框。
非极大抑制就是筛选出一定区域内属于同一种类得分最大的框。

得分筛选与非极大抑制的过程可以概括如下:
1、找出该图片中得分大于门限函数的框。在进行重合框筛选前就进行得分的筛选可以大幅度减少框的数量。
2、对种类进行循环,非极大抑制的作用是筛选出一定区域内属于同一种类得分最大的框,对种类进行循环可以帮助我们对每一个类分别进行非极大抑制。
3、根据得分对该种类进行从大到小排序。
4、每次取出得分最大的框,计算其与其它所有预测框的重合程度,重合程度过大的则剔除。

得分筛选与非极大抑制后的结果就可以用于绘制预测框了。

下图是经过非极大抑制的。
在这里插入图片描述
下图是未经过非极大抑制的。
在这里插入图片描述
实现代码为:

  1. box_scores = box_confidence * box_class_probs
  2. #-----------------------------------------------------------#
  3. # 判断得分是否大于score_threshold
  4. #-----------------------------------------------------------#
  5. mask = box_scores >= confidence
  6. max_boxes_tensor = K.constant(max_boxes, dtype='int32')
  7. boxes_out = []
  8. scores_out = []
  9. classes_out = []
  10. for c in range(num_classes):
  11. #-----------------------------------------------------------#
  12. # 取出所有box_scores >= score_threshold的框,和成绩
  13. #-----------------------------------------------------------#
  14. class_boxes = tf.boolean_mask(boxes, mask[:, c])
  15. class_box_scores = tf.boolean_mask(box_scores[:, c], mask[:, c])
  16. #-----------------------------------------------------------#
  17. # 非极大抑制
  18. # 保留一定区域内得分最大的框
  19. #-----------------------------------------------------------#
  20. nms_index = tf.image.non_max_suppression(class_boxes, class_box_scores, max_boxes_tensor, iou_threshold=nms_iou)
  21. #-----------------------------------------------------------#
  22. # 获取非极大抑制后的结果
  23. # 下列三个分别是:框的位置,得分与种类
  24. #-----------------------------------------------------------#
  25. class_boxes = K.gather(class_boxes, nms_index)
  26. class_box_scores = K.gather(class_box_scores, nms_index)
  27. classes = K.ones_like(class_box_scores, 'int32') * c
  28. boxes_out.append(class_boxes)
  29. scores_out.append(class_box_scores)
  30. classes_out.append(classes)
  31. boxes_out = K.concatenate(boxes_out, axis=0)
  32. scores_out = K.concatenate(scores_out, axis=0)
  33. classes_out = K.concatenate(classes_out, axis=0)

四、训练部分

1、计算loss所需内容

计算loss实际上是网络的预测结果和网络的真实结果的对比。
和网络的预测结果一样,网络的损失也由三个部分组成,分别是Reg部分、Obj部分、Cls部分。Reg部分是特征点的回归参数判断、Obj部分是特征点是否包含物体判断、Cls部分是特征点包含的物体的种类。

2、正样本特征点的必要条件

在YoloX中,物体的真实框落在哪些特征点内就由该特征点来预测。

对于每一个真实框,我们会求取所有特征点与它的空间位置情况。作为正样本的特征点需要满足以下几个特点:
1、特征点落在物体的真实框内。
2、特征点距离物体中心尽量要在一定半径内

特点1、2保证了属于正样本的特征点会落在物体真实框内部,特征点中心与物体真实框中心要相近。

上面两个条件仅用作正样本的而初步筛选,在YoloX中,我们使用了SimOTA方法进行动态的正样本数量分配。

  1. def get_in_boxes_info(gt_bboxes_per_image, x_shifts, y_shifts, expanded_strides, num_gt, total_num_anchors, center_radius = 2.5):
  2. #-------------------------------------------------------#
  3. # expanded_strides_per_image [n_anchors_all]
  4. # x_centers_per_image [num_gt, n_anchors_all]
  5. # x_centers_per_image [num_gt, n_anchors_all]
  6. #-------------------------------------------------------#
  7. expanded_strides_per_image = expanded_strides[0]
  8. x_centers_per_image = tf.tile(tf.expand_dims(((x_shifts[0] + 0.5) * expanded_strides_per_image), 0), [num_gt, 1])
  9. y_centers_per_image = tf.tile(tf.expand_dims(((y_shifts[0] + 0.5) * expanded_strides_per_image), 0), [num_gt, 1])
  10. #-------------------------------------------------------#
  11. # gt_bboxes_per_image_x [num_gt, n_anchors_all]
  12. #-------------------------------------------------------#
  13. gt_bboxes_per_image_l = tf.tile(tf.expand_dims((gt_bboxes_per_image[:, 0] - 0.5 * gt_bboxes_per_image[:, 2]), 1), [1, total_num_anchors])
  14. gt_bboxes_per_image_r = tf.tile(tf.expand_dims((gt_bboxes_per_image[:, 0] + 0.5 * gt_bboxes_per_image[:, 2]), 1), [1, total_num_anchors])
  15. gt_bboxes_per_image_t = tf.tile(tf.expand_dims((gt_bboxes_per_image[:, 1] - 0.5 * gt_bboxes_per_image[:, 3]), 1), [1, total_num_anchors])
  16. gt_bboxes_per_image_b = tf.tile(tf.expand_dims((gt_bboxes_per_image[:, 1] + 0.5 * gt_bboxes_per_image[:, 3]), 1), [1, total_num_anchors])
  17. #-------------------------------------------------------#
  18. # bbox_deltas [num_gt, n_anchors_all, 4]
  19. #-------------------------------------------------------#
  20. b_l = x_centers_per_image - gt_bboxes_per_image_l
  21. b_r = gt_bboxes_per_image_r - x_centers_per_image
  22. b_t = y_centers_per_image - gt_bboxes_per_image_t
  23. b_b = gt_bboxes_per_image_b - y_centers_per_image
  24. bbox_deltas = tf.stack([b_l, b_t, b_r, b_b], 2)
  25. #-------------------------------------------------------#
  26. # is_in_boxes [num_gt, n_anchors_all]
  27. # is_in_boxes_all [n_anchors_all]
  28. #-------------------------------------------------------#
  29. is_in_boxes = tf.reduce_min(bbox_deltas, axis = -1) > 0.0
  30. is_in_boxes_all = tf.reduce_sum(tf.cast(is_in_boxes, K.dtype(gt_bboxes_per_image)), axis = 0) > 0.0
  31. gt_bboxes_per_image_l = tf.tile(tf.expand_dims(gt_bboxes_per_image[:, 0], 1), [1, total_num_anchors]) - center_radius * tf.expand_dims(expanded_strides_per_image, 0)
  32. gt_bboxes_per_image_r = tf.tile(tf.expand_dims(gt_bboxes_per_image[:, 0], 1), [1, total_num_anchors]) + center_radius * tf.expand_dims(expanded_strides_per_image, 0)
  33. gt_bboxes_per_image_t = tf.tile(tf.expand_dims(gt_bboxes_per_image[:, 1], 1), [1, total_num_anchors]) - center_radius * tf.expand_dims(expanded_strides_per_image, 0)
  34. gt_bboxes_per_image_b = tf.tile(tf.expand_dims(gt_bboxes_per_image[:, 1], 1), [1, total_num_anchors]) + center_radius * tf.expand_dims(expanded_strides_per_image, 0)
  35. #-------------------------------------------------------#
  36. # center_deltas [num_gt, n_anchors_all, 4]
  37. #-------------------------------------------------------#
  38. c_l = x_centers_per_image - gt_bboxes_per_image_l
  39. c_r = gt_bboxes_per_image_r - x_centers_per_image
  40. c_t = y_centers_per_image - gt_bboxes_per_image_t
  41. c_b = gt_bboxes_per_image_b - y_centers_per_image
  42. center_deltas = tf.stack([c_l, c_t, c_r, c_b], 2)
  43. #-------------------------------------------------------#
  44. # is_in_centers [num_gt, n_anchors_all]
  45. # is_in_centers_all [n_anchors_all]
  46. #-------------------------------------------------------#
  47. is_in_centers = tf.reduce_min(center_deltas, axis = -1) > 0.0
  48. is_in_centers_all = tf.reduce_sum(tf.cast(is_in_centers, K.dtype(gt_bboxes_per_image)), axis = 0) > 0.0
  49. #-------------------------------------------------------#
  50. # fg_mask [n_anchors_all]
  51. # is_in_boxes_and_center [num_gt, fg_mask]
  52. #-------------------------------------------------------#
  53. fg_mask = tf.cast(is_in_boxes_all | is_in_centers_all, tf.bool)
  54. is_in_boxes_and_center = tf.boolean_mask(is_in_boxes, fg_mask, axis = 1) & tf.boolean_mask(is_in_centers, fg_mask, axis = 1)
  55. return fg_mask, is_in_boxes_and_center

3、SimOTA动态匹配正样本

在YoloX中,我们会计算一个Cost代价矩阵,代表每个真实框和每个特征点之间的代价关系,Cost代价矩阵由三个部分组成:
1、每个真实框和当前特征点预测框的重合程度;
2、每个真实框和当前特征点预测框的种类预测准确度;
3、每个真实框的中心是否落在了特征点的一定半径内。

每个真实框和当前特征点预测框的重合程度越高,代表这个特征点已经尝试去拟合该真实框了,因此它的Cost代价就会越小。

每个真实框和当前特征点预测框的种类预测准确度越高,也代表这个特征点已经尝试去拟合该真实框了,因此它的Cost代价就会越小。

每个真实框的中心如果落在了特征点的一定半径内,代表这个特征点应该去拟合该真实框,因此它的Cost代价就会越小。

Cost代价矩阵的目的是自适应的找到当前特征点应该去拟合的真实框,重合度越高越需要拟合,分类越准越需要拟合,在一定半径内越需要拟合。

在SimOTA中,不同目标设定不同的正样本数量(dynamick),以旷视科技官方回答中的蚂蚁和西瓜为例子,传统的正样本分配方案常常为同一场景下的西瓜和蚂蚁分配同样的正样本数,那要么蚂蚁有很多低质量的正样本,要么西瓜仅仅只有一两个正样本。对于哪个分配方式都是不合适的。
动态的正样本设置的关键在于如何确定k,SimOTA具体的做法是首先计算每个目标Cost最低的10特征点,然后把这十个特征点对应的预测框与真实框的IOU加起来求得最终的k。

因此,SimOTA的过程总结如下:
1、计算每个真实框和当前特征点预测框的重合程度。
2、计算将重合度最高的十个预测框与真实框的IOU加起来求得每个真实框的k,也就代表每个真实框有k个特征点与之对应。
3、计算每个真实框和当前特征点预测框的种类预测准确度。
4、判断真实框的中心是否落在了特征点的一定半径内。
5、计算Cost代价矩阵。
6、将Cost最低的k个点作为该真实框的正样本。

  1. def get_assignments(gt_bboxes_per_image, gt_classes, bboxes_preds_per_image, obj_preds_per_image, cls_preds_per_image, x_shifts, y_shifts, expanded_strides, num_classes, num_gt, total_num_anchors):
  2. #-------------------------------------------------------#
  3. # fg_mask [n_anchors_all]
  4. # is_in_boxes_and_center [num_gt, len(fg_mask)]
  5. #-------------------------------------------------------#
  6. fg_mask, is_in_boxes_and_center = get_in_boxes_info(gt_bboxes_per_image, x_shifts, y_shifts, expanded_strides, num_gt, total_num_anchors)
  7. #-------------------------------------------------------#
  8. # fg_mask [n_anchors_all]
  9. # bboxes_preds_per_image [fg_mask, 4]
  10. # cls_preds_ [fg_mask, num_classes]
  11. # obj_preds_ [fg_mask, 1]
  12. #-------------------------------------------------------#
  13. bboxes_preds_per_image = tf.boolean_mask(bboxes_preds_per_image, fg_mask, axis = 0)
  14. obj_preds_ = tf.boolean_mask(obj_preds_per_image, fg_mask, axis = 0)
  15. cls_preds_ = tf.boolean_mask(cls_preds_per_image, fg_mask, axis = 0)
  16. num_in_boxes_anchor = tf.shape(bboxes_preds_per_image)[0]
  17. #-------------------------------------------------------#
  18. # pair_wise_ious [num_gt, fg_mask]
  19. #-------------------------------------------------------#
  20. pair_wise_ious = bboxes_iou(gt_bboxes_per_image, bboxes_preds_per_image)
  21. pair_wise_ious_loss = -tf.log(pair_wise_ious + 1e-8)
  22. #-------------------------------------------------------#
  23. # cls_preds_ [num_gt, fg_mask, num_classes]
  24. # gt_cls_per_image [num_gt, fg_mask, num_classes]
  25. #-------------------------------------------------------#
  26. gt_cls_per_image = tf.tile(tf.expand_dims(tf.one_hot(tf.cast(gt_classes, tf.int32), num_classes), 1), (1, num_in_boxes_anchor, 1))
  27. cls_preds_ = K.sigmoid(tf.tile(tf.expand_dims(cls_preds_, 0), (num_gt, 1, 1))) *\
  28. K.sigmoid(tf.tile(tf.expand_dims(obj_preds_, 0), (num_gt, 1, 1)))
  29. pair_wise_cls_loss = tf.reduce_sum(K.binary_crossentropy(gt_cls_per_image, tf.sqrt(cls_preds_)), -1)
  30. cost = pair_wise_cls_loss + 3.0 * pair_wise_ious_loss + 100000.0 * tf.cast((~is_in_boxes_and_center), K.dtype(bboxes_preds_per_image))
  31. gt_matched_classes, fg_mask, pred_ious_this_matching, matched_gt_inds, num_fg = dynamic_k_matching(cost, pair_wise_ious, fg_mask, gt_classes, num_gt)
  32. return gt_matched_classes, fg_mask, pred_ious_this_matching, matched_gt_inds, num_fg
  33. def bboxes_iou(b1, b2):
  34. #---------------------------------------------------#
  35. # num_anchor,1,4
  36. # 计算左上角的坐标和右下角的坐标
  37. #---------------------------------------------------#
  38. b1 = K.expand_dims(b1, -2)
  39. b1_xy = b1[..., :2]
  40. b1_wh = b1[..., 2:4]
  41. b1_wh_half = b1_wh/2.
  42. b1_mins = b1_xy - b1_wh_half
  43. b1_maxes = b1_xy + b1_wh_half
  44. #---------------------------------------------------#
  45. # 1,n,4
  46. # 计算左上角和右下角的坐标
  47. #---------------------------------------------------#
  48. b2 = K.expand_dims(b2, 0)
  49. b2_xy = b2[..., :2]
  50. b2_wh = b2[..., 2:4]
  51. b2_wh_half = b2_wh/2.
  52. b2_mins = b2_xy - b2_wh_half
  53. b2_maxes = b2_xy + b2_wh_half
  54. #---------------------------------------------------#
  55. # 计算重合面积
  56. #---------------------------------------------------#
  57. intersect_mins = K.maximum(b1_mins, b2_mins)
  58. intersect_maxes = K.minimum(b1_maxes, b2_maxes)
  59. intersect_wh = K.maximum(intersect_maxes - intersect_mins, 0.)
  60. intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1]
  61. b1_area = b1_wh[..., 0] * b1_wh[..., 1]
  62. b2_area = b2_wh[..., 0] * b2_wh[..., 1]
  63. iou = intersect_area / (b1_area + b2_area - intersect_area)
  64. return iou
  65. def dynamic_k_matching(cost, pair_wise_ious, fg_mask, gt_classes, num_gt):
  66. #-------------------------------------------------------#
  67. # cost [num_gt, fg_mask]
  68. # pair_wise_ious [num_gt, fg_mask]
  69. # gt_classes [num_gt]
  70. # fg_mask [n_anchors_all]
  71. # matching_matrix [num_gt, fg_mask]
  72. #-------------------------------------------------------#
  73. matching_matrix = tf.zeros_like(cost)
  74. #------------------------------------------------------------#
  75. # 选取iou最大的n_candidate_k个点
  76. # 然后求和,判断应该有多少点用于该框预测
  77. # topk_ious [num_gt, n_candidate_k]
  78. # dynamic_ks [num_gt]
  79. # matching_matrix [num_gt, fg_mask]
  80. #------------------------------------------------------------#
  81. n_candidate_k = tf.minimum(10, tf.shape(pair_wise_ious)[1])
  82. topk_ious, _ = tf.nn.top_k(pair_wise_ious, n_candidate_k)
  83. dynamic_ks = tf.maximum(tf.reduce_sum(topk_ious, 1), 1)
  84. # dynamic_ks = tf.Print(dynamic_ks, [topk_ious, dynamic_ks], summarize = 100)
  85. def loop_body_1(b, matching_matrix):
  86. #------------------------------------------------------------#
  87. # 给每个真实框选取最小的动态k个点
  88. #------------------------------------------------------------#
  89. _, pos_idx = tf.nn.top_k(-cost[b], k=tf.cast(dynamic_ks[b], tf.int32))
  90. matching_matrix = tf.concat(
  91. [matching_matrix[:b], tf.expand_dims(tf.reduce_max(tf.one_hot(pos_idx, tf.shape(cost)[1]), 0), 0), matching_matrix[b+1:]], axis = 0
  92. )
  93. # matching_matrix = matching_matrix.write(b, K.cast(tf.reduce_max(tf.one_hot(pos_idx, tf.shape(cost)[1]), 0), K.dtype(cost)))
  94. return b + 1, matching_matrix
  95. #-----------------------------------------------------------#
  96. # 在这个地方进行一个循环、循环是对每一张图片进行的
  97. #-----------------------------------------------------------#
  98. _, matching_matrix = K.control_flow_ops.while_loop(lambda b,*args: b < tf.cast(num_gt, tf.int32), loop_body_1, [0, matching_matrix])
  99. #------------------------------------------------------------#
  100. # anchor_matching_gt [fg_mask]
  101. #------------------------------------------------------------#
  102. anchor_matching_gt = tf.reduce_sum(matching_matrix, 0)
  103. #------------------------------------------------------------#
  104. # 当某一个特征点指向多个真实框的时候
  105. # 选取cost最小的真实框。
  106. #------------------------------------------------------------#
  107. biger_one_indice = tf.reshape(tf.where(anchor_matching_gt > 1), [-1])
  108. def loop_body_2(b, matching_matrix):
  109. indice_anchor = tf.cast(biger_one_indice[b], tf.int32)
  110. indice_gt = tf.math.argmin(cost[:, indice_anchor])
  111. matching_matrix = tf.concat(
  112. [
  113. matching_matrix[:, :indice_anchor],
  114. tf.expand_dims(tf.one_hot(indice_gt, tf.cast(num_gt, tf.int32)), 1),
  115. matching_matrix[:, indice_anchor+1:]
  116. ], axis = -1
  117. )
  118. return b + 1, matching_matrix
  119. #-----------------------------------------------------------#
  120. # 在这个地方进行一个循环、循环是对每一张图片进行的
  121. #-----------------------------------------------------------#
  122. _, matching_matrix = K.control_flow_ops.while_loop(lambda b,*args: b < tf.cast(tf.shape(biger_one_indice)[0], tf.int32), loop_body_2, [0, matching_matrix])
  123. #------------------------------------------------------------#
  124. # fg_mask_inboxes [fg_mask]
  125. # num_fg为正样本的特征点个数
  126. #------------------------------------------------------------#
  127. fg_mask_inboxes = tf.reduce_sum(matching_matrix, 0) > 0.0
  128. num_fg = tf.reduce_sum(tf.cast(fg_mask_inboxes, K.dtype(cost)))
  129. fg_mask_indices = tf.reshape(tf.where(fg_mask), [-1])
  130. fg_mask_inboxes_indices = tf.reshape(tf.where(fg_mask_inboxes), [-1, 1])
  131. fg_mask_select_indices = tf.gather_nd(fg_mask_indices, fg_mask_inboxes_indices)
  132. fg_mask = tf.cast(tf.reduce_max(tf.one_hot(fg_mask_select_indices, tf.shape(fg_mask)[0]), 0), K.dtype(fg_mask))
  133. #------------------------------------------------------------#
  134. # 获得特征点对应的物品种类
  135. #------------------------------------------------------------#
  136. matched_gt_inds = tf.math.argmax(tf.boolean_mask(matching_matrix, fg_mask_inboxes, axis = 1), 0)
  137. gt_matched_classes = tf.gather_nd(gt_classes, tf.reshape(matched_gt_inds, [-1, 1]))
  138. pred_ious_this_matching = tf.boolean_mask(tf.reduce_sum(matching_matrix * pair_wise_ious, 0), fg_mask_inboxes)
  139. return gt_matched_classes, fg_mask, pred_ious_this_matching, matched_gt_inds, num_fg

4、计算Loss

由第一部分可知,YoloX的损失由三个部分组成:
1、Reg部分,由第三部分可知道每个真实框对应的特征点,获取到每个框对应的特征点后,取出该特征点的预测框,利用真实框和预测框计算IOU损失,作为Reg部分的Loss组成。
2、Obj部分,由第三部分可知道每个真实框对应的特征点,所有真实框对应的特征点都是正样本,剩余的特征点均为负样本,根据正负样本和特征点的是否包含物体的预测结果计算交叉熵损失,作为Obj部分的Loss组成。
3、Cls部分,由第三部分可知道每个真实框对应的特征点,获取到每个框对应的特征点后,取出该特征点的种类预测结果,根据真实框的种类和特征点的种类预测结果计算交叉熵损失,作为Cls部分的Loss组成。

  1. def get_yolo_loss(input_shape, num_layers, num_classes):
  2. def yolo_loss(args):
  3. labels, y_pred = args[-1], args[:-1]
  4. x_shifts = []
  5. y_shifts = []
  6. expanded_strides = []
  7. outputs = []
  8. #-----------------------------------------------#
  9. # inputs [[batch_size, 20, 20, num_classes + 5]
  10. # [batch_size, 40, 40, num_classes + 5]
  11. # [batch_size, 80, 80, num_classes + 5]]
  12. # outputs [[batch_size, 400, num_classes + 5]
  13. # [batch_size, 1600, num_classes + 5]
  14. # [batch_size, 6400, num_classes + 5]]
  15. #-----------------------------------------------#
  16. for i in range(num_layers):
  17. output = y_pred[i]
  18. grid_shape = tf.shape(output)[1:3]
  19. stride = input_shape[0] / tf.cast(grid_shape[0], K.dtype(output))
  20. grid_x, grid_y = tf.meshgrid(K.arange(grid_shape[1]), K.arange(grid_shape[0]))
  21. grid = tf.cast(tf.reshape(tf.stack((grid_x, grid_y), 2), (1, -1, 2)), K.dtype(output))
  22. output = tf.reshape(output, [tf.shape(y_pred[i])[0], grid_shape[0] * grid_shape[1], -1])
  23. output_xy = (output[..., :2] + grid) * stride
  24. output_wh = tf.exp(output[..., 2:4]) * stride
  25. output = tf.concat([output_xy, output_wh, output[..., 4:]], -1)
  26. x_shifts.append(grid[..., 0])
  27. y_shifts.append(grid[..., 1])
  28. expanded_strides.append(tf.ones_like(grid[..., 0]) * stride)
  29. outputs.append(output)
  30. #-----------------------------------------------#
  31. # x_shifts [1, n_anchors_all]
  32. # y_shifts [1, n_anchors_all]
  33. # expanded_strides [1, n_anchors_all]
  34. #-----------------------------------------------#
  35. x_shifts = tf.concat(x_shifts, 1)
  36. y_shifts = tf.concat(y_shifts, 1)
  37. expanded_strides = tf.concat(expanded_strides, 1)
  38. outputs = tf.concat(outputs, 1)
  39. return get_losses(x_shifts, y_shifts, expanded_strides, outputs, labels, num_classes)
  40. return yolo_loss
  41. def get_losses(x_shifts, y_shifts, expanded_strides, outputs, labels, num_classes):
  42. #-----------------------------------------------#
  43. # [batch, n_anchors_all, 4]
  44. # [batch, n_anchors_all, 1]
  45. # [batch, n_anchors_all, n_cls]
  46. #-----------------------------------------------#
  47. bbox_preds = outputs[:, :, :4]
  48. obj_preds = outputs[:, :, 4:5]
  49. cls_preds = outputs[:, :, 5:]
  50. #------------------------------------------------------------#
  51. # labels [batch, max_boxes, 5]
  52. # tf.reduce_sum(labels, -1) [batch, max_boxes]
  53. # nlabel [batch]
  54. #------------------------------------------------------------#
  55. nlabel = tf.reduce_sum(tf.cast(tf.reduce_sum(labels, -1) > 0, K.dtype(outputs)), -1)
  56. total_num_anchors = tf.shape(outputs)[1]
  57. num_fg = 0.0
  58. loss_obj = 0.0
  59. loss_cls = 0.0
  60. loss_iou = 0.0
  61. def loop_body(b, num_fg, loss_iou, loss_obj, loss_cls):
  62. num_gt = tf.cast(nlabel[b], tf.int32)
  63. #-----------------------------------------------#
  64. # gt_bboxes_per_image [num_gt, num_classes]
  65. # gt_classes [num_gt]
  66. # bboxes_preds_per_image [n_anchors_all, 4]
  67. # obj_preds_per_image [n_anchors_all, 1]
  68. # cls_preds_per_image [n_anchors_all, num_classes]
  69. #-----------------------------------------------#
  70. gt_bboxes_per_image = labels[b][:num_gt, :4]
  71. gt_classes = labels[b][:num_gt, 4]
  72. bboxes_preds_per_image = bbox_preds[b]
  73. obj_preds_per_image = obj_preds[b]
  74. cls_preds_per_image = cls_preds[b]
  75. def f1():
  76. num_fg_img = tf.cast(tf.constant(0), K.dtype(outputs))
  77. cls_target = tf.cast(tf.zeros((0, num_classes)), K.dtype(outputs))
  78. reg_target = tf.cast(tf.zeros((0, 4)), K.dtype(outputs))
  79. obj_target = tf.cast(tf.zeros((total_num_anchors, 1)), K.dtype(outputs))
  80. fg_mask = tf.cast(tf.zeros(total_num_anchors), tf.bool)
  81. return num_fg_img, cls_target, reg_target, obj_target, fg_mask
  82. def f2():
  83. gt_matched_classes, fg_mask, pred_ious_this_matching, matched_gt_inds, num_fg_img = get_assignments(
  84. gt_bboxes_per_image, gt_classes, bboxes_preds_per_image, obj_preds_per_image, cls_preds_per_image,
  85. x_shifts, y_shifts, expanded_strides, num_classes, num_gt, total_num_anchors,
  86. )
  87. reg_target = tf.cast(tf.gather_nd(gt_bboxes_per_image, tf.reshape(matched_gt_inds, [-1, 1])), K.dtype(outputs))
  88. cls_target = tf.cast(tf.one_hot(tf.cast(gt_matched_classes, tf.int32), num_classes) * tf.expand_dims(pred_ious_this_matching, -1), K.dtype(outputs))
  89. obj_target = tf.cast(tf.expand_dims(fg_mask, -1), K.dtype(outputs))
  90. return num_fg_img, cls_target, reg_target, obj_target, fg_mask
  91. num_fg_img, cls_target, reg_target, obj_target, fg_mask = tf.cond(tf.equal(num_gt, 0), f1, f2)
  92. num_fg += num_fg_img
  93. loss_iou += K.sum(1 - box_ciou(reg_target, tf.boolean_mask(bboxes_preds_per_image, fg_mask)))
  94. loss_obj += K.sum(K.binary_crossentropy(obj_target, obj_preds_per_image, from_logits=True))
  95. loss_cls += K.sum(K.binary_crossentropy(cls_target, tf.boolean_mask(cls_preds_per_image, fg_mask), from_logits=True))
  96. return b + 1, num_fg, loss_iou, loss_obj, loss_cls
  97. #-----------------------------------------------------------#
  98. # 在这个地方进行一个循环、循环是对每一张图片进行的
  99. #-----------------------------------------------------------#
  100. _, num_fg, loss_iou, loss_obj, loss_cls = K.control_flow_ops.while_loop(lambda b,*args: b < tf.cast(tf.shape(outputs)[0], tf.int32), loop_body, [0, num_fg, loss_iou, loss_obj, loss_cls])
  101. num_fg = tf.cast(tf.maximum(num_fg, 1), K.dtype(outputs))
  102. reg_weight = 5.0
  103. loss = reg_weight * loss_iou + loss_obj + loss_cls
  104. return loss / num_fg

训练自己的YoloX模型

首先前往Github下载对应的仓库,下载完后利用解压软件解压,之后用编程软件打开文件夹。
注意打开的根目录必须正确,否则相对目录不正确的情况下,代码将无法运行。

一定要注意打开后的根目录是文件存放的目录。
在这里插入图片描述

一、数据集的准备

本文使用VOC格式进行训练,训练前需要自己制作好数据集,如果没有自己的数据集,可以通过Github连接下载VOC12+07的数据集尝试下。
训练前将标签文件放在VOCdevkit文件夹下的VOC2007文件夹下的Annotation中。
在这里插入图片描述
训练前将图片文件放在VOCdevkit文件夹下的VOC2007文件夹下的JPEGImages中。
在这里插入图片描述
此时数据集的摆放已经结束。

二、数据集的处理

在完成数据集的摆放之后,我们需要对数据集进行下一步的处理,目的是获得训练用的2007_train.txt以及2007_val.txt,需要用到根目录下的voc_annotation.py。

voc_annotation.py里面有一些参数需要设置。
分别是annotation_mode、classes_path、trainval_percent、train_percent、VOCdevkit_path,第一次训练可以仅修改classes_path

  1. '''
  2. annotation_mode用于指定该文件运行时计算的内容
  3. annotation_mode为0代表整个标签处理过程,包括获得VOCdevkit/VOC2007/ImageSets里面的txt以及训练用的2007_train.txt、2007_val.txt
  4. annotation_mode为1代表获得VOCdevkit/VOC2007/ImageSets里面的txt
  5. annotation_mode为2代表获得训练用的2007_train.txt、2007_val.txt
  6. '''
  7. annotation_mode = 0
  8. '''
  9. 必须要修改,用于生成2007_train.txt、2007_val.txt的目标信息
  10. 与训练和预测所用的classes_path一致即可
  11. 如果生成的2007_train.txt里面没有目标信息
  12. 那么就是因为classes没有设定正确
  13. 仅在annotation_mode为0和2的时候有效
  14. '''
  15. classes_path = 'model_data/voc_classes.txt'
  16. '''
  17. trainval_percent用于指定(训练集+验证集)与测试集的比例,默认情况下 (训练集+验证集):测试集 = 9:1
  18. train_percent用于指定(训练集+验证集)中训练集与验证集的比例,默认情况下 训练集:验证集 = 9:1
  19. 仅在annotation_mode为0和1的时候有效
  20. '''
  21. trainval_percent = 0.9
  22. train_percent = 0.9
  23. '''
  24. 指向VOC数据集所在的文件夹
  25. 默认指向根目录下的VOC数据集
  26. '''
  27. VOCdevkit_path = 'VOCdevkit'

classes_path用于指向检测类别所对应的txt,以voc数据集为例,我们用的txt为:
在这里插入图片描述
训练自己的数据集时,可以自己建立一个cls_classes.txt,里面写自己所需要区分的类别。

三、开始网络训练

通过voc_annotation.py我们已经生成了2007_train.txt以及2007_val.txt,此时我们可以开始训练了。
训练的参数较多,大家可以在下载库后仔细看注释,其中最重要的部分依然是train.py里的classes_path。

classes_path用于指向检测类别所对应的txt,这个txt和voc_annotation.py里面的txt一样!训练自己的数据集必须要修改!
watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDc5MTk2NA_size_16_color_FFFFFF_t_70_pic_center 5
修改完classes_path后就可以运行train.py开始训练了,在训练多个epoch后,权值会生成在logs文件夹中。
其它参数的作用如下:

  1. '''
  2. 是否使用eager模式训练
  3. '''
  4. eager = False
  5. '''
  6. 训练前一定要修改classes_path,使其对应自己的数据集
  7. '''
  8. classes_path = 'model_data/voc_classes.txt'
  9. '''
  10. anchors_path代表先验框对应的txt文件,一般不修改。
  11. anchors_mask用于帮助代码找到对应的先验框,一般不修改。
  12. '''
  13. anchors_path = 'model_data/yolo_anchors.txt'
  14. anchors_mask = [[6, 7, 8], [3, 4, 5], [0, 1, 2]]
  15. '''
  16. 权值文件请看README,百度网盘下载
  17. 训练自己的数据集时提示维度不匹配正常,预测的东西都不一样了自然维度不匹配
  18. 预训练权重对于99%的情况都必须要用,不用的话权值太过随机,特征提取效果不明显
  19. 网络训练的结果也不会好,数据的预训练权重对不同数据集是通用的,因为特征是通用的
  20. '''
  21. model_path = 'model_data/yolo_weight.h5'
  22. '''
  23. 输入的shape大小,一定要是32的倍数
  24. '''
  25. input_shape = [416, 416]
  26. '''
  27. 训练分为两个阶段,分别是冻结阶段和解冻阶段
  28. 冻结阶段训练参数
  29. 此时模型的主干被冻结了,特征提取网络不发生改变
  30. 占用的显存较小,仅对网络进行微调
  31. '''
  32. Init_Epoch = 0
  33. Freeze_Epoch = 50
  34. Freeze_batch_size = 8
  35. Freeze_lr = 1e-3
  36. '''
  37. 解冻阶段训练参数
  38. 此时模型的主干不被冻结了,特征提取网络会发生改变
  39. 占用的显存较大,网络所有的参数都会发生改变
  40. '''
  41. UnFreeze_Epoch = 100
  42. Unfreeze_batch_size = 4
  43. Unfreeze_lr = 1e-4
  44. '''
  45. 是否进行冻结训练,默认先冻结主干训练后解冻训练。
  46. '''
  47. Freeze_Train = True
  48. '''
  49. 用于设置是否使用多线程读取数据,0代表关闭多线程
  50. 开启后会加快数据读取速度,但是会占用更多内存
  51. keras里开启多线程有些时候速度反而慢了许多
  52. 在IO为瓶颈的时候再开启多线程,即GPU运算速度远大于读取图片的速度。
  53. '''
  54. num_workers = 0
  55. '''
  56. 获得图片路径和标签
  57. '''
  58. train_annotation_path = '2007_train.txt'
  59. val_annotation_path = '2007_val.txt'

四、训练结果预测

训练结果预测需要用到两个文件,分别是yolo.py和predict.py。
我们首先需要去yolo.py里面修改model_path以及classes_path,这两个参数必须要修改。

model_path指向训练好的权值文件,在logs文件夹里。
classes_path指向检测类别所对应的txt。

在这里插入图片描述
完成修改后就可以运行predict.py进行检测了。运行后输入图片路径即可检测。

发表评论

表情:
评论列表 (有 0 条评论,381人围观)

还没有评论,来说两句吧...

相关阅读