【darknet源码解析-20】yolo_layer.h 和 yolo_layer.c 源码解析

本系列为darknet源码解析,本次解析src/yolo_layer.h 与 src/yolo_layer.c 两个。yolo_layer主要完成了yolo v3中的三层的detection,分别是52*52*75,26*26*75,13*13*75是yolo v3这篇论文的核心部分。

在阅读本节源码之前,请先了解一下 52*52*75,26*26*75,13*13*75 是什么样子的逻辑存储形式,在物体存储是一维数组;以及yolov3中bbox的[x, y, w, h]是如何进行表示的,本节只解析了yolov3的训练阶段的源码,inference阶段未进行解析;配对的cfg文件为cfg/yolov3-voc.cfg

yolo v3中用多个独立的逻辑回归替代了yolo v2的softmax,对每个标签使用使用二元交叉熵损失,避免使用softmax函数而降低计算复杂度;对[x, y] 和confidence进行逻辑回归;

yolo_layer.h 的定义如下:

#ifndef YOLO_LAYER_H
#define YOLO_LAYER_H

#include "darknet.h"
#include "layer.h"
#include "network.h"

// 构造yolo v3 yolo层
layer make_yolo_layer(int batch, int w, int h, int n, int total, int *mask, int classes);
// yolo层前向传播函数
void forward_yolo_layer(const layer l, network net);
// yolo层反向传播函数
void backward_yolo_layer(const layer l, network net);
void resize_yolo_layer(layer *l, int w, int h);
int yolo_num_detections(layer l, float thresh);

#ifdef GPU
void forward_yolo_layer_gpu(const layer l, network net);
void backward_yolo_layer_gpu(layer l, network net);
#endif

#endif

yolo_layer.c 的详细解释如下:

#include "yolo_layer.h"
#include "activations.h"
#include "blas.h"
#include "box.h"
#include "cuda.h"
#include "utils.h"

#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>

/**
 * 构建yolo v3层中的yolo层
 * @param batch 一个batch中包含图片的张数
 * @param w 输入图片的宽度
 * @param h 输入图片的高度
 * @param n 一个cell预测多少个bbox
 * @param total Anchor bbox的数目
 * @param mask 使用的是0,1,2 还是
 * @param classes 网络需要识别的物体类别数
 * @return
 */
layer make_yolo_layer(int batch, int w, int h, int n, int total, int *mask, int classes)
{
    int i;
    layer l = {0};
    l.type = YOLO; // 层类别

    l.n = n; // 一个cell预测多少个bbox
    l.total = total; // anchors的数目, 为9
    l.batch = batch; // 一个batch包含图片的张数
    l.h = h; // 输入图片的宽度
    l.w = w; // 输入图片的高度
    l.c = n*(classes + 4 + 1); // 输入图片的通道数, 3*(20 + 5)
    l.out_w = l.w; // 输出图片的宽度
    l.out_h = l.h; // 输出图片的高度
    l.out_c = l.c; // 输出图片的通道数
    l.classes = classes; // 网络需要识别的网络
    l.cost = calloc(1, sizeof(float)); // yolo层的总损失
    l.biases = calloc(total*2, sizeof(float)); // 存储bbox的Anchor box的[w,h]
    if(mask) l.mask = mask; // 52*52的时候,mask=[6,7,8] 26*26的时候,mask=[3,4,5], 13*13的时候,mask=[0,1,2]
    else{ // yolo v3 有mask传入,
        l.mask = calloc(n, sizeof(int));
        for(i = 0; i < n; ++i){
            l.mask[i] = i;
        }
    }
    l.bias_updates = calloc(n*2, sizeof(float)); //存储bbox的Anchor box的[w,h]的更新值
    l.outputs = h*w*n*(classes + 4 + 1); // yolo层对应输入type的输出元素个数,yolo层输入输出元素不发生变化
    l.inputs = l.outputs; // yolo层一张输入图片的元素个数
    l.truths = 90*(4 + 1); // GT: 存储90个bbox的信息, 这里是假设图片中GT bbox的数量是小于30的, 这里是写死的;此处与yolov1不同
    l.delta = calloc(batch*l.outputs, sizeof(float)); // yolo层误差项(包含整个batch的)
    l.output = calloc(batch*l.outputs, sizeof(float)); // yolo层所有输出(包含整个batch的)
    // 存储bbox的Anchor box的[w,h]的初始化,在src/parse.c中parse_yolo函数会加载cfg中Anchor尺寸
    for(i = 0; i < total*2; ++i){
        l.biases[i] = .5;
    }

    l.forward = forward_yolo_layer; // yolo层的前向传播
    l.backward = backward_yolo_layer; // yolo层的反向传播
#ifdef GPU
    l.forward_gpu = forward_yolo_layer_gpu;
    l.backward_gpu = backward_yolo_layer_gpu;
    l.output_gpu = cuda_make_array(l.output, batch*l.outputs);
    l.delta_gpu = cuda_make_array(l.delta, batch*l.outputs);
#endif

    fprintf(stderr, "yolo\n");
    srand(0);

    return l;
}

