抄写yolov5---1模型

Posted 东东就是我

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了抄写yolov5---1模型相关的知识,希望对你有一定的参考价值。

yolov5代码梳理

1.yolo.py

import torch.nn as nn
import yaml
import argparse
import logging
from pathlib import Path
import sys
from copy import deepcopy
from layers import *
from utils.general import *

sys.path.append(Path(__file__).parent.parent.absolute().__str__())  # to run '$ python *.py' files in subdirectories
logger = logging.getLogger(__name__)


class Detect(nn.Module):
    stride = None

    def __init__(self, nc=80, anchors=(), ch=(), inplace=True):  # 类别,anchros,输入的层
        super(Detect, self).__init__()
        self.nc = nc
        self.no = nc + 5  # 每一个annchor 输出的个数 85
        self.nl = len(anchors)  # 检测的层 3
        self.na = len(anchors[0]) // 2  # 每一个网络有几个anchor 3
        self.grid = [torch.zeros(1)] * self.nl  # 初始化网格  [tensor([0.]), tensor([0.]), tensor([0.])]
        a = torch.tensor(anchors).float().view(self.nl, -1, 2)  # 3,-1,2
        self.register_buffer('anchors', a)  # 3,3,2
        self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2))  # 3,1,-1,1,1,2
        self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch)
        self.inplace = inplace

    def forward(self, x):
        z = []
        for i in range(self.nl):  # 3
            x[i] = self.m[i](x[i])  # 把3个输出层 转化为255通道 bs,255,20,20
            bs, _, ny, nx = x[i].shape  # batch_size,255,20,20 to batch_size,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:  # 推理阶段 todo
                if self.grid[i].shape[2:4] != x[i].shape[2:4]:
                    self.grid[i] = self._make_grid(nx, ny).to(x[i].device)  # 1,1,20,20,2
                y = x[i].sigmoid(x)
                if self.inplace:
                    y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i]  # x,y  缩小的倍数
                    y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i]  # wh

                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()


def parse_model(d, ch):  # 修改后的配置文件‘yolov5.yaml’,输人通道[3]
    logger.info('\\n%3s%18s%3s%10s  %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments'))
    anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d[
        'width_multiple']  # anchor ,类别(80), 模型深度缩减比例( 0.33),模型宽度缩减比例(0.50)
    na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors  # 每一个检测层配置的anchor的个数,这里是3
    no = na * (nc + 5)  # 输出大小,每一个anchor要输出类别加上xywh和置信度, 3*(80+5)
    # no=na*(nc+5+180) # 输出大小,每一个anchor要输出类别加上xywh和置信度和角度分类, 3*(80+5+180)
    layers, save, c2 = [], [], ch[-1]  # 层,保存的数据,输出
    for i, (f, n, m, args) in enumerate(
            d['backbone'] + d['head']):  # 加载配置文件中backone和head部分 ,[来自那一层,层个数,层名字,其他参数(卷积核大小和步长)]
        m = eval(m) if isinstance(m, str) else m  # 输出str类型的层名字
        for j, a in enumerate(args):  # 输出str格式的参数
            try:
                args[j] = eval(a) if isinstance(a, str) else a  #
            except:
                pass
        n = max(round(n * gd), 1) if n > 1 else n  # 修改网络的深度,如果大于1 就乘以相应缩减比例

        if m in [CBA, GhostConv, Bottleneck, GhostBottleneck, SPP, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP,
                 C3, C3TR, SELayer]:
            c1, c2 = ch[f], args[0]
            if c2 != no:  # if not output
                c2 = make_divisible(c2 * gw, 8)  # 保证是8的倍数

            args = [c1, c2, *args[1:]]
            if m in [BottleneckCSP, C3, C3TR]:
                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])
        elif m is Detect:
            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)
        elif m is Contract:
            c2 = ch[f] * args[0] ** 2
        elif m is Expand:
            c2 = ch[f] // args[0] ** 2
        elif m is SELayer:
            channel = args[0]
            channel = make_divisible(channel * gw, 8) if channel != no else channel
            args = [channel]
        else:
            c2 = ch[f]
        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('%3s%18s%3s%10.0f  %-40s%-30s' % (i, f, n, np, t, args))  # print
        save.extend(
            x % i for x in ([f] if isinstance(f, int) else f) if x != -1)  # append to savelist  [6,4,14,10,17,20,23]
        layers.append(m_)
        if i == 0:
            ch = []
        ch.append(c2)
    return nn.Sequential(*layers), sorted(save)


