11、yolo.py文件解读

0、前言

文件位置:./models/yolo.py
https://www.zhihu.com/question/399884529/answer/2271806378
yolov5深度剖析+源码debug级讲解系列(二)backbone构建

这个文件是YOLOv5网络模型的搭建文件,如果你想改进YOLOv5,那么这么文件是你必须进行修改的文件之一。文件内容看起来多,其实真正有用的代码不多的,重点理解好我文中提到的一个函数两个类即可。

注:由于YOLOv5版本众多,同一个文件对于细节处你可能会看到不同的版本,不用担心这都是正常的,注意把握好整体架构即可。

● 📌
本次任务:将YOLOv5s网络模型中的C3模块按照下图方式修改形成C2模块,并将C2模块插入第2层与第3层之间,且跑通YOLOv5s。 ●
💫 任务提示: ○ 提示1:需要修改common.yaml、yolo.py、yolov5s.yaml文件。 ○
提示2:C2模块与C3模块是非常相似的两个模块,我们要插入C2到模型当中,只需要找到哪里有C3模块,然后在其附近加上C2即可。
● 📌本篇文章内容均来自K同学一对一辅导教案,博客发表仅用于学习记录,不做商业用途。
在这里插入图片描述
C2模块结构图
在这里插入图片描述

一、导入需要的包和基本配置

import argparse            # 解析命令行参数模块
import os    
import platform 
import sys                 # sys系统模块 包含了与Python解释器和它的环境有关的函数
from copy import deepcopy  # 数据拷贝模块 深拷贝
from pathlib import Path   # Path将str转换为Path对象 使字符串路径易于操作的模块

FILE = Path(__file__).resolve()
ROOT = FILE.parents[1]             # YOLOv5 root directory
if str(ROOT) not in sys.path:
    sys.path.append(str(ROOT))     # add ROOT to PATH
if platform.system() != 'Windows':
    ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative

from models.common import *
from models.experimental import *
from utils.autoanchor import check_anchor_order
from utils.general import LOGGER, check_version, check_yaml, make_divisible, print_args
from utils.plots import feature_visualization
from utils.torch_utils import (fuse_conv_and_bn, initialize_weights, model_info, profile, scale_img, select_device,
                               time_sync)

# 导入thop包 用于计算FLOPs
try:
    import thop  # for FLOPs computation
except ImportError:
    thop = None

二、parse_model函数

解析模型文件(从model中传来的字典形式),并搭建网络结构。
这个函数用于将模型的模块拼接起来,搭建完成的网络模型。后续如果需要动模型框架的话,你需要对这个函数做相应的改动。

这是一个用于解析 yaml 文件以创建网络模型的函数,以 yolov5s.yaml 为例讲一下解析过程 (在 models 文件夹中):

depth_multiple:表示网络深度增益 (针对 yaml 文件中每一行的 “number”),计算方法如下:

n=max(1,round(n⋅dm))

这个文件中 depth_multiple = 0.33,则是将网络深度缩小 3 倍
width_multiple:表示卷积通道增益 (针对每个网络单元的输出通道数),计算方法如下:

c2=8⋅ceil(c2⋅wm/8)

这个文件中 width_multiple = 0.5,则是将卷积通道数缩小 2 倍