void resize_yolo_layer(layer *l, int w, int h)
{
    l->w = w;
    l->h = h;

    l->outputs = h*w*l->n*(l->classes + 4 + 1);
    l->inputs = l->outputs;

    l->output = realloc(l->output, l->batch*l->outputs*sizeof(float));
    l->delta = realloc(l->delta, l->batch*l->outputs*sizeof(float));

#ifdef GPU
    cuda_free(l->delta_gpu);
    cuda_free(l->output_gpu);

    l->delta_gpu =     cuda_make_array(l->delta, l->batch*l->outputs);
    l->output_gpu =    cuda_make_array(l->output, l->batch*l->outputs);
#endif
}


// get_yolo_box(l.output, l.biases, l.mask[n], box_index, i, j, l.w, l.h, net.w, net.h, l.w*l.h);
box get_yolo_box(float *x, float *biases, int n, int index, int i, int j, int lw, int lh, int w, int h, int stride)
{
    box b;
    b.x = (i + x[index + 0*stride]) / lw; // 预测x 在特征图的的相对位置
    b.y = (j + x[index + 1*stride]) / lh;
    b.w = exp(x[index + 2*stride]) * biases[2*n]   / w; // 相对网络输入图片的宽度
    b.h = exp(x[index + 3*stride]) * biases[2*n+1] / h;
    return b;
}

// delta_yolo_box(truth, l.output, l.biases, l.mask[n], box_index, i, j, l.w, l.h, net.w, net.h, l.delta, (2-truth.w*truth.h), l.w*l.h);
float delta_yolo_box(box truth, float *x, float *biases, int n, int index, int i, int j, int lw, int lh, int w, int h, float *delta, float scale, int stride)
{
    // 获得第j*w+i个cell的第n个bbox在当前特征图的[x,y,w,h]
    box pred = get_yolo_box(x, biases, n, index, i, j, lw, lh, w, h, stride);
    float iou = box_iou(pred, truth); // 计算pred bbox与GT bbox的iou

    float tx = (truth.x*lw - i); // 计算GT bbox的tx, ty, tw, th
    float ty = (truth.y*lh - j);
    float tw = log(truth.w*w / biases[2*n]);
    float th = log(truth.h*h / biases[2*n + 1]);

    delta[index + 0*stride] = scale * (tx - x[index + 0*stride]); // 计算tx, ty, tw, th的梯度
    delta[index + 1*stride] = scale * (ty - x[index + 1*stride]);
    delta[index + 2*stride] = scale * (tw - x[index + 2*stride]);
    delta[index + 3*stride] = scale * (th - x[index + 3*stride]);
    return iou;
}

// delta_yolo_class(l.output, l.delta, class_index, class, l.classes, l.w*l.h, 0);
void delta_yolo_class(float *output, float *delta, int index, int class, int classes, int stride, float *avg_cat)
{
    int n;
    if (delta[index]){ //delta初始化为0, 不会进入此判断
        delta[index + stride*class] = 1 - output[index + stride*class];
        if(avg_cat) *avg_cat += output[index + stride*class];
        return;
    }
    for(n = 0; n < classes; ++n){
        // 计算类别损失的梯度,反向传递到误差项l.delta中
        delta[index + stride*n] = ((n == class)?1 : 0) - output[index + stride*n];
        if(n == class && avg_cat) *avg_cat += output[index + stride*n]; // 统计正确的得分
    }
}

