yolov3

YOLOV3网络结构

超详细的Yolo检测框预
https://zhuanlan.zhihu.com/p/49995236

Yolov3使用了darknet-53的前面的52层
在这里插入图片描述

网络结构 和 层理解

layer     filters    size              input                output
   0 conv     32  3 x 3 / 1   416 x 416 x   3   ->   416 x 416 x  32 0.299 BF
   1 conv     64  3 x 3 / 2   416 x 416 x  32   ->   208 x 208 x  64 1.595 BF
   2 conv     32  1 x 1 / 1   208 x 208 x  64   ->   208 x 208 x  32 0.177 BF
   3 conv     64  3 x 3 / 1   208 x 208 x  32   ->   208 x 208 x  64 1.595 BF
   4 Shortcut Layer: 1
   5 conv    128  3 x 3 / 2   208 x 208 x  64   ->   104 x 104 x 128 1.595 BF
   6 conv     64  1 x 1 / 1   104 x 104 x 128   ->   104 x 104 x  64 0.177 BF
   7 conv    128  3 x 3 / 1   104 x 104 x  64   ->   104 x 104 x 128 1.595 BF
   8 Shortcut Layer: 5
   9 conv     64  1 x 1 / 1   104 x 104 x 128   ->   104 x 104 x  64 0.177 BF
  10 conv    128  3 x 3 / 1   104 x 104 x  64   ->   104 x 104 x 128 1.595 BF
  11 Shortcut Layer: 8
  12 conv    256  3 x 3 / 2   104 x 104 x 128   ->    52 x  52 x 256 1.595 BF
  13 conv    128  1 x 1 / 1    52 x  52 x 256   ->    52 x  52 x 128 0.177 BF
  14 conv    256  3 x 3 / 1    52 x  52 x 128   ->    52 x  52 x 256 1.595 BF
  15 Shortcut Layer: 12
  16 conv    128  1 x 1 / 1    52 x  52 x 256   ->    52 x  52 x 128 0.177 BF
  17 conv    256  3 x 3 / 1    52 x  52 x 128   ->    52 x  52 x 256 1.595 BF
  18 Shortcut Layer: 15
  19 conv    128  1 x 1 / 1    52 x  52 x 256   ->    52 x  52 x 128 0.177 BF
  20 conv    256  3 x 3 / 1    52 x  52 x 128   ->    52 x  52 x 256 1.595 BF
  21 Shortcut Layer: 18
  22 conv    128  1 x 1 / 1    52 x  52 x 256   ->    52 x  52 x 128 0.177 BF
  23 conv    256  3 x 3 / 1    52 x  52 x 128   ->    52 x  52 x 256 1.595 BF
  24 Shortcut Layer: 21
  25 conv    128  1 x 1 / 1    52 x  52 x 256   ->    52 x  52 x 128 0.177 BF
  26 conv    256  3 x 3 / 1    52 x  52 x 128   ->    52 x  52 x 256 1.595 BF
  27 Shortcut Layer: 24
  28 conv    128  1 x 1 / 1    52 x  52 x 256   ->    52 x  52 x 128 0.177 BF
  29 conv    256  3 x 3 / 1    52 x  52 x 128   ->    52 x  52 x 256 1.595 BF
  30 Shortcut Layer: 27
  31 conv    128  1 x 1 / 1    52 x  52 x 256   ->    52 x  52 x 128 0.177 BF
  32 conv    256  3 x 3 / 1    52 x  52 x 128   ->    52 x  52 x 256 1.595 BF
  33 Shortcut Layer: 30
  34 conv    128  1 x 1 / 1    52 x  52 x 256   ->    52 x  52 x 128 0.177 BF
  35 conv    256  3 x 3 / 1    52 x  52 x 128   ->    52 x  52 x 256 1.595 BF
  36 Shortcut Layer: 33
  37 conv    512  3 x 3 / 2    52 x  52 x 256   ->    26 x  26 x 512 1.595 BF
  38 conv    256  1 x 1 / 1    26 x  26 x 512   ->    26 x  26 x 256 0.177 BF
  39 conv    512  3 x 3 / 1    26 x  26 x 256   ->    26 x  26 x 512 1.595 BF
  40 Shortcut Layer: 37
  41 conv    256  1 x 1 / 1    26 x  26 x 512   ->    26 x  26 x 256 0.177 BF
  42 conv    512  3 x 3 / 1    26 x  26 x 256   ->    26 x  26 x 512 1.595 BF
  43 Shortcut Layer: 40
  44 conv    256  1 x 1 / 1    26 x  26 x 512   ->    26 x  26 x 256 0.177 BF
  45 conv    512  3 x 3 / 1    26 x  26 x 256   ->    26 x  26 x 512 1.595 BF
  46 Shortcut Layer: 43
  47 conv    256  1 x 1 / 1    26 x  26 x 512   ->    26 x  26 x 256 0.177 BF
  48 conv    512  3 x 3 / 1    26 x  26 x 256   ->    26 x  26 x 512 1.595 BF
  49 Shortcut Layer: 46
  50 conv    256  1 x 1 / 1    26 x  26 x 512   ->    26 x  26 x 256 0.177 BF
  51 conv    512  3 x 3 / 1    26 x  26 x 256   ->    26 x  26 x 512 1.595 BF
  52 Shortcut Layer: 49
  53 conv    256  1 x 1 / 1    26 x  26 x 512   ->    26 x  26 x 256 0.177 BF
  54 conv    512  3 x 3 / 1    26 x  26 x 256   ->    26 x  26 x 512 1.595 BF
  55 Shortcut Layer: 52
  56 conv    256  1 x 1 / 1    26 x  26 x 512   ->    26 x  26 x 256 0.177 BF
  57 conv    512  3 x 3 / 1    26 x  26 x 256   ->    26 x  26 x 512 1.595 BF
  58 Shortcut Layer: 55
  59 conv    256  1 x 1 / 1    26 x  26 x 512   ->    26 x  26 x 256 0.177 BF
  60 conv    512  3 x 3 / 1    26 x  26 x 256   ->    26 x  26 x 512 1.595 BF
  61 Shortcut Layer: 58
  62 conv   1024  3 x 3 / 2    26 x  26 x 512   ->    13 x  13 x1024 1.595 BF
  63 conv    512  1 x 1 / 1    13 x  13 x1024   ->    13 x  13 x 512 0.177 BF
  64 conv   1024  3 x 3 / 1    13 x  13 x 512   ->    13 x  13 x1024 1.595 BF
  65 Shortcut Layer: 62
  66 conv    512  1 x 1 / 1    13 x  13 x1024   ->    13 x  13 x 512 0.177 BF
  67 conv   1024  3 x 3 / 1    13 x  13 x 512   ->    13 x  13 x1024 1.595 BF
  68 Shortcut Layer: 65
  69 conv    512  1 x 1 / 1    13 x  13 x1024   ->    13 x  13 x 512 0.177 BF
  70 conv   1024  3 x 3 / 1    13 x  13 x 512   ->    13 x  13 x1024 1.595 BF
  71 Shortcut Layer: 68
  72 conv    512  1 x 1 / 1    13 x  13 x1024   ->    13 x  13 x 512 0.177 BF
  73 conv   1024  3 x 3 / 1    13 x  13 x 512   ->    13 x  13 x1024 1.595 BF
  74 Shortcut Layer: 71
  75 conv    512  1 x 1 / 1    13 x  13 x1024   ->    13 x  13 x 512 0.177 BF
  76 conv   1024  3 x 3 / 1    13 x  13 x 512   ->    13 x  13 x1024 1.595 BF
  77 conv    512  1 x 1 / 1    13 x  13 x1024   ->    13 x  13 x 512 0.177 BF
  78 conv   1024  3 x 3 / 1    13 x  13 x 512   ->    13 x  13 x1024 1.595 BF
  79 conv    512  1 x 1 / 1    13 x  13 x1024   ->    13 x  13 x 512 0.177 BF
  80 conv   1024  3 x 3 / 1    13 x  13 x 512   ->    13 x  13 x1024 1.595 BF
  81 conv    255  1 x 1 / 1    13 x  13 x1024   ->    13 x  13 x 255 0.088 BF
  82 yolo
  83 route  79
  84 conv    256  1 x 1 / 1    13 x  13 x 512   ->    13 x  13 x 256 0.044 BF
  85 upsample            2x    13 x  13 x 256   ->    26 x  26 x 256
  86 route  85 61
  87 conv    256  1 x 1 / 1    26 x  26 x 768   ->    26 x  26 x 256 0.266 BF
  88 conv    512  3 x 3 / 1    26 x  26 x 256   ->    26 x  26 x 512 1.595 BF
  89 conv    256  1 x 1 / 1    26 x  26 x 512   ->    26 x  26 x 256 0.177 BF
  90 conv    512  3 x 3 / 1    26 x  26 x 256   ->    26 x  26 x 512 1.595 BF
  91 conv    256  1 x 1 / 1    26 x  26 x 512   ->    26 x  26 x 256 0.177 BF
  92 conv    512  3 x 3 / 1    26 x  26 x 256   ->    26 x  26 x 512 1.595 BF
  93 conv    255  1 x 1 / 1    26 x  26 x 512   ->    26 x  26 x 255 0.177 BF
  94 yolo
  95 route  91
  96 conv    128  1 x 1 / 1    26 x  26 x 256   ->    26 x  26 x 128 0.044 BF
  97 upsample            2x    26 x  26 x 128   ->    52 x  52 x 128
  98 route  97 36
  99 conv    128  1 x 1 / 1    52 x  52 x 384   ->    52 x  52 x 128 0.266 BF
 100 conv    256  3 x 3 / 1    52 x  52 x 128   ->    52 x  52 x 256 1.595 BF
 101 conv    128  1 x 1 / 1    52 x  52 x 256   ->    52 x  52 x 128 0.177 BF
 102 conv    256  3 x 3 / 1    52 x  52 x 128   ->    52 x  52 x 256 1.595 BF
 103 conv    128  1 x 1 / 1    52 x  52 x 256   ->    52 x  52 x 128 0.177 BF
 104 conv    256  3 x 3 / 1    52 x  52 x 128   ->    52 x  52 x 256 1.595 BF
 105 conv    255  1 x 1 / 1    52 x  52 x 256   ->    52 x  52 x 255 0.353 BF
 106 yolo

