YOLOv5-第Y5周:yolo.py文件解读

一、前言

文件位置:./models/yolo.py

yolo.py文件是YOLOv5网络模型的搭建文件。在YOLOv5源码中,模型的建立是依靠yolo.py文件中的函数和对象完成的。可以通过修改yolo.py来改进YOLOv5。这个文件主要由三个部分:parse_model函数、Detect类、Model类组成。

二、导包和基本配置

2.1 导入安装好的python库

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

2.2 获取当前文件的路径

作用: 1、将当前项目添加到系统路径上,使得项目中的模块可以调用。

​ 2、将当前项目的相对路径保存到ROOT中,便于寻找项目中的文件。

FILE = Path(__file__).resolve()	 # __file__指的是当前文件(即val.py),FILE最终保存着当前文件的绝对路径,比如D://yolov5/models/yolo.py
ROOT = FILE.parents[1]  # YOLOv5 root directory  # 保存着当前项目的父目录,比如 D://yolov5
if str(ROOT) not in sys.path:   # sys.path即当前python环境可以运行的路径,加入当前项目不在该路径中,就无法运行其中的模块,所以需要加载路径
    sys.path.append(str(ROOT))  # add ROOT to PATH  # 把ROOT添加到运行路径上
if platform.system() != 'Windows':
    ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative  # ROOT设置为相对路径

2.3 加载自定义模块

用户自定义库,顺序不可调换。

model.common: YOLOv5的网络结构。

model.experimental: 实验性质的代码,包括MixConv2d、跨层权重Sum等。

utils.autoanchor: 定义了自动生成锚框的方法。

utils.general: 定义了一些常用的工具函数,比如检查文件是否存在、检查图像大小是否符合要求、打印命令行参数等。

utils.plots: 定义了Annotator类,可以在图像上绘制矩形框和标注信息。

utils.torch_utils: 定义了一些与Pytorch有关的工具函数,比如选择设备、同步事件等。

from models.common import *  # noqa				 # yolov5的网络结构(yolov5)
from models.experimental import *  # noqa		 # 导入在线下载模块
from utils.autoanchor import check_anchor_order	 # 导入检查achors合法性的函数
from utils.general import LOGGER, check_version, check_yaml, make_divisible, print_args		# 定义了一些常用的工具函数
from utils.plots import feature_visualization	 # 定义了Annotator类,可以在图像上绘制矩形框和标注信息
from utils.torch_utils import (fuse_conv_and_bn, initialize_weights, model_info, profile, scale_img, select_device,
                               time_sync)		 # 定义了一些与Pytorch有关的工具函数

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

三、parse_model函数

parse_model函数用在DetectionModel模块中,主要作用是解析yaml的模块,通过读取yaml文件夹中的配置,并且到common.py中找到相对于的模块,然后组成一个相对完整的模型解析模型文件(字典形式),并搭建网络结构。

​ 即把yaml文件中的网络结构实例化成对应的模型,后续如果需要动模型框架的话,需要对这个函数做相应的改动。

​ 更新当前层的args(参数),计算c2(当前层的输出channel) = > 使用当前层的参数搭建当前层 = > 生成layers + save。

3.1 获取对应参数

这段代码主要是获取配置dict里面的参数,并打印最开始展示的网络结构表的表头。

: params d: yaml配置文件 model_dict 模型文件 字典形式 {dict:7},yolov5s.yaml中的6个元素+ch

: params ch: 记录模型每一层的输出channel,初始ch=[3],后面会删除

na: 判断anchor的数量

no: 根据anchor数量推断的输出维度

def parse_model(d, ch):  # model_dict, input_channels(3)
    # Parse a YOLOv5 model.yaml dictionary
    
    # 使用logging模块输出列标签
    
    LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10}  {'module':<40}{'arguments':<30}")
    
    # 获取anchors, 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: 每组先验框包含的先验框数
    na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors  # number of anchors
    
    # no: na * (属性数+5) 
    no = na * (nc + 5)  # number of outputs = anchors * (classes + 5)

3.2 搭建网络前的准备

这段代码主要是遍历backbone和head的每一层,获取搭建网络前的一系列信息。

layers: 保存每一层的层结构

save: 记录下所有层结构中from不是-1的层结构序号

c2: 保存当前层的输出channel

然后开始迭代循环backbone和head的配置。for i, (f, n, m, args) in enumerate(d[‘backbone’] + d[‘head’]):中的参数:

f: from,当前输入来自哪些层

n: number,当前层次数 初定

m: model,当前层类别

args: 当前层类参数 初定