static int entry_index(layer l, int batch, int location, int entry)
{
    int n =   location / (l.w*l.h);
    int loc = location % (l.w*l.h);
    return batch*l.outputs + n*l.w*l.h*(4+l.classes+1) + entry*l.w*l.h + loc;
}

/**
 * yolov3 yolo层的前向传播
 * @param l 当前yolo层
 * @param net 整个网络
 */
void forward_yolo_layer(const layer l, network net)
{
    int i,j,b,t,n;
    // 内存拷贝, l.output = net.input
    memcpy(l.output, net.input, l.outputs*l.batch*sizeof(float));

#ifndef GPU
    for (b = 0; b < l.batch; ++b){
        for(n = 0; n < l.n; ++n){
            int index = entry_index(l, b, n*l.w*l.h, 0); // 获取第b个batch开始的index
            activate_array(l.output + index, 2*l.w*l.h, LOGISTIC); // 对预测的tx,ty进行逻辑回归预测,
            index = entry_index(l, b, n*l.w*l.h, 4); // 获取第b个batch confidence开始的index
            activate_array(l.output + index, (1+l.classes)*l.w*l.h, LOGISTIC); // 对预测的confidence以及class进行逻辑回归
        }
    }
#endif

    // 将yolo层的误差项进行初始化(包含整个batch的)
    memset(l.delta, 0, l.outputs * l.batch * sizeof(float));
    if(!net.train) return; // inference阶段,到此结束
    float avg_iou = 0;
    float recall = 0;
    float recall75 = 0;
    float avg_cat = 0;
    float avg_obj = 0;
    float avg_anyobj = 0;
    int count = 0;
    int class_count = 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, net.w, net.h, l.w*l.h);
                    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(net.truth + t*(4 + 1) + b*l.truths, 1);
                        if(!truth.x) break; // 如果x坐标为0则取消,因为yolov3这里定义了90个bbox
                        float iou = box_iou(pred, truth); // 计算pred bbox与第t个GT bbox之间的iou
                        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);
                    avg_anyobj += l.output[obj_index]; // 统计pred bbox的confidence
                    // 与yolov1相似,先将所有pred bbox都当做noobject, 计算其confidence梯度
                    l.delta[obj_index] = 0 - l.output[obj_index];
                    if (best_iou > l.ignore_thresh) { // best_iou大于阈值则说明pred box有物体,在yolov3中正样本阈值ignore_thresh=.5
                        l.delta[obj_index] = 0;
                    }
                    if (best_iou > l.truth_thresh) { // pred bbox为完全预测正确样本,在yolov3完全预测正确样本的阈值truth_thresh=1.
                        l.delta[obj_index] = 1 - l.output[obj_index];

                        // 获得best_iou对应GT bbox的class的index
                        int class = net.truth[best_t*(4 + 1) + b*l.truths + 4];
                        if (l.map) class = l.map[class]; // yolov3 yolo层中map=0, 不参与计算
                        int class_index = entry_index(l, b, n*l.w*l.h + j*l.w + i, 4 + 1); // 获得best_iou对应pred bbox的class的index

                        delta_yolo_class(l.output, l.delta, class_index, class, l.classes, l.w*l.h, 0);
                        box truth = float_to_box(net.truth + best_t*(4 + 1) + b*l.truths, 1); // 获得best_iou对应GT bbox的[x,y,w,h]的index
                        // 计算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, net.w, net.h, l.delta, (2-truth.w*truth.h), l.w*l.h);
                    }
                }
            }
        }
        for(t = 0; t < l.max_boxes; ++t){
            // 遍历每一个GT bbox
            // 将第t个bbox由float数组转bbox结构体,方便计算iou
            box truth = float_to_box(net.truth + t*(4 + 1) + b*l.truths, 1);

            if(!truth.x) break; // 如果x坐标为0则取消,因为yolov3定义了90个bbox,可能实际上每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]/net.w; // 计算pred bbox的w在相对整张输入图片的位置
                pred.h = l.biases[2*n+1]/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
                }
            }