为了降低池化带来的梯度负面效果,摒弃了pooling的方式,改用用conv的stride的方式来实现下采样。用步长为2的卷积来进行下采样。
例如:layer 1:conv,layer 5:conv,layer 12:conv,layer 37:conv,layer 62:conv

layer 82:yolo层(检测层),经历5次stride=2,将特征图缩小到原输入尺寸的(1 / 2)^ 5 ,即1/32。输入为416x416,则输出为13x13 (416/32=13)。由于32倍下采样,这里得到的特征图的感受野最大,因此适合检测图像中尺寸比较大的对象。

layer 83:route 79,取79层特征图做为83层的特征图。
layer 85:upsample,为了实现细粒度的检测,将84层的特征图作上采样。
layer 86:route 85,61 取85层的特征图和61层特征图拼接在一起作为86层的特征图。
layer 94:yolo层(检测层),经历4次stride=2,(没有经过layer 62),得到相对于原输入尺寸的(1 / 2)^ 4,即1/16。输入为416x416,则输出为26x26 (416/16=26)。这样得到了相对输入图像16倍下采样的特征图,具有中等尺度的感受野,适合检测中等尺度的对象。

layer 95:route 91,取91层特征图做为95层的特征图。
layer 97:upsample,为了实现细粒度的检测,将96层的特征图作上采样。
layer 98:route 97,36 取97层的特征图和36层特征图拼接在一起作为98层的特征图。
layer 106:yolo层(检测层),经历3次stride=2,(没有经过layer37,layer 62),得到相对于原输入尺寸的(1 / 2)^ 3,即1/8。输入为416x416,则输出为52x52 (416/8=52)。这样得到的特征图。它的感受野最小,适合检测小尺寸的对象。

