往期回顾:YOLOv5源码解读1.0-目录_汉卿HanQ的博客-CSDN博客
学习完yolov*.yaml,就可以看具体网络架构了。本篇先介绍yolo.py,这是yolo的特定模块,yolov5的模型建立是依靠yolo.py中的函数和对象完成的。
目录
5.7初始化偏置biases信息_initialize_biases
1.导入python包
# ----------------------------------1.导入python包----------------------------------
import argparse # 解析命令行参数模块
import sys # sys系统模块 包含了与Python解释器和它的环境有关的函数
from copy import deepcopy # 数据拷贝模块 深拷贝
from pathlib import Path # Path将str转换为Path对象 使字符串路径易于操作的模块
2.获取文件路径
# ----------------------------------2.获取文件路径----------------------------------
FILE = Path(__file__).resolve() # __file__指的是当前文件(即val.py),FILE最终保存着当前文件的绝对路径,比如D://yolov5/modles/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添加到运行路径上
# ROOT = ROOT.relative_to(Path.cwd()) # relative ROOT设置为相对路径
3.加载自定义模块
# ----------------------------------3.加载自定义模块----------------------------------
from models.common import * # yolov5的网络结构(yolov5)
from models.experimental import * # 导入在线下载模块
from utils.autoanchor import check_anchor_order # 导入检查anchors合法性的函数
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 (copy_attr, fuse_conv_and_bn, initialize_weights, model_info, scale_img, select_device,
time_sync) # 定义了一些与PyTorch有关的工具函数
# 导入thop包 用于计算FLOPs
try:
import thop # for FLOPs computation
except ImportError:
thop = None
4.Detect类
4.1参数初始化__init
class Detect(nn.Module):
stride = None # 特征图缩放步长
onnx_dynamic = False # ONMX动态量化
# ----------------------------------4.1 参数初始化__init__----------------------------------
def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer
super().__init__()
self.nc = nc # nc: 数据集类别数量
self.no = nc + 5 # nc+5=nc+(x,y,w,h,conf) # no: 表示每个anchor的输出数,前nc个01字符对应类别,后5个对应:是否有目标,目标框的中心,目标框的宽高
self.nl = len(anchors) # nl: 表示预测层数,yolov5是3层预测
self.na = len(anchors[0]) // 2 # na: 表示anchors的数量,除以2是因为[10,13, 16,30, 33,23]这个长度是6,对应3个anchor
self.grid = [torch.zeros(1)] * self.nl # grid: 表示初始化grid列表大小,下面会计算grid,grid就是每个格子的x,y坐标(整数,比如0-19),左上角为(1,1),右下角为(input.w/stride,input.h/stride)
self.anchor_grid = [torch.zeros(1)] * self.nl # anchor_grid: 表示初始化anchor_grid列表大小,空列表
self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, # 注册常量anchor,并将预选框(尺寸)以数对形式存入,并命名为anchors
2)) # shape(nl,na,2) 注意后面就可以通过self.anchors来访问它了
# 每一张进行三次预测,每一个预测结果包含nc+5个值
# (n, 255, 80, 80),(n, 255, 40, 40),(n, 255, 20, 20) --> ch=(255, 255, 255)
# 255 -> (nc+5)*3 ===> 为了提取出预测框的位置信息以及预测框尺寸信息
self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv 3个输出层最后的1乘1卷积
self.inplace = inplace # inplace: 一般都是True,默认不使用AWS,Inferentia加速
# 如果模型不训练那么将会对这些预测得到的参数进一步处理,然后输出,可以方便后期的直接调用
# 包含了三个信息pred_box [x,y,w,h] pred_conf[confidence] pre_cls[cls0,cls1,cls2,...clsn]
4.2前向传播forward
# ----------------------------------4.2 前向传播forward----------------------------------
"""
这段代码主要是对三个feature map分别进行处理:(n,255,80,80),(n,255,40,40),(n,255,20,20)
首先进行for循环,每次的循环,产生一个z。维度重排列:(n,255,_,_)->(n,3,nc+5,ny,nx)->(n,3,ny,nx,nc+5)
三层分别预测了80*80、40*40、20*20次。接着构造网格,因为推理返回的不是归一化后的网格偏移量,需要再加上网格的位置,得到最终的推理坐标,再送入nms。
所以这里构建网格就是为了纪律每个grid的网格坐标方面后面使用最后按损失函数的回归方式来转换坐标,利用sigmoid激活函数计算定位参数,cat(dim=-1)为直接拼接。
注意:训练阶段直接返回x,而预测阶段返回3个特征图拼接的结果
"""
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() # 维度重排列:bs 先验框数组 检测框行数 属性数 分类数
# 前向传播将相对坐标转移到grid绝对坐标中
if not self.training: # inference 生成坐标系
if self.onnx_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) # 加载网格坐标 先验框尺寸
# 按损失函数回归方式转换坐标
y = x[i].sigmoid()
if self.inplace: # 改变原数据 计算定位参数
y[..., 0:2] = (y[..., 0:2] * 2 - 0.5 + self.grid[i]) * self.stride[i] # xy gird位置基准 cell的预测初始位置 y[...,0:2]是grid坐标基础上的位置偏移
y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh anchor_grid 预测框基准 预测框初始位置 y[..., 2:4]作为预测框位置的调整
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 stride是一个grid cell的实际尺寸 sigmoid为0-1 这里变化到-0.5 1.5
wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh 范围扩大0-4倍(4倍是下层感受野是上层2倍) 下层注重大目标 计算量小
y = torch.cat((xy, wh, y[..., 4:]), -1)
z.append(y.view(bs, -1, self.no)) # 存储每个特征图检测框的信息
return x if self.training else (torch.cat(z, 1), x) # 返回x(三个特征图拼接结果)
4.3转换坐标_make_grid
# ----------------------------------4.3 转换坐标_make_grid----------------------------------
"""
将相对坐标系转换到grid绝对坐标系
grid*3是因为每个scale生成3个预测框
anchor_grid是anchor宽高
"""
def _make_grid(self, nx=20, ny=20, i=0):
d = self.anchors[i].device
if check_version(torch.__version__, '1.10.0'): # torch>=1.10.0 meshgrid workaround for torch>=0.7 compatibility
yv, xv = torch.meshgrid([torch.arange(ny).to(d), torch.arange(nx).to(d)], indexing='ij') # indexing='ij' i是同一行 j是同一列
else:
yv, xv = torch.meshgrid([torch.arange(ny).to(d), torch.arange(nx).to(d)])
grid = torch.stack((xv, yv), 2).expand((1, self.na, ny, nx, 2)).float() # 复制三倍
anchor_grid = (self.anchors[i].clone() * self.stride[i]) \
.view((1, self.na, 1, 1, 2)).expand((1, self.na, ny, nx, 2)).float() # stride是下采样率 三层分别是8 16 36
return grid, anchor_grid
5. Model类
# ----------------------------------5. Model类----------------------------------
class Model(nn.Module):
def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
super().__init__()# 父类的构造方法
# 检查传入的参数格式,如果cfg是加载好的字典结果
if isinstance(cfg, dict):
self.yaml = cfg # 直接保存到模型中
# 若不是字典 则为yaml文件路径
else: # is *.yaml 一般执行这里
import yaml # 导入yaml文件
self.yaml_file = Path(cfg).name # 保存文件名:cfg file name = yolov5s.yaml
with open(cfg, encoding='ascii', errors='ignore') as f: # 如果配置文件中有中文,打开时要加encoding参数
self.yaml = yaml.safe_load(f) # 将yaml文件加载为字典 model dict 取到配置文件中每条的信息(没有注释内容)
# Define model 搭建模型
ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels 判断yaml的ch是否存在
if nc and nc != self.yaml['nc']: # 判断类的ch与yaml是否一致
LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}") # 终端提示
self.yaml['nc'] = nc # 将yaml改为model的nc
if anchors: # 重写anchor 一般不用 因为默认None
LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}') # 终端提示
self.yaml['anchors'] = round(anchors) # yaml值改为model的
self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # 解析模型
self.names = [str(i) for i in range(self.yaml['nc'])] # 加载每一类的类别名
self.inplace = self.yaml.get('inplace', True) # inplace类似x+=1 True不使用加速推理
# Build strides, anchors 构造步长和anchor
m = self.model[-1] # Detect()
if isinstance(m, Detect): # 判断最后一层是否是detect层
s = 256 # 定义一个256*256输入
m.inplace = self.inplace
m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # 保存特征层的stride 并将anchor处理成对应特征层的格式
m.anchors /= m.stride.view(-1, 1, 1) # 原始定义的anchor是原始图片像素值 将其缩放至特征图大小
check_anchor_order(m) # 价差anchor顺序与stride是否一致
self.stride = m.stride # 保存步长
self._initialize_biases() # 初始化bias
# Init weights, biases
initialize_weights(self) # 初始化权重
self.info() # 打印模型信息
LOGGER.info('')
5.1前向传播forward
# ----------------------------------5.1 前向传播forward----------------------------------
"""
管理前向传播
x 原图
augment 是否使用增强式推到
profile 是否测试每个网络层性能
visualize 是否输出每个网络层的特征图
"""
def forward(self, x, augment=False, profile=False, visualize=False):
if augment:
return self._forward_augment(x) # 增强训练
return self._forward_once(x, profile, visualize) # 默认整除前向推理
5.2推理的前向传播_forward_augment
# ----------------------------------5.2 推理的前向传播_forward_augment----------------------------------
"""
将图片进行裁剪 送入到模型中进行检擦
做数据增强TTA x为图像tensor
只在test detect中出现 用于提高推导精度
"""
def _forward_augment(self, x):
img_size = x.shape[-2:] # height, width 获取图像宽和高
s = [1, 0.83, 0.67] # scales 对图像进行三次变化 原图 尺寸缩小0.83并水平翻转 尺寸缩小0.67
f = [None, 3, None] # flips (2-ud, 3-lr) 翻转
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 前向传播_forward_once
# 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
5.3训练的前向传播_forward_once
# ----------------------------------5.3 训练的前向传播_forward_once----------------------------------
"""
对模型每一层进行迭代 训练的前向全波
x 输入图像
profile 测试每个网络层性能
visualize 是否输出每个网络层的特征图(获取batch第一张图象,然后把每个通道上的二维矩阵看出一张灰度图绘制)
"""
def _forward_once(self, x, profile=False, visualize=False):
y, dt = [], [] # 各网络层输出 y存放着self.save=True的每一层输出 后面concat要用到 dt在profile中性能评估使用
for m in self.model: # 遍历model各个模块
if m.f != -1: # if not from previous layer m.f是该层的输入来源 不是-1就不是从上一层来的
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 from指向网络层输出的列表
if profile: # 测试该网络层的性能
self._profile_one_layer(m, x, dt)
x = m(x) # run 使用该网络层进行推导 得到该网络层的输出
y.append(x if m.i in self.save else None) # save output 存放self.save的每一层输出 后面需要作concat操作,将每一层输出结果保存到y
if visualize:
feature_visualization(x, m.type, m.i, save_dir=visualize) # 绘制该图片第一张图的特征图
return x
5.4恢复图片_descale_pred
# ----------------------------------5.4 恢复图片_descale_pred----------------------------------
"""
将推理结果恢复到原图尺寸(逆操作)
p 推理结果
flips 反转标记
scale 图片缩放比例
img_size 原图图片尺寸
"""
def _descale_pred(self, p, flips, scale, img_size):
# de-scale predictions following augmented inference (inverse operation)
if self.inplace:
# 把xywh恢复
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
5.5图片切割_clip_augmented
# ----------------------------------5.5 图片切割_clip_augmented----------------------------------
"""
TTA时对图片进行裁剪切割 数据增强方式
"""
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
5.6打印日志操作_profile_one_layer
# ----------------------------------5.6 打印日志操作_profile_one_layer----------------------------------
"""
曾是每个网络层的性能
m 网络层
x 该网络层的from列表中的网络层输出
dt 各网络层推导耗时(列表)
"""
def _profile_one_layer(self, m, x, dt):
"""
time 前向推导时间
GFLOPs 浮点运算量
params 网络层参数量
module 网络层名称
"""
c = isinstance(m, Detect) # is final layer, copy input as inplace fix
o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs
t = time_sync()
for _ in range(10):
m(x.copy() if c else x)
dt.append((time_sync() - 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}')
if c:
LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
5.7初始化偏置biases信息_initialize_biases
# ----------------------------------5.7 初始化偏置biases信息_initialize_biases----------------------------------
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:] += math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # cls
mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
5.8打印偏置信息_print_biases
# ----------------------------------5.8 打印偏置信息_print_biases----------------------------------
def _print_biases(self):
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()))
5.9将Conv2d+BN进行融合fuse
# ----------------------------------5.9 将Conv2d+BN进行融合fuse----------------------------------
def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
LOGGER.info('Fusing layers... ')
for m in self.model.modules():
# 如果当前是卷积层Conv且有BN结构 就调用fuse_conv_and_bn进行融合加速推理
if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):
m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv 更新卷积层
delattr(m, 'bn') # remove batchnorm 移除BN
m.forward = m.forward_fuse # update forward 更新前向传播
self.info() # 打印融合信息
return self
5.10扩展模型功能autoshape
# ----------------------------------5.10 扩展模型功能autoshape----------------------------------
def autoshape(self): # add AutoShape module
LOGGER.info('Adding AutoShape... ')
# 预处理+推理+NMS
m = AutoShape(self) # wrap model
copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes
return m
5.11打印模型结构信息info
# ----------------------------------5.11 打印模型结构信息info----------------------------------
def info(self, verbose=False, img_size=640): # print model information
model_info(self, verbose, img_size)
5.12模块转移到CPU/GPU_apply
# ----------------------------------5.12 模块转移到CPU/GPU_apply----------------------------------
def _apply(self, fn):
# Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
self = super()._apply(fn)
m = self.model[-1] # Detect()
if isinstance(m, Detect):
m.stride = fn(m.stride)
m.grid = list(map(fn, m.grid))
if isinstance(m.anchor_grid, list):
m.anchor_grid = list(map(fn, m.anchor_grid))
return self
6.解析yaml模块parse_model
def parse_model(d, ch): # model_dict, input_channels(3)
"""
解析yaml模块 并且到common中找到相对于的模块,然后组成一个完整的模型解析文件,并搭建网络结构。如果后续对模型框架改动,需要对这个函数做改动
d yaml配置文件
ch 记录每一层 channel
"""
6.1参数初始化
# ----------------------------------6.1 参数初始化----------------------------------
LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}") # 输出
anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'] # 获取 anchors nc depth_multiple width_multiple
na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors 判断anchor数量
no = na * (nc + 5) # number of outputs = anchors * (classes + 5) 根据anchor数量输出维度
6.2搭建网络前准备
# ----------------------------------6.2 搭建网络前准备----------------------------------
layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out 网络单元列表(保存每一层的层结构) 网络输出引用列表(记录from不是-1)当前的输出通道数(保存当前channel)
# 读取backbone head中的网络单元
"""
f from 当前输入来自哪里
n number 当前层次数
m module 当前层类别
args 当前层参数
eval 将字符串当成有效的表达式来求值 实现list dict tuple str转换
"""
for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
m = eval(m) if isinstance(m, str) else m # eval strings 使用eval读取model参数对应的类名
for j, a in enumerate(args):
try:
args[j] = eval(a) if isinstance(a, str) else a # eval strings 使用eval将字符串转换为变量
except NameError:
pass
n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain 控制深度 n为当前模块的次数
if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,
BottleneckCSP, C3, C3TR, C3SPP, C3Ghost]:
c1, c2 = ch[f], args[0] # c1当前层输入channel c2当前层输出channel ch记录所有层的输出channel
if c2 != no: # if not output no=17 只有最后一层c2=no 最后一层不用控制宽度 输出channel必须是no
c2 = make_divisible(c2 * gw, 8) # width gain 控制宽度
args = [c1, c2, *args[1:]] # 在初始args上更新 加入当前层输出channel并更新当前层
# 如果当前层是BottleneckCPS/C3/C3Ghost/C3
if m in [BottleneckCSP, C3, C3TR, C3Ghost]:
args.insert(2, n) # number of repeats 在args第二个位置插入Bottlenect个数n
n = 1 # 恢复默认1
elif m is nn.BatchNorm2d: # 是否进行归一化模块
args = [ch[f]] # BN值需要返回上一层channel
elif m is Concat: # 是否tensor连接模块
c2 = sum(ch[x] for x in f) # concat层将f所有输出累加到这层的输出channel
elif m is Detect: # 是否是detect模块
args.append([ch[x] for x in f]) # args中加入三个detect层的输出channel
if isinstance(args[1], int): # number of anchors
args[1] = [list(range(args[1] * 2))] * len(f)
elif m is Contract:
c2 = ch[f] * args[0] ** 2
elif m is Expand:
c2 = ch[f] // args[0] ** 2
else:
c2 = ch[f]
6.3打印保存layers信息
# ----------------------------------6.3 打印保存layers信息----------------------------------
m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module m_得到当前层module 将n个模块组合存放到m_中
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) # 所有层结构中from!=-1记录
layers.append(m_) # 当前层结构module加入到layers中
if i == 0:
ch = [] # 取出输入channel[3]
ch.append(c2) # 把当前层输出channel数加入ch
return nn.Sequential(*layers), sorted(save)
7.main函数
# ----------------------------------7 main函数----------------------------------
if __name__ == '__main__':
parser = argparse.ArgumentParser() # 创建解析器
parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml') # cfg配置文件
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') # device 选择设备
parser.add_argument('--profile', action='store_true', help='profile model speed') # profile 用户配置文件
parser.add_argument('--test', action='store_true', help='test all yolo*.yaml') # tsest 测试
opt = parser.parse_args() # 增加后的属性给args
opt.cfg = check_yaml(opt.cfg) # check YAML 检查yaml
print_args(FILE.stem, opt) # 检测yolov5的仓库是否给出更新
device = select_device(opt.device) # 选择设备
# Create model 构造模型
model = Model(opt.cfg).to(device)
model.train()
# Profile 用户自定义配置
if opt.profile:
img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device)
y = model(img, profile=True)
# Test all models 测试所有模型
if opt.test:
for cfg in Path(ROOT / 'models').rglob('yolo*.yaml'):
try:
_ = Model(cfg)
except Exception as e:
print(f'Error in {cfg}: {e}')
# Tensorboard (not working https://github.com/ultralytics/yolov5/issues/2898)
# from torch.utils.tensorboard import SummaryWriter
# tb_writer = SummaryWriter('.')
# LOGGER.info("Run 'tensorboard --logdir=models' to view tensorboard at http://localhost:6006/")
# tb_writer.add_graph(torch.jit.trace(model, img, strict=False), []) # add model graph
8.整体代码
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
YOLO-specific modules
Usage:
$ python path/to/models/yolo.py --cfg yolov5s.yaml
"""
# ----------------------------------1.导入python包----------------------------------
import argparse # 解析命令行参数模块
import sys # sys系统模块 包含了与Python解释器和它的环境有关的函数
from copy import deepcopy # 数据拷贝模块 深拷贝
from pathlib import Path # Path将str转换为Path对象 使字符串路径易于操作的模块
# ----------------------------------2.获取文件路径----------------------------------
FILE = Path(__file__).resolve() # __file__指的是当前文件(即val.py),FILE最终保存着当前文件的绝对路径,比如D://yolov5/modles/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添加到运行路径上
# ROOT = ROOT.relative_to(Path.cwd()) # relative ROOT设置为相对路径
# ----------------------------------3.加载自定义模块----------------------------------
from models.common import * # yolov5的网络结构(yolov5)
from models.experimental import * # 导入在线下载模块
from utils.autoanchor import check_anchor_order # 导入检查anchors合法性的函数
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 (copy_attr, fuse_conv_and_bn, initialize_weights, model_info, scale_img, select_device,
time_sync) # 定义了一些与PyTorch有关的工具函数
# 导入thop包 用于计算FLOPs
try:
import thop # for FLOPs computation
except ImportError:
thop = None
# ----------------------------------4.Detect类----------------------------------
class Detect(nn.Module):
stride = None # 特征图缩放步长
onnx_dynamic = False # ONMX动态量化
# ----------------------------------4.1 参数初始化__init__----------------------------------
def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer
super().__init__()
self.nc = nc # nc: 数据集类别数量
self.no = nc + 5 # nc+5=nc+(x,y,w,h,conf) # no: 表示每个anchor的输出数,前nc个01字符对应类别,后5个对应:是否有目标,目标框的中心,目标框的宽高
self.nl = len(anchors) # nl: 表示预测层数,yolov5是3层预测
self.na = len(anchors[0]) // 2 # na: 表示anchors的数量,除以2是因为[10,13, 16,30, 33,23]这个长度是6,对应3个anchor
self.grid = [torch.zeros(1)] * self.nl # grid: 表示初始化grid列表大小,下面会计算grid,grid就是每个格子的x,y坐标(整数,比如0-19),左上角为(1,1),右下角为(input.w/stride,input.h/stride)
self.anchor_grid = [torch.zeros(1)] * self.nl # anchor_grid: 表示初始化anchor_grid列表大小,空列表
self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, # 注册常量anchor,并将预选框(尺寸)以数对形式存入,并命名为anchors
2)) # shape(nl,na,2) 注意后面就可以通过self.anchors来访问它了
# 每一张进行三次预测,每一个预测结果包含nc+5个值
# (n, 255, 80, 80),(n, 255, 40, 40),(n, 255, 20, 20) --> ch=(255, 255, 255)
# 255 -> (nc+5)*3 ===> 为了提取出预测框的位置信息以及预测框尺寸信息
self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv 3个输出层最后的1乘1卷积
self.inplace = inplace # inplace: 一般都是True,默认不使用AWS,Inferentia加速
# 如果模型不训练那么将会对这些预测得到的参数进一步处理,然后输出,可以方便后期的直接调用
# 包含了三个信息pred_box [x,y,w,h] pred_conf[confidence] pre_cls[cls0,cls1,cls2,...clsn]
# ----------------------------------4.2 前向传播forward----------------------------------
"""
这段代码主要是对三个feature map分别进行处理:(n,255,80,80),(n,255,40,40),(n,255,20,20)
首先进行for循环,每次的循环,产生一个z。维度重排列:(n,255,_,_)->(n,3,nc+5,ny,nx)->(n,3,ny,nx,nc+5)
三层分别预测了80*80、40*40、20*20次。接着构造网格,因为推理返回的不是归一化后的网格偏移量,需要再加上网格的位置,得到最终的推理坐标,再送入nms。
所以这里构建网格就是为了纪律每个grid的网格坐标方面后面使用最后按损失函数的回归方式来转换坐标,利用sigmoid激活函数计算定位参数,cat(dim=-1)为直接拼接。
注意:训练阶段直接返回x,而预测阶段返回3个特征图拼接的结果
"""
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() # 维度重排列:bs 先验框数组 检测框行数 属性数 分类数
# 前向传播将相对坐标转移到grid绝对坐标中
if not self.training: # inference 生成坐标系
if self.onnx_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) # 加载网格坐标 先验框尺寸
# 按损失函数回归方式转换坐标
y = x[i].sigmoid()
if self.inplace: # 改变原数据 计算定位参数
y[..., 0:2] = (y[..., 0:2] * 2 - 0.5 + self.grid[i]) * self.stride[i] # xy gird位置基准 cell的预测初始位置 y[...,0:2]是grid坐标基础上的位置偏移
y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh anchor_grid 预测框基准 预测框初始位置 y[..., 2:4]作为预测框位置的调整
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 stride是一个grid cell的实际尺寸 sigmoid为0-1 这里变化到-0.5 1.5
wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh 范围扩大0-4倍(4倍是下层感受野是上层2倍) 下层注重大目标 计算量小
y = torch.cat((xy, wh, y[..., 4:]), -1)
z.append(y.view(bs, -1, self.no)) # 存储每个特征图检测框的信息
return x if self.training else (torch.cat(z, 1), x) # 返回x(三个特征图拼接结果)
# ----------------------------------4.3 转换坐标_make_grid----------------------------------
"""
将相对坐标系转换到grid绝对坐标系
grid*3是因为每个scale生成3个预测框
anchor_grid是anchor宽高
"""
def _make_grid(self, nx=20, ny=20, i=0):
d = self.anchors[i].device
if check_version(torch.__version__, '1.10.0'): # torch>=1.10.0 meshgrid workaround for torch>=0.7 compatibility
yv, xv = torch.meshgrid([torch.arange(ny).to(d), torch.arange(nx).to(d)], indexing='ij') # indexing='ij' i是同一行 j是同一列
else:
yv, xv = torch.meshgrid([torch.arange(ny).to(d), torch.arange(nx).to(d)])
grid = torch.stack((xv, yv), 2).expand((1, self.na, ny, nx, 2)).float() # 复制三倍
anchor_grid = (self.anchors[i].clone() * self.stride[i]) \
.view((1, self.na, 1, 1, 2)).expand((1, self.na, ny, nx, 2)).float() # stride是下采样率 三层分别是8 16 36
return grid, anchor_grid
# ----------------------------------5. Model类----------------------------------
class Model(nn.Module):
def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
super().__init__()# 父类的构造方法
# 检查传入的参数格式,如果cfg是加载好的字典结果
if isinstance(cfg, dict):
self.yaml = cfg # 直接保存到模型中
# 若不是字典 则为yaml文件路径
else: # is *.yaml 一般执行这里
import yaml # 导入yaml文件
self.yaml_file = Path(cfg).name # 保存文件名:cfg file name = yolov5s.yaml
with open(cfg, encoding='ascii', errors='ignore') as f: # 如果配置文件中有中文,打开时要加encoding参数
self.yaml = yaml.safe_load(f) # 将yaml文件加载为字典 model dict 取到配置文件中每条的信息(没有注释内容)
# Define model 搭建模型
ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels 判断yaml的ch是否存在
if nc and nc != self.yaml['nc']: # 判断类的ch与yaml是否一致
LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}") # 终端提示
self.yaml['nc'] = nc # 将yaml改为model的nc
if anchors: # 重写anchor 一般不用 因为默认None
LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}') # 终端提示
self.yaml['anchors'] = round(anchors) # yaml值改为model的
self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # 解析模型
self.names = [str(i) for i in range(self.yaml['nc'])] # 加载每一类的类别名
self.inplace = self.yaml.get('inplace', True) # inplace类似x+=1 True不使用加速推理
# Build strides, anchors 构造步长和anchor
m = self.model[-1] # Detect()
if isinstance(m, Detect): # 判断最后一层是否是detect层
s = 256 # 定义一个256*256输入
m.inplace = self.inplace
m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # 保存特征层的stride 并将anchor处理成对应特征层的格式
m.anchors /= m.stride.view(-1, 1, 1) # 原始定义的anchor是原始图片像素值 将其缩放至特征图大小
check_anchor_order(m) # 价差anchor顺序与stride是否一致
self.stride = m.stride # 保存步长
self._initialize_biases() # 初始化bias
# Init weights, biases
initialize_weights(self) # 初始化权重
self.info() # 打印模型信息
LOGGER.info('')
# ----------------------------------5.1 前向传播forward----------------------------------
"""
管理前向传播
x 原图
augment 是否使用增强式推到
profile 是否测试每个网络层性能
visualize 是否输出每个网络层的特征图
"""
def forward(self, x, augment=False, profile=False, visualize=False):
if augment:
return self._forward_augment(x) # 增强训练
return self._forward_once(x, profile, visualize) # 默认整除前向推理
# ----------------------------------5.2 推理的前向传播_forward_augment----------------------------------
"""
将图片进行裁剪 送入到模型中进行检擦
做数据增强TTA x为图像tensor
只在test detect中出现 用于提高推导精度
"""
def _forward_augment(self, x):
img_size = x.shape[-2:] # height, width 获取图像宽和高
s = [1, 0.83, 0.67] # scales 对图像进行三次变化 原图 尺寸缩小0.83并水平翻转 尺寸缩小0.67
f = [None, 3, None] # flips (2-ud, 3-lr) 翻转
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 前向传播_forward_once
# 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
# ----------------------------------5.3 训练的前向传播_forward_once----------------------------------
"""
对模型每一层进行迭代 训练的前向全波
x 输入图像
profile 测试每个网络层性能
visualize 是否输出每个网络层的特征图(获取batch第一张图象,然后把每个通道上的二维矩阵看出一张灰度图绘制)
"""
def _forward_once(self, x, profile=False, visualize=False):
y, dt = [], [] # 各网络层输出 y存放着self.save=True的每一层输出 后面concat要用到 dt在profile中性能评估使用
for m in self.model: # 遍历model各个模块
if m.f != -1: # if not from previous layer m.f是该层的输入来源 不是-1就不是从上一层来的
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 from指向网络层输出的列表
if profile: # 测试该网络层的性能
self._profile_one_layer(m, x, dt)
x = m(x) # run 使用该网络层进行推导 得到该网络层的输出
y.append(x if m.i in self.save else None) # save output 存放self.save的每一层输出 后面需要作concat操作,将每一层输出结果保存到y
if visualize:
feature_visualization(x, m.type, m.i, save_dir=visualize) # 绘制该图片第一张图的特征图
return x
# ----------------------------------5.4 恢复图片_descale_pred----------------------------------
"""
将推理结果恢复到原图尺寸(逆操作)
p 推理结果
flips 反转标记
scale 图片缩放比例
img_size 原图图片尺寸
"""
def _descale_pred(self, p, flips, scale, img_size):
# de-scale predictions following augmented inference (inverse operation)
if self.inplace:
# 把xywh恢复
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
# ----------------------------------5.5 图片切割_clip_augmented----------------------------------
"""
TTA时对图片进行裁剪切割 数据增强方式
"""
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
# ----------------------------------5.6 打印日志操作_profile_one_layer----------------------------------
"""
曾是每个网络层的性能
m 网络层
x 该网络层的from列表中的网络层输出
dt 各网络层推导耗时(列表)
"""
def _profile_one_layer(self, m, x, dt):
"""
time 前向推导时间
GFLOPs 浮点运算量
params 网络层参数量
module 网络层名称
"""
c = isinstance(m, Detect) # is final layer, copy input as inplace fix
o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs
t = time_sync()
for _ in range(10):
m(x.copy() if c else x)
dt.append((time_sync() - 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}')
if c:
LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
# ----------------------------------5.7 初始化偏置biases信息_initialize_biases----------------------------------
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:] += math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum()) # cls
mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
# ----------------------------------5.8 打印偏置信息_print_biases----------------------------------
def _print_biases(self):
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):
# for m in self.model.modules():
# if type(m) is Bottleneck:
# LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
# ----------------------------------5.9 将Conv2d+BN进行融合fuse----------------------------------
def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
LOGGER.info('Fusing layers... ')
for m in self.model.modules():
# 如果当前是卷积层Conv且有BN结构 就调用fuse_conv_and_bn进行融合加速推理
if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):
m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv 更新卷积层
delattr(m, 'bn') # remove batchnorm 移除BN
m.forward = m.forward_fuse # update forward 更新前向传播
self.info() # 打印融合信息
return self
# ----------------------------------5.10 扩展模型功能autoshape----------------------------------
def autoshape(self): # add AutoShape module
LOGGER.info('Adding AutoShape... ')
# 预处理+推理+NMS
m = AutoShape(self) # wrap model
copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes
return m
# ----------------------------------5.11 打印模型结构信息info----------------------------------
def info(self, verbose=False, img_size=640): # print model information
model_info(self, verbose, img_size)
# ----------------------------------5.12 模块转移到CPU/GPU_apply----------------------------------
def _apply(self, fn):
# Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
self = super()._apply(fn)
m = self.model[-1] # Detect()
if isinstance(m, Detect):
m.stride = fn(m.stride)
m.grid = list(map(fn, m.grid))
if isinstance(m.anchor_grid, list):
m.anchor_grid = list(map(fn, m.anchor_grid))
return self
# ----------------------------------6 解析yaml模块parse_model----------------------------------
def parse_model(d, ch): # model_dict, input_channels(3)
"""
解析yaml模块 并且到common中找到相对于的模块,然后组成一个完整的模型解析文件,并搭建网络结构。如果后续对模型框架改动,需要对这个函数做改动
d yaml配置文件
ch 记录每一层 channel
"""
# ----------------------------------6.1 参数初始化----------------------------------
LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}") # 输出
anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'] # 获取 anchors nc depth_multiple width_multiple
na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors 判断anchor数量
no = na * (nc + 5) # number of outputs = anchors * (classes + 5) 根据anchor数量输出维度
# ----------------------------------6.2 搭建网络前准备----------------------------------
layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out 网络单元列表(保存每一层的层结构) 网络输出引用列表(记录from不是-1)当前的输出通道数(保存当前channel)
# 读取backbone head中的网络单元
"""
f from 当前输入来自哪里
n number 当前层次数
m module 当前层类别
args 当前层参数
eval 将字符串当成有效的表达式来求值 实现list dict tuple str转换
"""
for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
m = eval(m) if isinstance(m, str) else m # eval strings 使用eval读取model参数对应的类名
for j, a in enumerate(args):
try:
args[j] = eval(a) if isinstance(a, str) else a # eval strings 使用eval将字符串转换为变量
except NameError:
pass
n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain 控制深度 n为当前模块的次数
if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,
BottleneckCSP, C3, C3TR, C3SPP, C3Ghost]:
c1, c2 = ch[f], args[0] # c1当前层输入channel c2当前层输出channel ch记录所有层的输出channel
if c2 != no: # if not output no=17 只有最后一层c2=no 最后一层不用控制宽度 输出channel必须是no
c2 = make_divisible(c2 * gw, 8) # width gain 控制宽度
args = [c1, c2, *args[1:]] # 在初始args上更新 加入当前层输出channel并更新当前层
# 如果当前层是BottleneckCPS/C3/C3Ghost/C3
if m in [BottleneckCSP, C3, C3TR, C3Ghost]:
args.insert(2, n) # number of repeats 在args第二个位置插入Bottlenect个数n
n = 1 # 恢复默认1
elif m is nn.BatchNorm2d: # 是否进行归一化模块
args = [ch[f]] # BN值需要返回上一层channel
elif m is Concat: # 是否tensor连接模块
c2 = sum(ch[x] for x in f) # concat层将f所有输出累加到这层的输出channel
elif m is Detect: # 是否是detect模块
args.append([ch[x] for x in f]) # args中加入三个detect层的输出channel
if isinstance(args[1], int): # number of anchors
args[1] = [list(range(args[1] * 2))] * len(f)
elif m is Contract:
c2 = ch[f] * args[0] ** 2
elif m is Expand:
c2 = ch[f] // args[0] ** 2
else:
c2 = ch[f]
# ----------------------------------6.3 打印保存layers信息----------------------------------
m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module m_得到当前层module 将n个模块组合存放到m_中
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) # 所有层结构中from!=-1记录
layers.append(m_) # 当前层结构module加入到layers中
if i == 0:
ch = [] # 取出输入channel[3]
ch.append(c2) # 把当前层输出channel数加入ch
return nn.Sequential(*layers), sorted(save)
# ----------------------------------7 main函数----------------------------------
if __name__ == '__main__':
parser = argparse.ArgumentParser() # 创建解析器
parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml') # cfg配置文件
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') # device 选择设备
parser.add_argument('--profile', action='store_true', help='profile model speed') # profile 用户配置文件
parser.add_argument('--test', action='store_true', help='test all yolo*.yaml') # tsest 测试
opt = parser.parse_args() # 增加后的属性给args
opt.cfg = check_yaml(opt.cfg) # check YAML 检查yaml
print_args(FILE.stem, opt) # 检测yolov5的仓库是否给出更新
device = select_device(opt.device) # 选择设备
# Create model 构造模型
model = Model(opt.cfg).to(device)
model.train()
# Profile 用户自定义配置
if opt.profile:
img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device)
y = model(img, profile=True)
# Test all models 测试所有模型
if opt.test:
for cfg in Path(ROOT / 'models').rglob('yolo*.yaml'):
try:
_ = Model(cfg)
except Exception as e:
print(f'Error in {cfg}: {e}')
# Tensorboard (not working https://github.com/ultralytics/yolov5/issues/2898)
# from torch.utils.tensorboard import SummaryWriter
# tb_writer = SummaryWriter('.')
# LOGGER.info("Run 'tensorboard --logdir=models' to view tensorboard at http://localhost:6006/")
# tb_writer.add_graph(torch.jit.trace(model, img, strict=False), []) # add model graph