def parse_model(d, ch):  # model_dict, input_channels(3)  
                         # d:yaml 配置文件 (字典类型)  ch:输入图像的通道数,例如 RGB 格式图像的 ch = 3
    """用在上面Model模块中
    解析模型文件(字典形式),并搭建网络结构
    这个函数其实主要做的就是: 更新当前层的args(参数),计算c2(当前层的输出channel) =>
                          使用当前层的参数搭建当前层 =>
                          生成 layers + save
    :params d: model_dict 模型文件 字典形式 {dict:7}  yolov5s.yaml中的6个元素 + ch
    :params ch: 记录模型每一层的输出channel 初始ch=[3] 后面会删除
    :return nn.Sequential(*layers): 网络的每一层的层结构
    :return sorted(save): 把所有层结构中from不是-1的值记下 并排序 [4, 6, 10, 14, 17, 20, 23]
    """
    # 使用logging 模块输出列标签
    logger.info('\n%3s%18s%3s%10s  %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments'))
    # 读取yaml文件的参数:先验框,分类数,深度增益,通道增益(读取d字典中的anchors和parameters(nc、depth_multiple、width_multiple)
    anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
    # na: number of anchors 每一个predict head上的anchor数 = 3  (每组先验框包含的先验框数)
    na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors
    # no: number of outputs 每一个predict head层的输出channel = anchors * (classes + 5) = 75(VOC)     (na:na*属性数(5+分类数))
    no = na * (nc + 5) # number of outputs = anchors*(classess + 5)

    # 开始搭建网络
    # layers: 保存每一层的层结构                         网络单元列表
    # save: 记录下所有层结构中from中不是-1的层结构序号    网络输出引用列表
    # c2: 保存当前层的输出channel                        当前的输出通道数
    layers, save, c2 = [], [], ch[-1]  # layers, savelist,ch out
    
    # 读取 backbone  ,head  中的网络单元
         # from(当前层输入来自哪些层), number(当前层次数 初定), module(当前层类别), args(当前层类参数 初定)
    for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']):  # 遍历backbone和head的每一层
        # 利用eval函数  读取model参数对应的类
           # eval(string) 得到当前层的真实类名 例如: m= Focus -> <class 'models.common.Focus'>
        m = eval(m) if isinstance(m, str) else m  # eval strings

        # 没什么用,使用eval函数将字符串转换为变量
        for j, a in enumerate(args):
            try:
                args[j] = eval(a) if isinstance(a, str) else a  # eval strings
            except:
                pass
        # ------------------- 更新当前层的args(参数),计算c2(当前层的输出channel) -------------------
        # 使用gd(深度增益)计算网络单元串联深度/对应卷积单元的参数n
            # depth gain 控制深度  如v5s: n*0.33   n: 当前模块的次数(间接控制深度)
            # 这里的n表示结构的个数,也就是说,n是个>=1的整数(起码得有一个,否则不存在),depth_multiple越大,那么模型结构的个数也越多,因此网络就更”深“。
        n = max(round(n * gd), 1) if n > 1 else n  # depth gain    深度因子参与运算
        # 这些模块就是common.py所含有的模块, 如果在common.py添加新的模块,还需要在这边添加 
        if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, DWConv, MixConv2d,
                 Focus, CrossConv, BottleneckCSP, C3, C3TR, CBAM]:
            # c1: 当前层的输入的channel数  c2: 当前层的输出的channel数(初定)  ch: 记录着所有层的输出channel   ch[f]即from参数对应的输出通道数
            c1, c2 = ch[f], args[0]
            # if not output  no=75  只有最后一层c2=no  最后一层不用控制宽度,输出channel必须是no
            if c2 != no:
                # width gain 控制宽度  如v5s: c2*0.5  c2: 当前层的最终输出的channel数(间接控制宽度)
                # 令输出通道数为8的倍数,c2代表当前层的输出的通道(channel)数,也就是说,width_multiple越大,那么模型结构的通道数越多,因此看起来就更”宽“。
                c2 = make_divisible(c2 * gw, 8)  # 宽度因子参与运算
            # 在初始arg的基础上更新 加入当前层的输入channel并更新当前层   ( yaml字典中不含有输入通道数,补上  ,指定新的输出通道数)
            args = [c1, c2, *args[1:]]  # [in_channel, out_channel, *args[1:]]
            # 如果当前层是BottleneckCSP/C3/C3TR, 则需要在args中加入bottleneck的个数
            # [in_channel, out_channel, Bottleneck的个数n, bool(True表示有shortcut 默认,反之无)]
            if m in [BottleneckCSP, C3, C3TR]:
                # 当网络单元有n参数,补上
                args.insert(2, n)  #   number of repeats    在第二个位置插入bottleneck个数n
                n = 1  # 恢复默认值1
        # BN  只有一个参数: from 参数对应的输出通道数
        elif m is nn.BatchNorm2d:
            # BN层只需要返回上一层的输出channel
            args = [ch[f]]
        # Concat: from 为1个列表,输出通道数为多个网络单元输出通道数的和
        elif m is Concat:
            # Concat层则将f中所有的输出累加得到这层的输出channel
            c2 = sum([ch[x] for x in f])
        # Detect检测头 
        elif m is Detect:  # Detect(YOLO Layer)层
            # 在args中加入三个Detect层的输出channel    (根据from 参数找到对应的输出通道数,确定Detect的ch参数)
            args.append([ch[x] for x in f])
            # 如果先验框参数是一个int,  则所有先验框长宽均为该数
            if isinstance(args[1], int):  # number of anchors  几乎不执行
                args[1] = [list(range(args[1] * 2))] * len(f)
        # Contract,  Expend:计算对应的输出通道数
        elif m is Contract:  # 不怎么用
            c2 = ch[f] * args[0] ** 2
        elif m is Expand:   # 不怎么用
            c2 = ch[f] // args[0] ** 2
        elif m is SELayer:  # 加入SE模块
            channel, re = args[0], args[1]
            channel = make_divisible(channel * gw, 8) if channel != no else channel
            args = [channel, re]
        else:
            # Upsample
            c2 = ch[f]  # args不变
        # -----------------------------------------------------------------------------------

        # m_: 得到当前层module  如果n>1就创建多个m(当前层结构), 如果n=1就创建一个m
        m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args)

        # 打印当前层结构的一些基本信息
        t = str(m)[8:-2].replace('__main__.', '')  # t = module type   'modules.common.Focus'
        # 计算该网络层的参数量
        np = sum([x.numel() for x in m_.parameters()])  # number params  计算这一层的参数量
        #  设置网格层的实例属性
        m_.i, m_.f, m_.type, m_.np = i, f, t, np  # index, 'from' index, number, type, number params
        # 使用logging 模块输出该网络层的信息
        logger.info('%3s%18s%3s%10.0f  %-40s%-30s' % (i, f, n, np, t, args))  # print

        # append to savelist  把所有层结构中from不是-1的值记下  [6, 4, 14, 10, 17, 20, 23]   (保存除-1之外的from参数到save列表)
        save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1)   # append to savelist 

        # 将当前层结构module加入layers中,保存该网络层
        layers.append(m_)

        if i == 0:
            ch = []  # 去除输入channel [3]

        # 把当前层的输出channel数加入ch,存储该网络层的通道数信息
        ch.append(c2)
        
    # nn.Sequential(*layers):网络层列表
    # sorted(save): 对于上面的yaml文件,输出是 [4,6,10,14,17,20,23],即from 参数的集合
    return nn.Sequential(*layers), sorted(save)