//            int int_index(int *a, int val, int n)
//            {
//                int i;
//                for(i = 0; i < n; ++i){
//                    if(a[i] == val) return i;
//                }
//                return -1;
//            }

            // 上面记录bbox的编号,是否由该层Anchor预测的
            int mask_n = int_index(l.mask, best_n, l.n);
            if(mask_n >= 0){
                // 获得best_iou对应anchor box的index
                int box_index = entry_index(l, b, mask_n*l.w*l.h + j*l.w + i, 0);
                // 计算best_iou对应Anchor bbox的[x,y,w,h]的梯度
                float iou = delta_yolo_box(truth, l.output, l.biases, best_n, box_index, i, j, l.w, l.h, net.w, net.h, l.delta, (2-truth.w*truth.h), l.w*l.h);
                // 获得best_iou对应anchor box的confidence的index
                int obj_index = entry_index(l, b, mask_n*l.w*l.h + j*l.w + i, 4);
                avg_obj += l.output[obj_index]; //统计confidence
                l.delta[obj_index] = 1 - l.output[obj_index]; // 计算confidence的梯度

                // 获得best_iou对应GT box的class的index
                int class = net.truth[t*(4 + 1) + b*l.truths + 4];
                if (l.map) class = l.map[class];
                // // 获得best_iou对应anchor box的class的index
                int class_index = entry_index(l, b, mask_n*l.w*l.h + j*l.w + i, 4 + 1);
                // 计算class的梯度
                delta_yolo_class(l.output, l.delta, class_index, class, l.classes, l.w*l.h, &avg_cat);

                ++count;
                ++class_count;
                if(iou > .5) recall += 1;
                if(iou > .75) recall75 += 1;
                avg_iou += iou;
            }
        }
    }
    *(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", net.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);
}

/**
 * yolov3 yolo层的反向传播
 * @param l 当前yolo层
 * @param net 整个网络
 */
void backward_yolo_layer(const layer l, network net)
{
    // net.delta += l.delta
    // net.delta指向上一层的delta
   axpy_cpu(l.batch*l.inputs, 1, l.delta, 1, net.delta, 1);
}

void correct_yolo_boxes(detection *dets, int n, int w, int h, int netw, int neth, int relative)
{
    int i;
    int new_w=0;
    int new_h=0;
    if (((float)netw/w) < ((float)neth/h)) {
        new_w = netw;
        new_h = (h * netw)/w;
    } else {
        new_h = neth;
        new_w = (w * neth)/h;
    }
    for (i = 0; i < n; ++i){
        box b = dets[i].bbox;
        b.x =  (b.x - (netw - new_w)/2./netw) / ((float)new_w/netw); 
        b.y =  (b.y - (neth - new_h)/2./neth) / ((float)new_h/neth); 
        b.w *= (float)netw/new_w;
        b.h *= (float)neth/new_h;
        if(!relative){
            b.x *= w;
            b.w *= w;
            b.y *= h;
            b.h *= h;
        }
        dets[i].bbox = b;
    }
}

int yolo_num_detections(layer l, float thresh)
{
    int i, n;
    int count = 0;
    for (i = 0; i < l.w*l.h; ++i){
        for(n = 0; n < l.n; ++n){
            int obj_index  = entry_index(l, 0, n*l.w*l.h + i, 4);
            if(l.output[obj_index] > thresh){
                ++count;
            }
        }
    }
    return count;
}

void avg_flipped_yolo(layer l)
{
    int i,j,n,z;
    float *flip = l.output + l.outputs;
    for (j = 0; j < l.h; ++j) {
        for (i = 0; i < l.w/2; ++i) {
            for (n = 0; n < l.n; ++n) {
                for(z = 0; z < l.classes + 4 + 1; ++z){
                    int i1 = z*l.w*l.h*l.n + n*l.w*l.h + j*l.w + i;
                    int i2 = z*l.w*l.h*l.n + n*l.w*l.h + j*l.w + (l.w - i - 1);
                    float swap = flip[i1];
                    flip[i1] = flip[i2];
                    flip[i2] = swap;
                    if(z == 0){
                        flip[i1] = -flip[i1];
                        flip[i2] = -flip[i2];
                    }
                }
            }
        }
    }
    for(i = 0; i < l.outputs; ++i){
        l.output[i] = (l.output[i] + flip[i])/2.;
    }
}

