YoloV5源码部分注释解读(ultralytics版本)(yolo.py)

这篇文章详细解析了YOLOv5模型的Python实现,包括导入包、配置路径、模型构建、目标检测类等功能。代码中展示了如何使用yolo.py文件创建和测试YOLOv5模型,特别关注了DetectionModel和Segment类,以及如何解析配置文件yolov5s.yaml来构建网络结构。
摘要由CSDN通过智能技术生成

yolo.py的主要作用是构建yolov5的模型;

而且这个yolo.py文件可以单独执行;

这里主要对目标检测中的相关类进行了注释解读,分割等没有用到的暂时没有注释。

第一部分:导入包,配置路径等
第二部分:程序入口,执行程序;在这部分中,创建了一张640×640×3的图片测试,送入Model类中进行了测试。
第三部分:Model类的执行;这里Model又根据DetectionModel创建而来,因此分析DetectionModel即可
第四部分:在DetectionModel中,执行了parse_model类。
这里parse_model进行了yolov5s.yaml(不同yaml文件的解析)

# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
"""
YOLO-specific modules

Usage:
    $ python models/yolo.py --cfg yolov5s.yaml
"""

########################################################################################################################
# 第一部分:导包和配置根目录路径
import argparse    #  argparse:用于解析命令行参数和选项;
import contextlib  # contextlib:上下文管理工具,包含一些用于简化try...except代码块的工具;
import os          # os:提供了许多与操作系统交互的功能;
import platform    # platform:提供了获取运行平台相关信息的函数;
import sys         # sys:提供了一些与Python解释器交互的函数和变量;
from copy import deepcopy  # deepcopy:深复制对象的工具;
from pathlib import Path   # pathlib.Path:处理文件路径和目录的类。

# 这段代码是Python代码,它的作用是设置一些环境变量。
# 首先,它将变量FILE设置为当前脚本的绝对路径,即Path(file).resolve()。然后,变量ROOT被设置为FILE的父目录的上一级目录,即YOLOv5根目录。
# 接下来,代码判断ROOT是否已经在sys.path中,如果没有,就通过sys.path.append()函数将ROOT添加到PYTHONPATH环境变量中,以便程序在运行时能够找到YOLOv5根目录下的Python模块。
# 最后,代码还检查当前运行环境是否为Windows系统。如果不是,就把ROOT设置为当前工作目录与ROOT的相对路径,以便在非Windows系统上运行时能够正确地寻找和加载YOLOv5根目录下的Python模块。
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的Python模块。如果导入成功,则把该模块赋值给变量thop;
# 如果导入失败(即引发了ImportError异常),则把变量thop设置为Non
try:
    import thop  # for FLOPs computation
except ImportError:
    thop = None
########################################################################################################################

# 这几部分暂时没有注释,根据名字可以简单看出,推理,分割,基础模型
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
        super().__init__()
        self.nc = nc  # number of classes
        self.no = nc + 5  # number of outputs per anchor
        self.nl = len(anchors)  # number of detection layers
        self.na = len(anchors[0]) // 2  # number of anchors
        self.grid = [torch.empty(0) for _ in range(self.nl)]  # init grid
        self.anchor_grid = [torch.empty(0) for _ in range(self.nl)]  # init anchor grid
        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
                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
class Segment(Detect):
    # YOLOv5 Segment head for segmentation models
    def __init__(self, nc=80, anchors=(), nm=32, npr=256, ch=(), inplace=True):
        super().__init__(nc, anchors, ch, inplace)
        self.nm = nm  # number of masks
        self.npr = npr  # number of protos
        self.no = 5 + nc + self.nm  # number of outputs per anchor
        self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch)  # output conv
        self.proto = Proto(ch[0], self.npr, self.nm)  # protos
        self.detect = Detect.forward

    def forward(self, x):
        p = self.proto(x[0])
        x = self.detect(self, x)
        return (x, p) if self.training else (x[0], p) if self.export else (x[0], p, x[1])