三、Detect类

Detect模块是用来构建Detect层的,将输入feature map通过一个卷积操作和公式计算到我们想要的shape,为后面的计算损失或者NMS作准备。
Detect 对象是 YOLO 网络模型的最后一层 (对应 yaml 文件最后一行),通过 yaml 文件进行声明,格式为:

[*from], 1, Detect, [nc, anchors]

其中 nc 为分类数,anchors 为先验框,修改 yaml 文件的前几行即可

在 parse_model 函数中,会根据 from 参数,找到对应网络层的输出通道数 (ch:列表)。传参给 Detect 对象后,生成对应的 Conv2d

nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch)

其中,self.no 为 分类数 (80) + 检测框属性数 (5),self.na 为每个矩阵输出对应的先验框数 (3)

class Detect(nn.Module):
    """Detect模块是用来构建Detect层的,将输入feature map 通过一个卷积操作和公式计算到我们想要的shape, 为后面的计算损失或者NMS作准备"""
    stride = None  # strides computed during build
    onnx_dynamic = False  # ONNX export parameter

    def __init__(self, nc=80, anchors=(), ch=(), inplace=True):
        """
        detection layer 相当于yolov3中的YOLOLayer层
        :params nc: number of classes
        :params anchors: 传入3个feature map上的所有anchor的大小(P3、P4、P5)
        :params ch: [128, 256, 512] 3个输出feature map的channel
        """
        super(Detect, self).__init__()
        self.nc = nc  # number of classes VOC: 20
        self.no = nc + 5  # number of outputs per anchor  VOC: 5+20=25  xywhc+20classes
        self.nl = len(anchors)  # number of detection layers   Detect的个数 3
        self.na = len(anchors[0]) // 2  # number of anchors  每个feature map的anchor个数 3
        self.grid = [torch.zeros(1)] * self.nl  # init grid  {list: 3}  tensor([0.]) X 3
        # a=[3, 3, 2]  anchors以[w, h]对的形式存储  3个feature map 每个feature map上有三个anchor(w,h)
        a = torch.tensor(anchors).float().view(self.nl, -1, 2)
        # register_buffer
        # 模型中需要保存的参数一般有两种:一种是反向传播需要被optimizer更新的,称为parameter; 另一种不要被更新称为buffer
        # buffer的参数更新是在forward中,而optim.step只能更新nn.parameter类型的参数
        # shape(nl,na,2)
        self.register_buffer('anchors', a)
        # shape(nl,1,na,1,1,2)
        self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2))
        # output conv 对每个输出的feature map都要调用一次conv1x1
        self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch)
        # use in-place ops (e.g. slice assignment) 一般都是True 默认不使用AWS Inferentia加速
        self.inplace = inplace

    def forward(self, x):
        """
        :return train: 一个tensor list 存放三个元素   [bs, anchor_num, grid_w, grid_h, xywh+c+20classes]
                       分别是 [1, 3, 80, 80, 25] [1, 3, 40, 40, 25] [1, 3, 20, 20, 25]
                inference: 0 [1, 19200+4800+1200, 25] = [bs, anchor_num*grid_w*grid_h, xywh+c+20classes]
                           1 一个tensor list 存放三个元素 [bs, anchor_num, grid_w, grid_h, xywh+c+20classes]
                             [1, 3, 80, 80, 25] [1, 3, 40, 40, 25] [1, 3, 20, 20, 25]
        """
        # x = x.copy()  # for profiling
        z = []  # inference output   
        for i in range(self.nl):  # 对三个feature map分别进行处理
            # 调用Conv2d进行计算
            x[i] = self.m[i](x[i])  # conv  xi[bs, 128/256/512, 80, 80] to [bs, 75, 80, 80]
            bs, _, ny, nx = x[i].shape
            # [bs, 75, 80, 80] to [1, 3, 25, 80, 80] to [1, 3, 80, 80, 25]
            # 维度重排列: bs, 先验框组数, 检测框行数, 检测框列数, 属性数 + 分类数
            x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()

            # inference
            if not self.training:
                # 构造网格
                # 因为推理返回的不是归一化后的网格偏移量 需要再加上网格的位置 得到最终的推理坐标 再送入nms
                # 所以这里构建网格就是为了纪律每个grid的网格坐标 方面后面使用
                if self.grid[i].shape[2:4] != x[i].shape[2:4] or self.onnx_dynamic:
                    # 加载网络点坐标,先验框尺寸
                    self.grid[i] = self._make_grid(nx, ny).to(x[i].device)

                y = x[i].sigmoid()
                # stride:相对于原图像的尺寸缩小倍数
                if self.inplace:
                    # 默认执行 不使用AWS Inferentia
                    # 这里的公式和yolov3、v4中使用的不一样 是yolov5作者自己用的 效果更好
                    y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i]  # xy
                    # y[..., 2:4] = torch.exp(y[..., 2:4]) * self.anchor_wh     # wh yolo method
                    y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i]  # wh power method
                else:  # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953
                    xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i]  # xy
                    wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i].view(1, self.na, 1, 1, 2) # wh
                    y = torch.cat((xy, wh, y[..., 4:]), -1)
                # z是一个tensor list 三个元素 分别是[1, 19200, 25] [1, 4800, 25] [1, 1200, 25]
                # 存储检测框信息
                z.append(y.view(bs, -1, self.no))

        return x if self.training else (torch.cat(z, 1), x)

    @staticmethod
    def _make_grid(nx=20, ny=20):
        """
        构造网格
        """
        yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
        return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()