3个yolo层(目标检测)采用的都是全卷积的结构,尺度分别是13x13,26×26和52×52。最后一个卷积层的卷积核个数(filters)都是255。对于每一个 yolo 层,3x(80+4+1)=255。3表示 一个这个yolo层的每个grid cell包含3个bounding box,4表示 框的4个坐标信息,1表示 object score, 80 是针对COCO数据集的80类。

先验框

在这里插入图片描述
yolov3用K-means聚类得到先验框的尺寸,并为每种下采样尺度设定3种先验框,总共聚类出9种尺寸的先验框,这9个先验框是:(10x13),(16x30),(33x23),(30x61),(62x45),(59x119),(116x90),(156x198),(373x326)。

  1. 在最小的13x13特征图上(有最大的感受野,下采样stride=32),所以用大的先验框(116x90),(156x198),(373x326),检测大对象。
  2. 在中等的26x26特征图上(有中等的感受野,下采样stride=16),所以用中的先验框(30x61),(62x45),(59x119),检测中等对象。
  3. 在较大的52x52特征图上(有最小的感受野,下采样stride=8),所以用小的先验框(10x13),(16x30),(33x23),检测小对象。

感受一下9种先验框的尺寸,下图中蓝色框为聚类得到的先验框。黄色框式ground truth,红框是对象中心点所在的网格。
在这里插入图片描述

回顾一下

在这里插入图片描述

对象分类 从softmax改成logistic

yolov3采用的是logistic激活函数,分别对 网络的tx,ty预测 和 objectness score 以及 类别预测,代码如下:

#ifndef GPU
    for (b = 0; b < l.batch; ++b) {
        for (n = 0; n < l.n; ++n) {
        	// entry_index 得到指针偏移量,即入口需要的索引
        	// entry=0,loc=0获取的是x的索引,且获取的是第一个x也即l.out_w*l.out_h个网格中第一个网格中第一个矩形框x参数的索引;
        	// 当entry=4时,就是获取矩形框置信度信息c在l.output中的索引;entry=4,loc=1获取的是c的索引,且获取的是第二个c也即l.out_w*l.out_h个网格中第二个网格中第一个矩形框c参数的索引;
            int index = entry_index(l, b, n*l.w*l.h, 0);
			// 对预测的tx,ty进行逻辑回归预测,
            activate_array(l.output + index, 2 * l.w*l.h, LOGISTIC);        // x,y,
            scal_add_cpu(2 * l.w*l.h, l.scale_x_y, -0.5*(l.scale_x_y - 1), l.output + index, 1);    // scale x,y
			index = entry_index(l, b, n*l.w*l.h, 4);
			// 对预测的confidence以及class进行逻辑回归
            activate_array(l.output + index, (1 + l.classes)*l.w*l.h, LOGISTIC);
        }
    }
#endif