class BaseModel(nn.Module):
    # YOLOv5 base model
    def forward(self, x, profile=False, visualize=False):
        return self._forward_once(x, profile, visualize)  # single-scale inference, train

    def _forward_once(self, x, profile=False, visualize=False):
        y, dt = [], []  # outputs
        for m in self.model:
            if m.f != -1:  # if not from previous layer
                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
            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
            if visualize:
                feature_visualization(x, m.type, m.i, save_dir=visualize)
        return x

    def _profile_one_layer(self, m, x, dt):
        c = m == self.model[-1]  # 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")

    def fuse(self):  # fuse model Conv2d() + BatchNorm2d() layers
        LOGGER.info('Fusing layers... ')
        for m in self.model.modules():
            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
                m.forward = m.forward_fuse  # update forward
        self.info()
        return self

    def info(self, verbose=False, img_size=640):  # print model information
        model_info(self, verbose, img_size)

    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, Segment)):
            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
########################################################################################################################

########################################################################################################################
# 第三部分
class DetectionModel(BaseModel):
    # YOLOv5 detection model
    # 第一部分:主要是加载配置文件yolov5s.yaml

    # 参数 cfg 是模型的配置文件路径,默认值为 yolov5s.yaml。如果传入的是一个字典对象,则直接使用该字典作为模型配置;如果传入的是一个 YAML 文件路径,则使用 yaml.safe_load() 函数解析该文件,并将解析结果存储在 self.yaml 属性中,该属性是一个字典对象。
    # 参数 ch 表示输入图像的通道数,默认为 3,即 RGB 彩色图像。
    # 参数 nc 表示分类问题的类别数,如果为 None 则表示没有分类问题(默认为 None)。
    # 参数 anchors 表示先验框(默认为 None)。
    # 由于这里是yaml文件,最后加载到了self.yaml中
    def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None):  # model, input channels, number of classes
        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
            with open(cfg, encoding='ascii', errors='ignore') as f:
                self.yaml = yaml.safe_load(f)  # model dict

    # 定义模型
    # Define model
        # 添加了一个ch键值对,ch:3(3通道)
        ch = self.yaml['ch'] = self.yaml.get('ch', ch)  # input channels
        # 根据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
        # 根据yaml中的值,更新anchors的值
        if anchors:
            # 打印信息
            LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}')
            self.yaml['anchors'] = round(anchors)  # override yaml value

        # 利用 parse_model() 函数解析self.yaml字典,生成模型及其保存列表(savelist),
        # 并将它们分别存储在 self.model 和 self.save 属性中。ch=[ch] 表示将输入的通道数设置为 ch。
        # 根据 self.yaml 中的类别数 nc,生成一个默认的类别名列表,存储在 self.names 属性中。这里利用了 Python 的列表推导式。
        # 从 self.yaml 中获取是否需要 inplace 操作的配置信息,并将其存储在 self.inplace 属性中。
        # 根据yaml文件构建了yolov5的模型存入了self.model中。这里可以看下parse_model看看如何搭建yolov5的网络结构
        # 得到了模型结构,以及哪些层需要保存
        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的大小
        # 输入256;输出32;256*32=8;

        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)
            m.stride = torch.tensor([s / x.shape[-2] for x in forward(torch.zeros(1, ch, s, s))])  # forward
            # 检测anchor的顺序,确保低层和高层各自检验各自
            check_anchor_order(m)
            # 由于原图在特征层上已经缩小了8倍,这里anchor也需要缩小8倍进行检测
            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):
        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


class SegmentationModel(DetectionModel):
    # YOLOv5 segmentation model
    def __init__(self, cfg='yolov5s-seg.yaml', ch=3, nc=None, anchors=None):
        super().__init__(cfg, ch, nc, anchors)