四、Model

这个模块是整个模型的搭建模块。且yolov5的作者将这个模块的功能写的很全,不光包含模型的搭建,还扩展了很多功能如:特征可视化,打印模型信息、TTA推理增强、融合Conv+Bn加速推理、模型搭载nms功能、autoshape函数:模型包含前处理、推理、后处理的模块(预处理 + 推理 + nms)。感兴趣的可以仔细看看,不感兴趣的可以直接看__init__和forward两个函数即可。
Model 对象的声明语句如下:

Model(cfg=‘yolov5s.yaml’, ch=3, nc=None, anchors=None)

cfg:yaml 文件,将调用 parse_model 函数得到网络结构
ch:输入图像的通道数,例如 RGB 格式图像的 ch = 3
nc:分类数,如果设置了则会覆盖 yaml 字典的 nc 参数
anchors:先验框尺寸 (3 行 6 列),如果设置了则会覆盖 yaml 字典的 anchors 参数
初始化:

调用 parse_model 函数得到网络结构
调用 self._initialize_biases,修改 Detect 实例的 Conv2d 的 bias
如果最后一层是 Detect,则计算网络模型使图像尺寸缩小的倍数,记为 stride;同时将先验框的尺寸除以对应的 stride
调用 utils.torch_utils.initialize_weights,初始化网络参数
调用 utils.torch_utils.model_info,输出 网络深度、参数量、梯度量

Model模块代码:

class Model(nn.Module):
    def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None):
        """
        :params cfg:模型配置文件
        :params ch: input img channels 一般是3 RGB文件
        :params nc: number of classes 数据集的类别个数
        :anchors: 一般是None
        """
        super(Model, self).__init__()
        if isinstance(cfg, dict):
            self.yaml = cfg  # model dict
        else:
            # is *.yaml  一般执行这里
            import yaml  # for torch hub
            self.yaml_file = Path(cfg).name  # cfg file name = yolov5s.yaml
            # 如果配置文件中有中文,打开时要加encoding参数
            with open(cfg, encoding='utf-8') as f:
                # model dict  取到配置文件中每条的信息(没有注释内容)
                self.yaml = yaml.safe_load(f)    
                # model dict
                
        # Define model
        # input channels  ch=3
        ch = self.yaml['ch'] = self.yaml.get('ch', ch)
        # 设置类别数 一般不执行, 因为nc=self.yaml['nc']恒成立
        if nc and nc != self.yaml['nc']:
            logger.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
            self.yaml['nc'] = nc  # override yaml value
        # 重写anchor,一般不执行, 因为传进来的anchors一般都是None
        if anchors:
            logger.info(f'Overriding model.yaml anchors with anchors={anchors}')
            self.yaml['anchors'] = round(anchors)  # override yaml value

        # 创建网络模型
        # self.model: 初始化的整个网络模型(包括Detect层结构)
        # self.save: 所有层结构中from不等于-1的序号,并排好序  [4, 6, 10, 14, 17, 20, 23]
        self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch])

        # default class names ['0', '1', '2',..., '19']
        self.names = [str(i) for i in range(self.yaml['nc'])]

        # self.inplace=True  默认True  不使用加速推理
        # AWS Inferentia Inplace compatiability
        # https://github.com/ultralytics/yolov5/pull/2953
        self.inplace = self.yaml.get('inplace', True)
        # logger.info([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))])

        # 获取Detect模块的stride(相对输入图像的下采样率)和anchors在当前Detect输出的feature map的尺度
        m = self.model[-1]  # Detect()
        if isinstance(m, Detect):
            s = 256  # 2x min stride
            m.inplace = self.inplace
            # 计算三个feature map下采样的倍率  [8, 16, 32]
            m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))])  # forward
            # 求出相对当前feature map的anchor大小 如[10, 13]/8 -> [1.25, 1.625]
            m.anchors /= m.stride.view(-1, 1, 1)
            # 检查anchor顺序与stride顺序是否一致
            check_anchor_order(m)
            self.stride = m.stride
            self._initialize_biases()  # only run once 初始化偏置
            # logger.info('Strides: %s' % m.stride.tolist())

        # Init weights, biases
        initialize_weights(self)  # 调用torch_utils.py下initialize_weights初始化模型权重
        self.info()  # 打印模型信息
        logger.info('')

    def forward(self, x, augment=False, profile=False):
        # augmented inference, None  上下flip/左右flip
        # 是否在测试时也使用数据增强  Test Time Augmentation(TTA)
        # augemnt:是否使用增强式推导,是则调用self._forward_augment,否则调用self._forward_once
        # profile:是否测试每个网络层的性能
        # visulize: 是否输出每个网络层的特征图
        if augment:
            return self.forward_augment(x)
        else:
            # 默认执行 正常前向推理
            # single-scale inference, train
            return self.forward_once(x, profile)

    def forward_augment(self, x):
        """
        TTA Test Time Augmentation
       [增强式推导,其 x 参数是图像所对应的 tensor。这个函数只在 val、detect 主函数中使用,用于提高推导的精度
       设分类数为 80 、检测框属性数为 5,则基本步骤是:
       1、对图像进行变换:总共 3 次,分别是 \[ 原图 \],\[ 尺寸缩小到原来的 0.83,同时水平翻转 \],\[ 尺寸缩小到原来的 0.67 \]
       2、对图像使用 _forward_once 函数,得到在 eval 模式下网络模型的推导结果。对原图是 shape 为 \[1, 22743, 85\] 的图像检测框信息 (见 Detect 对象的 forward 函数)
       3、根据 尺寸缩小倍数、翻转维度 对检测框信息进行逆变换,添加进列表 y
       4、截取 y\[0\] 对大物体的检测结果,保留 y\[1\] 所有的检测结果,截取 y\[2\] 对小物体的检测结果,拼接得到新的检测框信息](https://blog.csdn.net/qq_55745968/article/details/124512331?spm=1001.2014.3001.5506) 
        """
        img_size = x.shape[-2:]  # height, width
        # 尺寸变换:不变,缩小到原0.83,缩小到原0.67
        s = [1, 0.83, 0.67]  # scales ratio
        # 维度翻转:无,水平翻转,无
        f = [None, 3, None]  # flips (2-ud上下flip, 3-lr左右flip)
        y = []  # outputs
        for si, fi in zip(s, f):
            # 对图像进行变换,scale_img缩放图片尺寸
            xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
            # 得到整个模型的推导结果
            yi = self.forward_once(xi)[0]  # forward
            # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1])  # save
            # 将推导结果进行逆变换,_descale_pred将推理结果恢复到相对原图图片尺寸
            yi = self._descale_pred(yi, fi, si, img_size)
            y.append(yi)
        # 截取y[0]对大物体检测结果,保留y[1]的检测结果,截取y[2]对小物体的检测结果
        # y = self.clip_augmented(y)   # clip augmented tails

        # 对所有检测框进行拼接,得到新的检测框信息
        return torch.cat(y, 1), None  # augmented inference, train

    def forward_once(self, x, profile=False, feature_vis=False):
        """
        :params x: 输入图像
        :params profile: True 可以做一些性能评估
        :params feature_vis: True 可以做一些特征可视化
        :return train: 一个tensor list 存放三个元素   [bs, anchor_num, grid_w, grid_h, xywh+c+20classes]
                       分别是 [1, 3, 80, 80, 25] [1, 3, 40, 40, 25] [1, 3, 20, 20, 25]
                inference: 0 [1, 19200+4800+1200, 25] = [bs, anchor_num*grid_w*grid_h, xywh+c+20classes]
                           1 一个tensor list 存放三个元素 [bs, anchor_num, grid_w, grid_h, xywh+c+20classes]
                             [1, 3, 80, 80, 25] [1, 3, 40, 40, 25] [1, 3, 20, 20, 25]
        """
        # y: 存放着self.save=True的每一层的输出,因为后面的层结构concat等操作要用到
        # dt: 在profile中做性能评估时使用
        y, dt = [], []
        for m in self.model:
            # 前向推理每一层结构   m.i=index   m.f=from   m.type=类名   m.np=number of params
            # if not from previous layer   m.f=当前层的输入来自哪一层的输出  s的m.f都是-1
            if m.f != -1:
                # 这里需要做4个concat操作和1个Detect操作
                # concat操作如m.f=[-1, 6] x就有两个元素,一个是上一层的输出,另一个是index=6的层的输出 再送到x=m(x)做concat操作
                # Detect操作m.f=[17, 20, 23] x有三个元素,分别存放第17层第20层第23层的输出 再送到x=m(x)做Detect的forward
                x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]  # from earlier layers

            # 打印日志信息  FLOPs time等
            if profile:
                o = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 if thop else 0  # FLOPs
                t = time_synchronized()
                for _ in range(10):
                    _ = m(x)
                dt.append((time_synchronized() - t) * 100)
                if m == self.model[0]:
                    logger.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s}  {'module'}")
                logger.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f}  {m.type}')

            x = m(x)  # run正向推理  

            # 存放着self.save的每一层的输出,因为后面需要用来作concat等操作要用到  不在self.save层的输出就为None
            y.append(x if m.i in self.save else None)

            # 特征可视化 可以自己改动想要哪层的特征进行可视化
            if feature_vis and m.type == 'models.common.SPP':
                feature_visualization(x, m.type, m.i)

        # 打印日志信息  前向推理时间
        if profile:
            logger.info('%.1fms total' % sum(dt))
        return x

    def _initialize_biases(self, cf=None):
        """用在上面的__init__函数上
        initialize biases into Detect(), cf is class frequency
        https://arxiv.org/abs/1708.02002 section 3.3
        """
        # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
        m = self.model[-1]  # Detect() module
        for mi, s in zip(m.m, m.stride):  # from
            b = mi.bias.view(m.na, -1)  # conv.bias(255) to (3,85)
            b.data[:, 4] += math.log(8 / (640 / s) ** 2)  # obj (8 objects per 640 image)
            b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum())  # cls
            mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)

    def info(self, verbose=False, img_size=640):  # print model information
        """用在上面的__init__函数上
        调用torch_utils.py下model_info函数打印模型信息
        """
        model_info(self, verbose, img_size)

    def _descale_pred(self, p, flips, scale, img_size):
        """用在上面的__init__函数上
        将推理结果恢复到原图图片尺寸  Test Time Augmentation(TTA)中用到
        de-scale predictions following augmented inference (inverse operation)
        :params p: 推理结果
        :params flips:
        :params scale:
        :params img_size:
        """
        # 不同的方式前向推理使用公式不同 具体可看Detect函数
        if self.inplace:  # 默认执行 不使用AWS Inferentia
            p[..., :4] /= scale  # de-scale
            if flips == 2:
                p[..., 1] = img_size[0] - p[..., 1]  # de-flip ud
            elif flips == 3:
                p[..., 0] = img_size[1] - p[..., 0]  # de-flip lr
        else:
            x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale  # de-scale
            if flips == 2:
                y = img_size[0] - y  # de-flip ud
            elif flips == 3:
                x = img_size[1] - x  # de-flip lr
            p = torch.cat((x, y, wh, p[..., 4:]), -1)
        return p

    def _print_biases(self):
        """
        打印模型中最后Detect层的偏置bias信息(也可以任选哪些层bias信息)
        """
        m = self.model[-1]  # Detect() module
        for mi in m.m:  # from
            b = mi.bias.detach().view(m.na, -1).T  # conv.bias(255) to (3,85)
            logger.info(
                ('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))

    def _print_weights(self):
        """
        打印模型中Bottleneck层的权重参数weights信息(也可以任选哪些层weights信息)
        """
        for m in self.model.modules():
            if type(m) is Bottleneck:
                logger.info('%10.3g' % (m.w.detach().sigmoid() * 2))  # shortcut weights

    def fuse(self):
        """用在detect.py、val.py
        fuse model Conv2d() + BatchNorm2d() layers
        调用torch_utils.py中的fuse_conv_and_bn函数和common.py中Conv模块的fuseforward函数
        """
        logger.info('Fusing layers... ')  # 日志
        # 遍历每一层结构
        for m in self.model.modules():
            # 如果当前层是卷积层Conv且有bn结构, 那么就调用fuse_conv_and_bn函数讲conv和bn进行融合, 加速推理
            if type(m) is Conv and hasattr(m, 'bn'):
                m.conv = fuse_conv_and_bn(m.conv, m.bn)  # 融合 update conv
                delattr(m, 'bn')  # 移除bn remove batchnorm
                m.forward = m.fuseforward  # 更新前向传播 update forward (反向传播不用管, 因为这种推理只用在推理阶段)
        self.info()  # 打印conv+bn融合后的模型信息
        return self

    def nms(self, mode=True):
        """
        add or remove NMS module
        可以自选是否扩展model 增加模型nms功能  直接调用common.py中的NMS模块
         一般是用不到的 前向推理结束直接掉用non_max_suppression函数即可
        """
        present = type(self.model[-1]) is NMS  # last layer is NMS
        if mode and not present:
            logger.info('Adding NMS... ')
            m = NMS()  # module
            m.f = -1  # from
            m.i = self.model[-1].i + 1  # index
            self.model.add_module(name='%s' % m.i, module=m)  # add nms module to model
            self.eval()  # nms 开启模型验证模式
        elif not mode and present:
            logger.info('Removing NMS... ')
            self.model = self.model[:-1]  # remove nms from model
        return self

    def autoshape(self):
        """
        add AutoShape module  直接调用common.py中的AutoShape模块  也是一个扩展模型功能的模块
        """
        logger.info('Adding AutoShape... ')
        # wrap model 扩展模型功能 此时模型包含前处理、推理、后处理的模块(预处理 + 推理 + nms)
        m = AutoShape(self)
        copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=())  # copy attributes
        return m

参考1
参考2
参考3
参考4
参考5

五、模型调整

./models/common.py 参考C3模块结构增加C2模块

class C2(nn.Module):
    # CSP Bottleneck with 3 convolutions
    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, number, shortcut, groups, expansion
        super().__init__()
        c_ = int(c2 * 0.5)  # hidden channels
        self.cv1 = Conv(c1, c_, 1, 1)
        self.cv2 = Conv(c1, c_, 1, 1)
        self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))

    def forward(self, x):
        # 移除cv3卷积层后,若要保持最终输出的channel仍为c2,则中间层的channel需为c2/2
        # 设置e=0.5即可,取默认值不变
        return torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1)