l.w l.h 表示当前特征图的宽和高 yolov3中是13x13 26x26 52x52,表示原图被分成的grid cell(网格)数量
l.n 就是当前的 yolo layer上,每一个grid cell(网格)可以预测多少(l.n)个bbox。( 某分支上mask =0,1,2,那么这里的 l.n = 3 )

darknet中,对于logistic的定义:就是完成一个sigmoid激活函数

static inline float logistic_activate(float x){return 1./(1. + exp(-x));}

通过聚类得到anchor boxes(先验框)之后。网络预测的是每个包围框的4个坐标,tx, ty, tw, th。 这里令网格的宽和高都是1,σ函数(sigmoid函数)将tx,ty约束在(0,1)的范围内。如果单元格从图像左上角偏移(cx, cy),并且先验框有宽度和高度pw, ph。那么预测对应于:
在这里插入图片描述
也就是说,预测得到了 tx,ty,tw和th。通过bx,by,bw,bh四个公式的计算得到蓝色的预测框,bx,by是蓝框的中心点坐标,bw,bh是篮框的宽高。

预测对象类别时不使用softmax,改成使用logistic的输出进行预测。 这样能够支持多标签对象分类(比如一个人有Woman 和 Person两个标签)。大多数分类器认为目标分类是互斥的,所以yolov2用的是softmax(全部分类的概率之和为1)。而yolov3为每个分类使用独立的logistic分类器以计算输入属于特定分类的概率。yolov3给每个分类用的是 二分交叉熵,而非MSE 。此举同时降低了计算复杂度。

yolov3使用logistic回归来预测每一个bbox为物体的置信度(objectness score),σ函数(sigmoid函数)将置信度约束在(0,1)的范围内。从9个anchor priors(先验框)中找到了objectness score(目标存在可能性得分)最高的那一个。

loss

forward_network通过l.forward(l, net)计算出l.cost,然后使用calc_network_cost对每个层的cost进行累加。所以计算的cost是三个yolo层共同的cost。
每个yolo层的cost是通过forward_yolo_layer(…)函数中的以下语句执行的:

*(l.cost) = pow(mag_array(l.delta, l.outputs * l.batch), 2);

该语句计算的是单个yolo层中所有通道feature map的元素的delta的平方,代码中用l.delta表示,元素数量为l.outputs * l.batch = l.wl.hl.n * l.batch。主要包括几类内容,序号按代码中出现的先后顺序排列:
① 无目标位置confidence的delta:0 - l.output[obj_index]
② 有目标位置confidence的delta:1 - l.output[obj_index]
③ 有目标位置坐标(x,y,w,h)的delta
④ 有目标位置class的delta
LOSS函数的具体公式如下(这里引用GaintPanda中的公式),第1、2行计算的是③项,第3行计算的是②项,第4行是①项,第5行是④项。

在这里插入图片描述
逻辑:

  1. yolov3修改计算损失函数的方式,如果bbox与真实标签obj重叠区域大于其他所有的,其对应的obj(物体)置信度为1(即选取一个与ground truth有最多重叠的anchor,其对应的obj score为1。所以假设有x个objects, 就只会有x个标签为1的样本,并且只有这些样本参与loss_cls和loss_coor的计算)
  2. 其他与真实标签obj重叠区域超过阈值(默认为0.5)的anchor,在之后的loss中不计算损失。(表示不计算loss_obj也不计算loss_noobj)
  3. 每个ground truth 只允许分配一个boundingbox。如果某个boundingbox没有被分配ground truth,,在之后的loss中不计算其分类和定位损失,只参与计算非目标置信度损失(loss_noobj)。

无目标位置confidence的delta:0 - l.output[obj_index]

遍历每个cell,遍历这个cell下的每个anchor box。取每一个anchor box,先重置best_iou=0,然后遍历所有的gt bbox,计算所有的gt bbox与这个anchor box的iou,找到与这个anchor box的iou最大的gt bbox,记录iou最大的best_iou,记录该gt box的编号t。best_iou大于阈值则说明pred box有物体。如果IOU大于l.ignore_thresh(在cfg文件中为0.7),则delta=0,表示默认这个点是真值,delta是0不意味着l.output[obj_index]==1(就认为是有目标,将其忽略掉)。计算剩下的位置的confidence值的delta,即l.delta[obj_index] = 0 - l.output[obj_index]。目标是将 l.output[obj_index]降为0. //可信度的delta为0-l.output[obj_index],用0做减法,就可以使用交叉熵,不管用不用都不影响