函数eval(): 主要作用是将字符串当成有效的表达式来求值,并且返回执行的结果。实现list、dict、tuple与str之间的转化。

# 网络单元列表、网络输出引用列表、当前的输出通道数
layers, save, c2 = [], [], ch[-1]  # layers, savelist, ch out

	# 读取backbone、head中的网络单元
    for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']):  # from, number, module, args
    	# 利用eval()函数,读取model对应的类名 如'Focus','Conv'等
        m = eval(m) if isinstance(m, str) else m  # eval strings
        # 利用eval()函数,将字符串转换为变量 如'None','nc','anchors'
        for j, a in enumerate(args):
            with contextlib.suppress(NameError):
                args[j] = eval(a) if isinstance(a, str) else a  # eval strings

3.3 更新当前层的参数,计算c2

# 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, C3, C3TR, C3SPP, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x}:
            # c1:当前网络层的输入channel数;c2:当前层的输出channel数(初定);ch:记录着所有层的输出channel数
            c1, c2 = ch[f], args[0]
            if c2 != no:  # if not output
                c2 = make_divisible(c2 * gw, 8)

3.4 使用当前层的参数搭建当前层

# 再初始args基础上更新,加入当前层的输入channel并更新当前层
# [in_channel, out_channel, *args[1:]]
args = [c1, c2, *args[1:]]
			# 如果当前层是BottleneckCSP/C3/C3TR,则需要在args中加入bottleneck的个数
			# [in_channel, out_channel, Bottleneck的个数m, bool(True表示有shortcut 默认, 反之无)]
            if m in {BottleneckCSP, C3, C3TR, C3Ghost, C3x}:
                args.insert(2, n)  # number of repeats # 在第2个位置插入bottleneck的个数m
                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(YOLO Layer)层
        	# 在args中加入三个Detect层的输出channel
            args.append([ch[x] for x in f])
            if isinstance(args[1], int):  # number of anchors # number of channel 几乎不执行
                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:
            c2 = ch[f]

3.5 打印和保存layers

# m_: 得到当前层的model 如果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
        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
        save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1)  # append to savelist  把所有层结构中from不是-1的值记下 
        
        # 将当前层的model加入到layer中
        layers.append(m_)
        if i == 0:
            ch = [] # 去除输入channel[3]
        
        # 把当前层的输入channel数加入ch
        ch.append(c2)
    return nn.Sequential(*layers), sorted(save)

四、Detect类

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

[*from], 1, Detect, [nc, anchors]
class Detect(nn.Module):
    # YOLOv5 Detect head for detection models
    stride = None  # strides computed during build
    dynamic = False  # force grid reconstruction
    export = False  # export mode

    def __init__(self, nc=80, anchors=(), ch=(), inplace=True):  # detection layer
    	"""
    	detextion layer 相当于yolov3中的YOLO Layer层
    	:params nc: number of classes
    	:params anchors: 传入3个feature map上的所有anchor的大小(P3、P4、P5)
    	:params ch: [128, 256, 512] 3个输出feature map上的channel
    	"""
        super().__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 up上的anchor数 3
        self.grid = [torch.empty(0) for _ in range(self.nl)]  # init grid  {list: 3} tensor([0.]) X 3
        self.anchor_grid = [torch.empty(0) for _ in range(self.nl)]  # init anchor grid
        # register_buffer
        # 模型中需要保存的参数一般有两种:一种是反向传播需要被optimizer更新的,成为parameter; 另一种不需要被更新的称为buffer
        # buffer的蚕食更新是在forward中, 而optim.step只能更新nn.parameter类型的参数
        self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2))  # shape(nl,na,2)
        self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch)  # output conv
        self.inplace = inplace  # use inplace ops (e.g. slice assignment)

    def forward(self, x):
        z = []  # inference output
        for i in range(self.nl):
            x[i] = self.m[i](x[i])  # conv
            bs, _, ny, nx = x[i].shape  # x(bs,255,20,20) to x(bs,3,20,20,85)
            x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()

            if not self.training:  # inference
            	# 构造网络
            	# 因为推理返回的不是归一化后的网格偏移量,需要再加上网格的位置,得到最终的推理坐标, 再送入NMS
            	# 所以这里构建网络就是为了记录每个grid网格坐标,方便后面再使用
                if self.dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]:
                    self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)

                if isinstance(self, Segment):  # (boxes + masks)
                    xy, wh, conf, mask = x[i].split((2, 2, self.nc + 1, self.no - self.nc - 5), 4)
                    xy = (xy.sigmoid() * 2 + self.grid[i]) * self.stride[i]  # xy
                    wh = (wh.sigmoid() * 2) ** 2 * self.anchor_grid[i]  # wh
                    y = torch.cat((xy, wh, conf.sigmoid(), mask), 4)
                else:  # Detect (boxes only)
                    xy, wh, conf = x[i].sigmoid().split((2, 2, self.nc + 1), 4)
                    xy = (xy * 2 + self.grid[i]) * self.stride[i]  # xy
                    wh = (wh * 2) ** 2 * self.anchor_grid[i]  # wh
                    y = torch.cat((xy, wh, conf), 4)
                z.append(y.view(bs, self.na * nx * ny, self.no))

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

    def _make_grid(self, nx=20, ny=20, i=0, torch_1_10=check_version(torch.__version__, '1.10.0')):
        d = self.anchors[i].device
        t = self.anchors[i].dtype
        shape = 1, self.na, ny, nx, 2  # grid shape
        y, x = torch.arange(ny, device=d, dtype=t), torch.arange(nx, device=d, dtype=t)
        yv, xv = torch.meshgrid(y, x, indexing='ij') if torch_1_10 else torch.meshgrid(y, x)  # torch>=0.7 compatibility
        grid = torch.stack((xv, yv), 2).expand(shape) - 0.5  # add grid offset, i.e. y = 2.0 * x - 0.5
        anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape)
        return grid, anchor_grid