def initialize_weights(model):
    for m in model.modules():
        t=type(m)
        if t is nn.Conv2d:
            pass
        elif t is nn.BatchNorm2d:
            m.eps=1e-3
            m.momentum=0.03
        elif t in [nn.Hardswish,nn.LeakyReLU,nn.ReLU,nn.ReLU6]:
            m.inplace=True


class Model(nn.Module):
    def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None):  # 模型、输人、类别、anchors
        super(Model, self).__init__()
        if isinstance(cfg, dict):  # 如果是字典类型表示已经加载过了,否则加载模型配置文件
            self.yaml = cfg
        else:
            with open(cfg) as f:
                self.yaml = yaml.safe_load(f)

        # 定义模型
        ch = self.yaml['ch'] = self.yaml.get('ch', ch)  # input channels#图片输入通道

        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

        if anchors:
            logger.info(f'Overriding model.yaml anchors with anchors={anchors}')
            self.yaml['anchors'] = round(anchors)  # 修改配置文件的anchor

        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)

        m = self.model[-1]  # detect
        if isinstance(m, Detect):
            s = 128
            m.inplace = self.inplace
            m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))])  # 同过前向计算 ,得到缩小比例
            m.anchors /= m.stride.view(-1, 1, 1)  # 缩小相应比例
            check_anchor_order(m)  #  检测anchor排序
            self.stride = m.stride
            self._initialize_biases()

        initialize_weights(self)  #初始化eights, biases
        self.info()


    def forward(self, x, augment=False):
        if augment:  # 图像增强
            return self.forward_augment(x)
        else:
            return self.forward_once(x)

    def forward_augment(self,x):
        img_size=x.shape[-2:] #h,w
        s=[1,0.83,0.67]  #缩放
        f=[None,3,None]  #反转
        y=[]
        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]
            yi = self._descale_pred(yi, fi, si, img_size)  #对输出结果做缩放
            y.append(yi)
        return torch.cat(y,1),None

    def forward_once(self, x):
        y, dt = [], []
        for m in self.model:
            if m.f != -1:  # 不是来源前一个层,多个层相加
                x = [x if j == -1 else y[j] for j in m.f]
            x = m(x)
            y.append(x if m.i in self.save else None)  # 把[6,4,14,10,17,20,23] 层的输出保存起来
        return x

    def info(self, verbose=False, img_size=640):  # print model information
        model_info(self, verbose, img_size)
    def _descale_pred(self,p,flips,scale,img_size):  #输出,反转,缩放,输入的大小

        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
        return p

    def _initialize_biases(self,cf=None): # 初始化检测层的偏执,cf是类别概率
        m=self.model[-1]
        for mi ,s in zip(m.m,m.stride):
            b=mi.bias.view(m.na,-1)  #bias 255  to 3,85
            b.data[:, 4] += math.log(8 / (640 <

以上是关于抄写yolov5---1模型的主要内容,如果未能解决你的问题,请参考以下文章

AJAX相关JS代码片段和部分浏览器模型

8.17 动态规划——书的抄写

使用片段时 Intellij 无法正确识别 Thymeleaf 模型变量

php 一个自定义的try..catch包装器代码片段,用于执行模型函数,使其成为一个单行函数调用

如何防止在背面片段导航上再次设置视图模型

回顾这些年的学习技术经历