class C3(nn.Module):
    # CSP Bottleneck with 3 convolutions
    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, number, shortcut, groups, expansion
        ''' 在C3RT模块和yolo.py的parse_model函数中被调用
        :params c1: 整个C3的输入channel
        :params c2: 整个C3的输出channel
        :params n: 有n个子模块[Bottleneck/CrossConv]
        :params shortcut: bool值,子模块[Bottlenec/CrossConv]中是否有shortcut,默认True
        :params g: 子模块[Bottlenec/CrossConv]中的3x3卷积类型,=1普通卷积,>1深度可分离卷积
        :params e: expansion ratio,e*c2=中间其它所有层的卷积核个数=中间所有层的的输入输出channel
        '''
        super().__init__()
        c_ = int(c2 * e)  # hidden channels
        self.cv1 = Conv(c1, c_, 1, 1)
        self.cv2 = Conv(c1, c_, 1, 1)
        self.cv3 = Conv(2 * c_, c2, 1)  # optional act=FReLU(c2)
        self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))
        # 实验性 CrossConv
        #self.m = nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)])

    def forward(self, x):
        return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))


./models/yolo.py 在parse_model中增加对C2的解析

def parse_model(d, ch):  # model_dict, input_channels(3)
    # Parse a YOLOv5 model.yaml dictionary
    ''' 用在上面DetectionModel模块中
    解析模型文件(字典形式),并搭建网络结构
    这个函数其实主要做的就是:
        更新当前层的args(参数),计算c2(当前层的输出channel)
        ->使用当前层的参数搭建当前层
        ->生成 layers + save
    :params d: model_dict模型文件,字典形式{dice: 7}(yolov5s.yaml中的6个元素 + ch)
    :params ch: 记录模型每一层的输出channel,初始ch=[3],后面会删除
    :return nn.Sequential(*layers): 网络的每一层的层结构
    :return sorted(save): 把所有层结构中的from不是-1的值记下,并排序[4,6,10,14,17,20,23]
    '''
    LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10}  {'module':<40}{'arguments':<30}")
    # 读取字典d中的anchors和parameters(nc,depth_multiple,width_multiple)
    anchors, nc, gd, gw, act = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'], d.get('activation')
    if act:
        Conv.default_act = eval(act)  # redefine default activation, i.e. Conv.default_act = nn.SiLU()
        LOGGER.info(f"{colorstr('activation:')} {act}")  # print
    # na: number of anchors 每一个predict head上的anchor数=3
    na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors  # number of anchors
    # no: number of outputs 每一个predict head层的输出channel=anchors*(classes+5)=75(VOC)
    no = na * (nc + 5)  # number of outputs = anchors * (classes + 5)

    ''' 开始搭建网络
    layers: 保存每一层的层结构
    save: 记录下所有层结构中from不是-1的层结构序号
    c2: 保存当前层的输出channel
    '''
    layers, save, c2 = [], [], ch[-1]  # layers, savelist, ch out
    # from: 当前层输入来自哪些层
    # number: 当前层数,初定
    # module: 当前层类别
    # args: 当前层类参数,初定
    # 遍历backbone和head的每一层
    for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']):  # from, number, module, args
        # 得到当前层的真实类名,例如:m = Focus -> <class 'models.common.Focus'>
        m = eval(m) if isinstance(m, str) else m  # eval strings
        # 没什么用
        for j, a in enumerate(args):
            with contextlib.suppress(NameError):
                args[j] = eval(a) if isinstance(a, str) else a  # eval strings

        # --------------------更新当前层的args(参数),计算c2(当前层的输出channel)--------------------
        # depth gain 控制深度,如yolov5s: n*0.33,n: 当前模块的次数(间接控制深度)
        n = n_ = max(round(n * gd), 1) if n > 1 else n  # depth gain
        if m in {
                Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,
                BottleneckCSP, C2, C3, C3TR, C3SPP, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x}:
            # c1: 当前层的输入channel数; c2: 当前层的输出channel数(初定); ch: 记录着所有层的输出channel数
            c1, c2 = ch[f], args[0]
            # no=75,只有最后一层c2=no,最后一层不用控制宽度,输出channel必须是no
            if c2 != no:  # if not output
                # width gain 控制宽度,如yolov5s: c2*0.5; c2: 当前层的最终输出channel数(间接控制宽度)
                c2 = make_divisible(c2 * gw, 8)

            # 在初始args的基础上更新,加入当前层的输入channel并更新当前层
            # [in_channels, out_channels, *args[1:]]
            args = [c1, c2, *args[1:]]
            # 如果当前层是BottleneckCSP/C2/C3/C3TR/C3Ghost/C3x,则需要在args中加入Bottleneck的个数
            # [in_channels, out_channels, Bottleneck个数, Bool(shortcut有无标记)]
            if m in {BottleneckCSP, C2, C3, C3TR, C3Ghost, C3x}:
                args.insert(2, n)  # number of repeats 在第二个位置插入Bottleneck的个数n
                n = 1 # 恢复默认值1
        elif m is nn.BatchNorm2d:
            # BN层只需要返回上一层的输出channel
            args = [ch[f]]
        elif m is Concat:
            # Concat层则将f中所有的输出累加得到这层的输出channel
            c2 = sum(ch[x] for x in f)
        # TODO: channel, gw, gd
        elif m in {Detect, Segment}:  # Detect/Segment(YOLO Layer)层
            # 在args中加入三个Detect层的输出channel
            args.append([ch[x] for x in f])
            if isinstance(args[1], int):  # number of anchors 几乎不执行
                args[1] = [list(range(args[1] * 2))] * len(f)
            if m is Segment:
                args[3] = make_divisible(args[3] * gw, 8)
        elif m is Contract:  # 不怎么用
            c2 = ch[f] * args[0] ** 2
        elif m is Expand:  # 不怎么用
            c2 = ch[f] // args[0] ** 2
        else:  # Upsample
            c2 = ch[f]  # args不变
        # -------------------------------------------------------------------------------------------

        # m_: 得到当前层的module,如果n>1就创建多个m(当前层结构),如果n=1就创建一个m
        m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args)  # module
        # 打印当前层结构的一些基本信息
        t = str(m)[8:-2].replace('__main__.', '')  # module type  <'modules.common.Focus'>
        np = sum(x.numel() for x in m_.parameters())  # number params 计算这一层的参数量
        m_.i, m_.f, m_.type, m_.np = i, f, t, np  # attach index, 'from' index, type, number params
        LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f}  {t:<40}{str(args):<30}')  # print
        # 把所有层结构中的from不是-1的值记下 [6,4,14,10,17,20,23]
        save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1)  # append to savelist
        # 将当前层结构module加入layers中
        layers.append(m_)
        if i == 0:
            ch = []  # 去除输入channel[3]
        # 把当前层的输出channel数加入ch
        ch.append(c2)
    return nn.Sequential(*layers), sorted(save)

./models/yolov5s.yaml 在原第2层和原第3层之间插入C2模块

# YOLOv5 v6.0 backbone
backbone:
  # [from, number, module, args]
  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2
   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4
   [-1, 3, C3, [128]],
   [-1, 3, C2, [128]],  # 在原第2层和原第3层之间插入C2模块
   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8
   [-1, 6, C3, [256]],
   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16
   [-1, 9, C3, [512]],
   [-1, 1, Conv, [1024, 3, 2]],  # 7-P5/32
   [-1, 3, C3, [1024]],
   [-1, 1, SPPF, [1024, 5]],  # 9
  ]

运行与模型打印:
python train.py --img 640 --batch 8 --epoch 1 --data data/fruits.yaml --cfg models/yolov5s.yaml --weights weights/yolov5s.pt --device 0

正确结果:
在这里插入图片描述

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦在黎明破晓时啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值