代码:

    *(l.cost) = 0; // yolo层的总损失初始化为0
    for (b = 0; b < l.batch; ++b) {// 遍历batch中的每一张图片
        for (j = 0; j < l.h; ++j) {
            for (i = 0; i < l.w; ++i) {// 遍历每个cell, 当前cell编号[j, i]
                for (n = 0; n < l.n; ++n) {// 遍历每一个bbox, 当前bbox编号 [n]
					// 在这里与yolov2 reorg层是相似的, 获得第j*w+i个cell第n个bbox的index
                    int box_index = entry_index(l, b, n*l.w*l.h + j*l.w + i, 0);
					// 计算第j*w+i个cell第n个bbox在当前特征图上的相对位置[x,y],在网络输入图片上的相对宽度,高度[w,h]
                    box pred = get_yolo_box(l.output, l.biases, l.mask[n], box_index, i, j, l.w, l.h, state.net.w, state.net.h, l.w*l.h);
                    float best_match_iou = 0;
                    int best_match_t = 0;
                    float best_iou = 0; // 保存最大iou
                    int best_t = 0;// 保存最大iou的bbox id
                    for (t = 0; t < l.max_boxes; ++t) {// 遍历每一个GT bbox
						// 将第t个bbox由float数组转bbox结构体,方便计算iou
                        box truth = float_to_box_stride(state.truth + t*(4 + 1) + b*l.truths, 1);
						//获取第t个bbox的类别,检查是否有标注错误
                        int class_id = state.truth[t*(4 + 1) + b*l.truths + 4];
                        if (class_id >= l.classes) {
                            printf(" Warning: in txt-labels class_id=%d >= classes=%d in cfg-file. In txt-labels class_id should be [from 0 to %d] \n", class_id, l.classes, l.classes - 1);
                            printf(" truth.x = %f, truth.y = %f, truth.w = %f, truth.h = %f, class_id = %d \n", truth.x, truth.y, truth.w, truth.h, class_id);
                            getchar();
                            continue; // if label contains class_id more than number of classes in the cfg-file
                        }
						// 如果x坐标为0则取消,因为yolov3这里定义了max_boxes个bbox
                        if (!truth.x) break;  // continue;

                        int class_index = entry_index(l, b, n*l.w*l.h + j*l.w + i, 4 + 1);//预测bbox 类别s下标
                        int obj_index = entry_index(l, b, n*l.w*l.h + j*l.w + i, 4); //预测bbox objectness下标
                        float objectness = l.output[obj_index]; //预测bbox object置信度
						//获得预测bbox 的类别信息,如果某个类别的概率超过0.25返回1
                        int class_id_match = compare_yolo_class(l.output, l.classes, class_index, l.w*l.h, objectness, class_id, 0.25f);

                        float iou = box_iou(pred, truth); // 计算pred bbox与第t个GT bbox之间的iou
						// 这个地方和原始的DarkNet实现不太一样,多了一个class_id_match=1的限制,即预测bbox的置信度必须大于0.25
                        if (iou > best_match_iou && class_id_match == 1) {
                            best_match_iou = iou;
                            best_match_t = t;
                        }
                        if (iou > best_iou) {
                            best_iou = iou; // 记录iou最大的iou
                            best_t = t; // 记录该GT bbox的编号t
                        }
                    }
					// 在这里与yolov2 reorg层是相似的, 获得第j*w+i个cell第n个bbox的confidence
                    int obj_index = entry_index(l, b, n*l.w*l.h + j*l.w + i, 4);
					// 统计pred bbox的confidence
                    avg_anyobj += l.output[obj_index];
					 // 与yolov1相似,先将所有pred bbox都当做noobject, 计算其confidence梯度,不过这里多了一个平衡系数
                    l.delta[obj_index] = l.cls_normalizer * (0 - l.output[obj_index]);
					// best_iou大于阈值则说明pred box有物体,在yolov3中正样本阈值ignore_thresh=.5
                    if (best_match_iou > l.ignore_thresh) {
                        l.delta[obj_index] = 0;
                    }
					// pred bbox为完全预测正确样本,在yolov3完全预测正确样本的阈值truth_thresh=1.
					//这个参数在cfg文件中,值为1,这个条件语句永远不可能成立
                    if (best_iou > l.truth_thresh) {
						// 作者在YOLOV3论文中的第4节提到了这部分。
						// 作者尝试Faster-RCNN中提到的双IOU策略,当Anchor与GT的IoU大于0.7时,该Anchor被算作正样本
						//计入损失中,但训练过程中并没有产生好的结果,所以最后放弃了。
                        l.delta[obj_index] = l.cls_normalizer * (1 - l.output[obj_index]);
						 // 获得best_iou对应GT bbox的class的index
                        int class_id = state.truth[best_t*(4 + 1) + b*l.truths + 4];
						//yolov3 yolo层中map=0, 不参与计算
                        if (l.map) class_id = l.map[class_id]; 
						// 获得best_iou对应pred bbox的class的index
                        int class_index = entry_index(l, b, n*l.w*l.h + j*l.w + i, 4 + 1);
                        delta_yolo_class(l.output, l.delta, class_index, class_id, l.classes, l.w*l.h, 0, l.focal_loss, l.label_smooth_eps, l.classes_multipliers);
                        box truth = float_to_box_stride(state.truth + best_t*(4 + 1) + b*l.truths, 1);
                        const float class_multiplier = (l.classes_multipliers) ? l.classes_multipliers[class_id] : 1.0f;
                        // 计算pred bbox的[x,y,w,h]的梯度
						delta_yolo_box(truth, l.output, l.biases, l.mask[n], box_index, i, j, l.w, l.h, state.net.w, state.net.h, l.delta, (2 - truth.w*truth.h), l.w*l.h, l.iou_normalizer * class_multiplier, l.iou_loss, 1, l.max_delta);
                    }
                }
            }
        }

有目标位置confidence的delta:1 - l.output[obj_index]

遍历每一个GT box,获得当前t个GT bbox所在的cell,遍历每一个anchor bbox找到与GT bbox最大的IOU,yolo层total应该为9,这里采用了预置框进行训练,total为预置框的个数,l.total = 3,目标选出best_n。 //在l.mask中,如果有和最佳预置图片序号相等的,返回mask的序号,没有的话返回-1。delta_yolo_box,计算iou和delta,这里只计算box_index位置有没有目标,和真值差多少,及IOU。
1 - l.output[obj_index];//计算目标点上的Obj的误差
++count;//目标的个数
++class_count;目标class的个数,每运行一次加1,参与每个批次的大循环累加

基本原理是先对比先验框anchors和GT的IOU,确定best_n。通过best_n,在l.mask中,如果有和最佳预置图片序号相等的,返回mask的序号,就认为这个位置是有目标的,然后计算每个有GT且先验框正确的位置上的confidence的delta = 1 - l.output[obj_index]。这个有GT的位置在张量上的坐标为(i,j,mask_n*255+4)。
这时候就有一个问题了,前面计算的无目标点会和后面的有目标点重合,但是这并不影响,针对这几种目标逐个分析:
a)当feature map这个位置本来没有目标,同时也每检测到目标,计算0 - l.output[obj_index],然后调整weight降低这个值,可以减少无目标点的虚警。
b)当feature map这个位置本来有目标,同时又预测到(best_iou>0.7)时,计算1 - l.output[obj_index],然后调整weight降低这个值,可以提升有目标点的准确率。
c)当feature map这个位置本来有目标,但又没有预测到(best_iou≤0.7)时,先令l.delta[obj_index] = 0;然后再计算l.delta[obj_index] = 1 - l.output[obj_index],然后仍然是提升有目标点的准确率。

        for (t = 0; t < l.max_boxes; ++t) {
			//遍历每一个GT box
			// 将第t个bbox由float数组转bbox结构体,方便计算iou
            box truth = float_to_box_stride(state.truth + t*(4 + 1) + b*l.truths, 1);
            if (truth.x < 0 || truth.y < 0 || truth.x > 1 || truth.y > 1 || truth.w < 0 || truth.h < 0) {
                char buff[256];
                printf(" Wrong label: truth.x = %f, truth.y = %f, truth.w = %f, truth.h = %f \n", truth.x, truth.y, truth.w, truth.h);
                sprintf(buff, "echo \"Wrong label: truth.x = %f, truth.y = %f, truth.w = %f, truth.h = %f\" >> bad_label.list",
                    truth.x, truth.y, truth.w, truth.h);
                system(buff);
            }
            int class_id = state.truth[t*(4 + 1) + b*l.truths + 4];
            if (class_id >= l.classes) continue; // if label contains class_id more than number of classes in the cfg-file

            if (!truth.x) break;  // 如果x坐标为0则取消,因为yolov3定义了max_boxes个bbox,可能实际上没那么多
            float best_iou = 0; //保存最大的IOU
            int best_n = 0; //保存最大IOU的bbox index
            i = (truth.x * l.w); // 获得当前t个GT bbox所在的cell
            j = (truth.y * l.h); 
            box truth_shift = truth;
            truth_shift.x = truth_shift.y = 0; //将truth_shift的box位置移动到0,0
            for (n = 0; n < l.total; ++n) { // 遍历每一个anchor bbox找到与GT bbox最大的IOU
                box pred = { 0 };
                pred.w = l.biases[2 * n] / state.net.w; // 计算pred bbox的w在相对整张输入图片的位置
                pred.h = l.biases[2 * n + 1] / state.net.h; // 计算pred bbox的h在相对整张输入图片的位置
                float iou = box_iou(pred, truth_shift); // 计算GT box truth_shift 与 预测bbox pred二者之间的IOU
                if (iou > best_iou) { 
                    best_iou = iou;// 记录最大的IOU
                    best_n = n;// 以及记录该bbox的编号n
                }
            }
            // 上面记录bbox的编号,是否由该层Anchor预测的
            int mask_n = int_index(l.mask, best_n, l.n);
            if (mask_n >= 0) {
                int class_id = state.truth[t*(4 + 1) + b*l.truths + 4];
                if (l.map) class_id = l.map[class_id];
				// 获得best_iou对应anchor box的index
                int box_index = entry_index(l, b, mask_n*l.w*l.h + j*l.w + i, 0);
				//这个参数是用来控制样本数量不均衡的,即Focal Loss中的alpha
                const float class_multiplier = (l.classes_multipliers) ? l.classes_multipliers[class_id] : 1.0f;
				// 计算best_iou对应Anchor bbox的[x,y,w,h]的梯度
                ious all_ious = delta_yolo_box(truth, l.output, l.biases, best_n, box_index, i, j, l.w, l.h, state.net.w, state.net.h, l.delta, (2 - truth.w*truth.h), l.w*l.h, l.iou_normalizer * class_multiplier, l.iou_loss, 1, l.max_delta);

				// 下面的都是模板检测最新的工作,metricl learning,包括IOU/GIOU/DIOU/CIOU Loss
                // range is 0 <= 1
                tot_iou += all_ious.iou;
                tot_iou_loss += 1 - all_ious.iou;
                // range is -1 <= giou <= 1
                tot_giou += all_ious.giou;
                tot_giou_loss += 1 - all_ious.giou;

                tot_diou += all_ious.diou;
                tot_diou_loss += 1 - all_ious.diou;

                tot_ciou += all_ious.ciou;
                tot_ciou_loss += 1 - all_ious.ciou;
				// 获得best_iou对应anchor box的confidence的index
                int obj_index = entry_index(l, b, mask_n*l.w*l.h + j*l.w + i, 4);
				//统计confidence
                avg_obj += l.output[obj_index];
				// 计算confidence的梯度
                l.delta[obj_index] = class_multiplier * l.cls_normalizer * (1 - l.output[obj_index]);
				// 获得best_iou对应GT box的class的index
                int class_index = entry_index(l, b, mask_n*l.w*l.h + j*l.w + i, 4 + 1);
				// 获得best_iou对应anchor box的class的index
                delta_yolo_class(l.output, l.delta, class_index, class_id, l.classes, l.w*l.h, &avg_cat, l.focal_loss, l.label_smooth_eps, l.classes_multipliers);

                ++count;
                ++class_count;
                if (all_ious.iou > .5) recall += 1;
                if (all_ious.iou > .75) recall75 += 1;
            }

			//下面这个过程和上面一样,不过多约束了一个iou_thresh
            // iou_thresh
            for (n = 0; n < l.total; ++n) {
                int mask_n = int_index(l.mask, n, l.n);
                if (mask_n >= 0 && n != best_n && l.iou_thresh < 1.0f) {
                    box pred = { 0 };
                    pred.w = l.biases[2 * n] / state.net.w;
                    pred.h = l.biases[2 * n + 1] / state.net.h;
                    float iou = box_iou(pred, truth_shift);
                    // iou, n

                    if (iou > l.iou_thresh) {
                        int class_id = state.truth[t*(4 + 1) + b*l.truths + 4];
                        if (l.map) class_id = l.map[class_id];

                        int box_index = entry_index(l, b, mask_n*l.w*l.h + j*l.w + i, 0);
                        const float class_multiplier = (l.classes_multipliers) ? l.classes_multipliers[class_id] : 1.0f;
                        ious all_ious = delta_yolo_box(truth, l.output, l.biases, n, box_index, i, j, l.w, l.h, state.net.w, state.net.h, l.delta, (2 - truth.w*truth.h), l.w*l.h, l.iou_normalizer * class_multiplier, l.iou_loss, 1, l.max_delta);

                        // range is 0 <= 1
                        tot_iou += all_ious.iou;
                        tot_iou_loss += 1 - all_ious.iou;
                        // range is -1 <= giou <= 1
                        tot_giou += all_ious.giou;
                        tot_giou_loss += 1 - all_ious.giou;

                        tot_diou += all_ious.diou;
                        tot_diou_loss += 1 - all_ious.diou;

                        tot_ciou += all_ious.ciou;
                        tot_ciou_loss += 1 - all_ious.ciou;

                        int obj_index = entry_index(l, b, mask_n*l.w*l.h + j*l.w + i, 4);
                        avg_obj += l.output[obj_index];
                        l.delta[obj_index] = class_multiplier * l.cls_normalizer * (1 - l.output[obj_index]);

                        int class_index = entry_index(l, b, mask_n*l.w*l.h + j*l.w + i, 4 + 1);
                        delta_yolo_class(l.output, l.delta, class_index, class_id, l.classes, l.w*l.h, &avg_cat, l.focal_loss, l.label_smooth_eps, l.classes_multipliers);

                        ++count;
                        ++class_count;
                        if (all_ious.iou > .5) recall += 1;
                        if (all_ious.iou > .75) recall75 += 1;
                    }
                }
            }
        }
        // averages the deltas obtained by the function: delta_yolo_box()_accumulate
        for (j = 0; j < l.h; ++j) {
            for (i = 0; i < l.w; ++i) {
                for (n = 0; n < l.n; ++n) {
					// 在这里与yolov2 reorg层是相似的, 获得第j*w+i个cell第n个bbox的index
                    int box_index = entry_index(l, b, n*l.w*l.h + j*l.w + i, 0);
					//获得第j*w+i个cell第n个bbox的类别
                    int class_index = entry_index(l, b, n*l.w*l.h + j*l.w + i, 4 + 1);
					//特征图的大小
                    const int stride = l.w*l.h;
					//对梯度进行平均
                    averages_yolo_deltas(class_index, box_index, stride, l.classes, l.delta);
                }
            }
        }
    }

    //*(l.cost) = pow(mag_array(l.delta, l.outputs * l.batch), 2);
    //printf("Region %d Avg IOU: %f, Class: %f, Obj: %f, No Obj: %f, .5R: %f, .75R: %f,  count: %d\n", state.index, avg_iou / count, avg_cat / class_count, avg_obj / count, avg_anyobj / (l.w*l.h*l.n*l.batch), recall / count, recall75 / count, count);

    int stride = l.w*l.h;
    float* no_iou_loss_delta = (float *)calloc(l.batch * l.outputs, sizeof(float));
    memcpy(no_iou_loss_delta, l.delta, l.batch * l.outputs * sizeof(float));
    for (b = 0; b < l.batch; ++b) {
        for (j = 0; j < l.h; ++j) {
            for (i = 0; i < l.w; ++i) {
                for (n = 0; n < l.n; ++n) {
					//yolov3如果使用的是iou loss,也就是metric learning的方式,那么x,y,w,h的loss可以设置为0
                    int index = entry_index(l, b, n*l.w*l.h + j*l.w + i, 0);
                    no_iou_loss_delta[index + 0 * stride] = 0;
                    no_iou_loss_delta[index + 1 * stride] = 0;
                    no_iou_loss_delta[index + 2 * stride] = 0;
                    no_iou_loss_delta[index + 3 * stride] = 0;
                }
            }
        }
    }
	//计算所有的分类loss
    float classification_loss = l.cls_normalizer * pow(mag_array(no_iou_loss_delta, l.outputs * l.batch), 2);
    free(no_iou_loss_delta);
	//计算总的loss
    float loss = pow(mag_array(l.delta, l.outputs * l.batch), 2);
	//计算回归loss
    float iou_loss = loss - classification_loss;

    float avg_iou_loss = 0;
    // gIOU loss + MSE (objectness) loss
    if (l.iou_loss == MSE) {
        *(l.cost) = pow(mag_array(l.delta, l.outputs * l.batch), 2);
    }
    else {
        // Always compute classification loss both for iou + cls loss and for logging with mse loss
        // TODO: remove IOU loss fields before computing MSE on class
        //   probably split into two arrays
        if (l.iou_loss == GIOU) {
            avg_iou_loss = count > 0 ? l.iou_normalizer * (tot_giou_loss / count) : 0;
        }
        else {
			//count代表目标个数
            avg_iou_loss = count > 0 ? l.iou_normalizer * (tot_iou_loss / count) : 0;
        }
        *(l.cost) = avg_iou_loss + classification_loss;
    }

    loss /= l.batch;
    classification_loss /= l.batch;
    iou_loss /= l.batch;

    printf("v3 (%s loss, Normalizer: (iou: %f, cls: %f) Region %d Avg (IOU: %f, GIOU: %f), Class: %f, Obj: %f, No Obj: %f, .5R: %f, .75R: %f, count: %d, loss = %f, class_loss = %f, iou_loss = %f\n",
        (l.iou_loss == MSE ? "mse" : (l.iou_loss == GIOU ? "giou" : "iou")), l.iou_normalizer, l.cls_normalizer, state.index, tot_iou / count, tot_giou / count, avg_cat / class_count, avg_obj / count, avg_anyobj / (l.w*l.h*l.n*l.batch), recall / count, recall75 / count, count,
        loss, classification_loss, iou_loss);
}