class ClassificationModel(BaseModel):
    # YOLOv5 classification model
    def __init__(self, cfg=None, model=None, nc=1000, cutoff=10):  # yaml, model, number of classes, cutoff index
        super().__init__()
        self._from_detection_model(model, nc, cutoff) if model is not None else self._from_yaml(cfg)

    def _from_detection_model(self, model, nc=1000, cutoff=10):
        # Create a YOLOv5 classification model from a YOLOv5 detection model
        if isinstance(model, DetectMultiBackend):
            model = model.model  # unwrap DetectMultiBackend
        model.model = model.model[:cutoff]  # backbone
        m = model.model[-1]  # last layer
        ch = m.conv.in_channels if hasattr(m, 'conv') else m.cv1.conv.in_channels  # ch into module
        c = Classify(ch, nc)  # Classify()
        c.i, c.f, c.type = m.i, m.f, 'models.common.Classify'  # index, from, type
        model.model[-1] = c  # replace
        self.model = model.model
        self.stride = model.stride
        self.save = []
        self.nc = nc

    def _from_yaml(self, cfg):
        # Create a YOLOv5 classification model from a *.yaml file
        self.model = None

########################################################################################################################
# 第四部分
# 这里的d是跳转前解析yaml文件得到的列表
def parse_model(d, ch):  # model_dict, input_channels(3)
    # Parse a YOLOv5 model.yaml dictionary
    # 以第一行举例子
    # 打印信息
    LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10}  {'module':<40}{'arguments':<30}")
    # 取anchors先验框,nc类别数,深度倍数,宽度倍数,activation
    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

    # anchors取了[10,13, 16,30, 33,23],而每个anchor都是宽和高的组成,因此len(anchors[0])/2 = 6/2 = 3
    na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors  # number of anchors
    # 输出通道数;每个目标有三个anchors来检验,则总的3*(80+ 4 + 1) 80类别,x,y,w,h,p
    no = na * (nc + 5)  # number of outputs = anchors * (classes + 5)

    # layers存储网络层;save判断哪些层需要保存,方便后面层使用;c2是输出通道数
    layers, save, c2 = [], [], ch[-1]  # layers, savelist, ch out

    # 搭建每一层
    #  f=from(上一层);n:number模块数量;m是model(Conv);args:[64, 6, 2, 2]
    for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']):  # from, number, module, args
        # eval将m(Conv)转换成了Python表达式并执行,而这里Conv是一个common.py的一个函数
        m = eval(m) if isinstance(m, str) else m  # eval strings
        # 对于参数列表args中的每个元素a,如果它的类型是字符串,那么把它转换成Python表达式,然后再把结果赋值给原来的位置
        # 这里最终得到的还是[64,6,2,2]
        for j, a in enumerate(args):
            with contextlib.suppress(NameError):
                args[j] = eval(a) if isinstance(a, str) else a  # eval strings

        # 求最终的深度倍数n,四舍五入求得最终C3有几个模块。n*C3。
        n = n_ = max(round(n * gd), 1) if n > 1 else n  # depth gain

        # 这里判断m属于哪个模块,而这些模块都在common.py文件中
        if m in {
                Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,
                BottleneckCSP, C3, C3TR, C3SPP, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x}:

            # c2:args[0]是输出通道数64;c1是输入通道数,ch[-1]:3
            c1, c2 = ch[f], args[0]
            # 判断是不是等于no(256),最终的通道数
            if c2 != no:  # if not output
                # 计算当前输出真正的通道数 64*gw = 64*0.5=32,而且是8的倍数;对于GPU计算友好
                c2 = make_divisible(c2 * gw, 8)

            # 拼接最终的args参数: c1输入通道数,c2输出通道数; [3,32,6,2,2],这个参数在传入Conv函数的时候,就可以直接利用了。
            args = [c1, c2, *args[1:]]

            # 这段代码大致意思是,如果变量m的值在{BottleneckCSP, C3, C3TR, C3Ghost, C3x}这个集合中
            # 那么就在参数列表args的第三个位置(从0开始计数)插入一个值为n的元素,同时把n赋值为1。
            # 而这个n,在Conv传参时候,会用到。
            if m in {BottleneckCSP, C3, C3TR, C3Ghost, C3x}:
                args.insert(2, n)  # number of repeats
                n = 1
        #
        elif m is nn.BatchNorm2d:
            args = [ch[f]]
        elif m is Concat:
            c2 = sum(ch[x] for x in f)
        # TODO: channel, gw, gd
        elif m in {Detect, Segment}:
            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:
            c2 = ch[f]

        # 判断如C3模块,到底是有几个,当大于1时候,就会取得相应数量
        # nn.Sequential是PyTorch中用于构建神经网络模型的一个类。它可以将多个神经网络模块按顺序组合到一起,形成一个神经网络模型。
        m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args)  # module
        # 判断模块类型,也就是C3
        t = str(m)[8:-2].replace('__main__.', '')  # module type
        # 统计第0层得参数量
        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
        # 打印输入信息,也就是train.py运行得时候看到的每层的结构信息
        # n是有几个Conv模块
        # from    n    parms     module          argument
        #  -1     1     3520      Conv             [3,32,6,2,2]
        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
        layers.append(m_)
        # 当在第一层的时候,将ch置为空,并条件c2,也就是输出通道数32,再次执行for循环的时候,可以用来作用下一层的输入通道。
        if i == 0:
            ch = []
        ch.append(c2)
    return nn.Sequential(*layers), sorted(save) # 需要保存的层号 [6,4,14,10,17,20,23] > 排序 [4,6,10,14,17,20,23]