五、Model类

Model类是整个模型的搭建模块,通过自定义YOLO模型类,继承torch.nn.model。主要作用是指定模型的yaml文件以及一系列的训练参数。

class DetectionModel(BaseModel):
    # YOLOv5 detection model
    def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None):  # model, input channels, number of classes
    	"""
    	:params cfg: 模型配置文件
    	:params ch: input img channels 一般是3 RGB文件
    	:params nc: number of classes 数据集的类别个数
    	:anchors: 一般是None
    	"""
        super().__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='ascii', errors='ignore') as f:
            	# 取到配置文件中的每条信息(没有注释内容)
                self.yaml = yaml.safe_load(f)  # model dict

        # Define model   
        ch = self.yaml['ch'] = self.yaml.get('ch', ch)  # input channels ch=3
        # 设置类别数,一般不执行,因为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
        # 重写anchors, 一般不执行,因为传进来的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的序号,并排好序 
        self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch])  # model, savelist
        self.names = [str(i) for i in range(self.yaml['nc'])]  # default names
        self.inplace = self.yaml.get('inplace', True)

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

        # Init weights, biases
        initialize_weights(self)
        self.info()
        LOGGER.info('')

    def forward(self, x, augment=False, profile=False, visualize=False):
    	# 上下flip/左右flip
    	# 是否在测试时也要使用数据增强
        if augment:
            return self._forward_augment(x)  # augmented inference, None
        # 默认执行 正常前向推理
        return self._forward_once(x, profile, visualize)  # single-scale inference, train

    def _forward_augment(self, x):
        img_size = x.shape[-2:]  # height, width
        s = [1, 0.83, 0.67]  # scales
        f = [None, 3, None]  # flips (2-ud, 3-lr)
        y = []  # outputs
        for si, fi in zip(s, f):
            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
            yi = self._descale_pred(yi, fi, si, img_size)
            y.append(yi)
        y = self._clip_augmented(y)  # clip augmented tails
        return torch.cat(y, 1), None  # augmented inference, train

    def _descale_pred(self, p, flips, scale, img_size):
        # de-scale predictions following augmented inference (inverse operation)
        if self.inplace:
            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 _clip_augmented(self, y):
        # Clip YOLOv5 augmented inference tails
        nl = self.model[-1].nl  # number of detection layers (P3-P5)
        g = sum(4 ** x for x in range(nl))  # grid points
        e = 1  # exclude layer count
        i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e))  # indices
        y[0] = y[0][:, :-i]  # large
        i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e))  # indices
        y[-1] = y[-1][:, i:]  # small
        return y

    def _initialize_biases(self, cf=None):  # 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:5 + m.nc] += math.log(0.6 / (m.nc - 0.99999)) if cf is None else torch.log(cf / cf.sum())  # cls
            mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)


Model = DetectionModel  # retain YOLOv5 'Model' class for backwards compatibility

六、本周任务

image-20231117211520194

img

img

img

6.1 仿造C3模块在common.py文件中实现C2

image-20231117211720080

6.2 在yolov5s.yaml文件中增加C2

image-20231117211829767

6.3 在yolo.py文件中的parse_model模块增加C2

image-20231117212026065

6.4 运行结果

image-20231117212153074

image-20231117212331099

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值