int get_yolo_detections(layer l, int w, int h, int netw, int neth, float thresh, int *map, int relative, detection *dets)
{
    int i,j,n;
    float *predictions = l.output;
    if (l.batch == 2) avg_flipped_yolo(l);
    int count = 0;
    for (i = 0; i < l.w*l.h; ++i){
        int row = i / l.w;
        int col = i % l.w;
        for(n = 0; n < l.n; ++n){
            int obj_index  = entry_index(l, 0, n*l.w*l.h + i, 4);
            float objectness = predictions[obj_index];
            if(objectness <= thresh) continue;
            int box_index  = entry_index(l, 0, n*l.w*l.h + i, 0);
            dets[count].bbox = get_yolo_box(predictions, l.biases, l.mask[n], box_index, col, row, l.w, l.h, netw, neth, l.w*l.h);
            dets[count].objectness = objectness;
            dets[count].classes = l.classes;
            for(j = 0; j < l.classes; ++j){
                int class_index = entry_index(l, 0, n*l.w*l.h + i, 4 + 1 + j);
                float prob = objectness*predictions[class_index];
                dets[count].prob[j] = (prob > thresh) ? prob : 0;
            }
            ++count;
        }
    }
    correct_yolo_boxes(dets, count, w, h, netw, neth, relative);
    return count;
}

#ifdef GPU

void forward_yolo_layer_gpu(const layer l, network net)
{
    copy_gpu(l.batch*l.inputs, net.input_gpu, 1, l.output_gpu, 1);
    int b, n;
    for (b = 0; b < l.batch; ++b){
        for(n = 0; n < l.n; ++n){
            int index = entry_index(l, b, n*l.w*l.h, 0);
            activate_array_gpu(l.output_gpu + index, 2*l.w*l.h, LOGISTIC);
            index = entry_index(l, b, n*l.w*l.h, 4);
            activate_array_gpu(l.output_gpu + index, (1+l.classes)*l.w*l.h, LOGISTIC);
        }
    }
    if(!net.train || l.onlyforward){
        cuda_pull_array(l.output_gpu, l.output, l.batch*l.outputs);
        return;
    }

    cuda_pull_array(l.output_gpu, net.input, l.batch*l.inputs);
    forward_yolo_layer(l, net);
    cuda_push_array(l.delta_gpu, l.delta, l.batch*l.outputs);
}

void backward_yolo_layer_gpu(const layer l, network net)
{
    axpy_gpu(l.batch*l.inputs, 1, l.delta_gpu, 1, net.delta_gpu, 1);
}
#endif

完,

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
YOLOlayer.h是一个头文件,其中定义了YOLO层的相关函数和结构体。该头文件包含了以下内容: 1. 构造YOLO层的函数make_yolo_layer,用于创建YOLO层的实例。 2. YOLO层的前向传播函数forward_yolo_layer,用于执行YOLO层的前向传播操作。 3. YOLO层的反向传播函数backward_yolo_layer,用于执行YOLO层的反向传播操作。 4. 调整YOLO层大小的函数resize_yolo_layer,用于调整YOLO层的输入尺寸。 5. 计算YOLO层检测结果数量的函数yolo_num_detections,用于计算YOLO层的检测结果数量。 此外,该头文件还包含了一些与GPU相关的函数,如forward_yolo_layer_gpu和backward_yolo_layer_gpu,用于在GPU上执行YOLO层的前向传播和反向传播操作。\[1\] YOLOlayer.h是darknet源码中的一个文件,主要用于实现YOLO v3中的三个detection层,分别对应52*52*75,26*26*75和13*13*75的输出。这些层是YOLO v3论文的核心部分。\[2\] 此外,YOLOlayer.h还与TensorRT加速YOLOv5相关。可以通过GitHub手动获取对应版本的tensorrtx,也可以使用相应版本的指令进行安装。\[3\] #### 引用[.reference_title] - *1* *2* [【darknet源码解析-20yolo_layer.h 和 yolo_layer.c 源码解析](https://blog.csdn.net/caicaiatnbu/article/details/102962445)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [YOLOv5-v3.1,推理环境配置、Tensorrt加速一步到位(各种问题总结,吐血整理)](https://blog.csdn.net/knowledge112233/article/details/126262744)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值