二分交叉熵,而非MSE

使用MSE作为损失函数
在这里插入图片描述
计算梯度
在这里插入图片描述
可以看到使用MSE作为损失函数的话,它的梯度是和sigmod函数的导数有关的。w的梯度跟激活函数σ ′ ( z ) 的梯度成正比。假设当前模型的输出接近1时,σ ′ ( z ) 就会非常小,接近0,使得求得w的梯度很小,损失函数收敛的很慢。

使用交叉熵作为损失函数
在这里插入图片描述
计算梯度
在这里插入图片描述
从结果可以看出梯度中不再含有sigmoid的导数,有的是sigmoid的值和实际值之间的差,误差大的话更新的就快,误差小的话就更新的慢点,这满足了我们之前所说的错误越大,下降的越快。因此,我们需要用交叉熵而不是MSE作为损失函数。

参考文章
https://blog.csdn.net/taoqick/article/details/102621605
https://pjreddie.com/media/files/papers/YOLOv3.pdf
https://blog.csdn.net/litt1e/article/details/88907542
https://www.jianshu.com/p/d13ae1055302
https://blog.csdn.net/leviopku/article/details/82660381
https://blog.csdn.net/just_sort/article/details/104345016
https://blog.csdn.net/ying86615791/article/details/103584065
https://zhuanlan.zhihu.com/p/142662181
https://zhuanlan.zhihu.com/p/61944055
https://blog.csdn.net/qq_41736617/article/details/106583800

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值