########################################################################################################################
# 第二部分:程序入口
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    # 加载模型yolov5模型文件,在models中有不同大小的模型
    parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')
    # batch-size大小
    parser.add_argument('--batch-size', type=int, default=1, help='total batch size for all GPUs')
    # cpu or gpu运算
    parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
    # 开启模型速度的分析功能;命令行开启;
    parser.add_argument('--profile', action='store_true', help='profile model speed')
    # 逐层分析模型速度
    parser.add_argument('--line-profile', action='store_true', help='profile model speed layer by layer')
    # 对所有yolo*.yaml 进行测试
    parser.add_argument('--test', action='store_true', help='test all yolo*.yaml')

    opt = parser.parse_args() # 调用 parser.parse_args() 方法解析命令行参数,并将其赋值给变量 opt
    opt.cfg = check_yaml(opt.cfg)  # check YAML # 根据 opt.cfg 的值,检查并调整 YAML 文件的格式,确保其可以被正确读取。其中 check_yaml() 函数可能是自定义的。
    print_args(vars(opt)) # 打印参数的值,使用 vars(opt) 将 Namespace 对象转化为字典对象,再使用 print_args() 函数将参数信息打印出来。
    device = select_device(opt.device) # 根据设备名称选定设备cpu or gpu,使用 select_device() 函数实现。该函数可能是自定义的,用于根据指定的设备名称选择相应的设备。

    # Create model 创建模型
    # 创建一个大小为 (batch_size, 3, 640, 640) 的张量 im,
    # 其中 batch_size 和 device 分别从命令行参数中获取,表示一批次的输入数据,共有 batch_size 个图像,每个图像为 RGB 三通道,分辨率为 640x640。
    # 创建一张图片,送入网络中
    im = torch.rand(opt.batch_size, 3, 640, 640).to(device)
    # 使用Model类创建一个模型model,其中opt.cfg 是命令行参数解析后得到的YAML配置文件路径。该类可能是自定义的,根据配置文件生成一个模型
    model = Model(opt.cfg).to(device)

    # Options
    # 如果opt.line_profile为True,则对模型进行逐层分析,即每一层的计算时间;
    # 如果opt.profile为True,则对模型进行前向和后向传播的分析,即整个模型的计算时间;
    # 如果opt.test为True,则测试所有的模型;
    # 否则,执行模型的合并操作,即调用model.fuse()函数。
    if opt.line_profile:  # profile layer by layer
        model(im, profile=True)
    elif opt.profile:  # profile forward-backward
        results = profile(input=im, ops=[model], n=3)
    elif opt.test:  # test all models
        for cfg in Path(ROOT / 'models').rglob('yolo*.yaml'):
            try:
                _ = Model(cfg)
            except Exception as e:
                print(f'Error in {cfg}: {e}')
    else:  # report fused model summary
        model.fuse()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值