国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

YOLOv5 白皮書-第Y5周:yolo.py文件解讀

這篇具有很好參考價值的文章主要介紹了YOLOv5 白皮書-第Y5周:yolo.py文件解讀。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

  • ?? 本文為??365天深度學(xué)習(xí)訓(xùn)練營 中的學(xué)習(xí)記錄博客
  • ?? 原作者:K同學(xué)啊|接輔導(dǎo)、項目定制
  • ?? 我的環(huán)境:
    ● 語言環(huán)境:Python 3.8
    ● 數(shù)據(jù)集:coco128
    ● 深度學(xué)習(xí)環(huán)境:Pytorch

一、前言

本周任務(wù):將YOLOv5s網(wǎng)絡(luò)模型中的C3模塊按照下圖方式修改形成C2模塊,并將C2模塊插入第2層與第3層之間,且跑通YOLOv5s。
任務(wù)提示:
提示1:需要修改common.yaml、yolo.py、yolov5s.yaml文件。
提示2:C2模塊與C3模塊是非常相似的兩個模塊,我們要插入C2到模型當(dāng)中,只需要找到哪里有C3模塊,然后在其附近加上C2即可。
YOLOv5 白皮書-第Y5周:yolo.py文件解讀
YOLOv5 白皮書-第Y5周:yolo.py文件解讀
YOLOv5 白皮書-第Y5周:yolo.py文件解讀

二、導(dǎo)入需要的包和基本配置

# YOLOv5 ?? by Ultralytics, GPL-3.0 license
"""
YOLO-specific modules

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

import argparse
import contextlib
import os
import platform
import sys
from copy import deepcopy
from pathlib import 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)

try:
    import thop  # for FLOPs computation
except ImportError:
    thop = None

三、 parse_model函數(shù)

這個函數(shù)用于將模型的模塊拼接起來,搭建完成的網(wǎng)絡(luò)模型。后續(xù)如果需要動模型框架的話,你需要對這個函數(shù)做相應(yīng)的改動。

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, 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 = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors  # number of anchors
    no = na * (nc + 5)  # number of outputs = anchors * (classes + 5)

    layers, save, c2 = [], [], ch[-1]  # layers, savelist, ch out
    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
        for j, a in enumerate(args):
            with contextlib.suppress(NameError):
                args[j] = eval(a) if isinstance(a, str) else a  # eval strings

        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, c2 = ch[f], args[0]
            if c2 != no:  # if not output
                c2 = make_divisible(c2 * gw, 8)

            args = [c1, c2, *args[1:]]
            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]

        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
        layers.append(m_)
        if i == 0:
            ch = []
        ch.append(c2)
    return nn.Sequential(*layers), sorted(save)


四、Detect類

Detect模塊是用來構(gòu)建Detect層的,將輸入featuremap通過一個卷積操作和公式計算到我們想要的shape,為后面的計算損失或者NMS作準(zhǔn)備。

Detect模塊代碼:

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

五、BaseModel類

這個模塊是整個模型的搭建模塊。且yolov5的作者將這個模塊的功能寫的很全,不光包含模型的搭建,還擴(kuò)展了很多功能如:特征可視化,打印模型信息、TTA推理增強(qiáng)、融合Conv+Bn加速推理、模型搭載nms功能、autoshape函數(shù):模型包含前處理、推理、后處理的模塊(預(yù)處理+推理+nms)。感興趣的可以仔細(xì)看看,不感興趣的可以直接看init和forward兩個函數(shù)即可。

BaseModel模塊代碼:


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

六、調(diào)整模型

1. common.py中生成C2

復(fù)制c3生成c2文章來源地址http://www.zghlxwxcb.cn/news/detail-471586.html

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

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

2. yolo.py的parse_model中增加c2

 if m in {
                Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,
                BottleneckCSP, C2, C3, C3TR, C3SPP, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x}:
            c1, c2 = ch[f], args[0]
            if c2 != no:  # if not output
                c2 = make_divisible(c2 * gw, 8)

            args = [c1, c2, *args[1:]]
            if m in {BottleneckCSP, C2, C3, C3TR, C3Ghost, C3x}:
                args.insert(2, n)  # number of repeats
                n = 1

3. yolov5s.yaml中增加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]], # todo
   [-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
  ]

到了這里,關(guān)于YOLOv5 白皮書-第Y5周:yolo.py文件解讀的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 海峽鏈技術(shù)白皮書-整體篇

    “引言:海峽鏈技術(shù)白皮書分為《海峽鏈技術(shù)白皮書-整體篇》、《海峽鏈技術(shù)白皮書-開放共識鏈篇》、《海峽鏈技術(shù)白皮書-開放許可鏈篇》和《海峽鏈技術(shù)白皮書-IPFS篇》四個章節(jié)?!逗{鏈技術(shù)白皮書-整體篇》對海峽鏈的設(shè)計思路、技術(shù)框架、產(chǎn)品生態(tài)等方面進(jìn)行了整體

    2023年04月12日
    瀏覽(28)
  • 以太坊白皮書(中英對照版)

    以太坊白皮書(中英對照版)

    Ethereum:A Next-Generation Smart Contract and Decentralized Application Platform 以太坊:下一代智能合約和去中心化應(yīng)用平臺 Satoshi Nakamoto’s development of Bitcoin in 2009 has often been hailed as a radical development in money and currency, being the first example of a digital asset which simultaneously has no backing or “intrinsic v

    2024年02月03日
    瀏覽(31)
  • Solana白皮書中文翻譯(1)

    Solana白皮書中文翻譯(1)

    作者:Anatoly Yakovenko(anatoly@solana.io) 翻譯:tangenter.eth 本文提出了一種新的區(qū)塊鏈架構(gòu),其基礎(chǔ)是一種能夠驗證鏈上事件發(fā)生的先后順序及時間間隔的新共識算法,稱作 工作歷史證明 (Proof of History,PoH)。PoH算法能夠?qū)⒉豢尚湃蔚臅r間間隔數(shù)據(jù)打包為區(qū)塊鏈賬本——一種只

    2024年02月02日
    瀏覽(26)
  • (四)yolov5--common.py文件解讀

    (四)yolov5--common.py文件解讀

    ??? 本文為??365天深度學(xué)習(xí)訓(xùn)練營 中的學(xué)習(xí)記錄博客 ?? 原作者:K同學(xué)啊|接輔導(dǎo)、項目定制? 參考網(wǎng)址:https://blog.csdn.net/qq_38251616/article/details/124665998 ? ? ? ? ? ? ? ? ??yolov5 代碼解讀 --common.py_XiaoGShou的博客-CSDN博客 ????????上次對yolov5s.yaml文件進(jìn)行了解讀,這次在

    2024年02月09日
    瀏覽(23)
  • 公告|Gear 官方白皮書正式發(fā)布!

    Gear 官方白皮書對開發(fā)者很有助益,將分為以下部分: Gear 協(xié)議的技術(shù)原理 Gear 網(wǎng)絡(luò)架構(gòu) Gear 協(xié)議的組成部分 Gear 與其他 dApp 開發(fā)網(wǎng)絡(luò)有何不同 為了使大家更好地了解 Gear 網(wǎng)絡(luò)的愿景,Gear 白皮書涵蓋以下內(nèi)容: 互聯(lián)網(wǎng)簡史,闡述第一代區(qū)塊鏈和現(xiàn)代區(qū)塊鏈的區(qū)別以及它們的

    2024年02月01日
    瀏覽(30)
  • 《金融數(shù)據(jù)保護(hù)治理白皮書》發(fā)布(137頁)

    《金融數(shù)據(jù)保護(hù)治理白皮書》發(fā)布(137頁)

    溫馨提示:文末附完整PDF下載鏈接 導(dǎo)讀 ? 目前業(yè)界已出臺數(shù)據(jù)保護(hù)方面的治理模型,但圍繞金融數(shù)據(jù)保護(hù)治理的實踐指導(dǎo)等尚不成熟,本課題圍繞數(shù)據(jù)保護(hù)治理的金融實踐、發(fā)展現(xiàn)狀,探索和標(biāo)準(zhǔn)化相關(guān)能力要求,歸納總結(jié)相關(guān)建設(shè)范式,推進(jìn)數(shù)據(jù)保護(hù)、治理在金融領(lǐng)域的

    2024年02月14日
    瀏覽(29)
  • Chainlink——白皮書簡析(whitepaper v2)

    Chainlink——白皮書簡析(whitepaper v2)

    ????????以目前區(qū)塊鏈公鏈比較成熟的生態(tài)以太坊為例,為了保證賬本的準(zhǔn)確性和智能合約執(zhí)行的確定性,以太坊節(jié)點虛擬機(jī)會被運(yùn)行在一個隔離的環(huán)境中,因此在虛擬機(jī)中運(yùn)行的智能合約代碼無法跟傳統(tǒng)編程語言一般直接從鏈下或者互聯(lián)網(wǎng)獲取數(shù)據(jù),所有鏈下的數(shù)據(jù)都需

    2023年04月09日
    瀏覽(23)
  • 《2023人工智能發(fā)展白皮書》發(fā)布(118頁)

    《2023人工智能發(fā)展白皮書》發(fā)布(118頁)

    導(dǎo)讀 nbsp; 本白皮書由七大部分組成。第一章人工智能產(chǎn)業(yè)鏈分析,描繪人工智能產(chǎn)業(yè)鏈全景圖,并對產(chǎn)業(yè)鏈各環(huán)節(jié)進(jìn)行深入分析;第二章人工智能行業(yè)環(huán)境,明確中國人工智能行業(yè)生命周期和競爭結(jié)構(gòu);第三章人工智能發(fā)展概況,闡述國內(nèi)外人工智能行業(yè)發(fā)展現(xiàn)狀;第四章人工智

    2024年02月09日
    瀏覽(30)
  • AI 大型語言模型的最佳應(yīng)用白皮書手冊

    目錄 What are large language models?什么是大型語言模型? Applications of large language models大語言模型的應(yīng)用

    2024年02月07日
    瀏覽(23)
  • 【中國金融機(jī)構(gòu) FRTB 合規(guī)的數(shù)據(jù)挑戰(zhàn) 白皮書】

    【中國金融機(jī)構(gòu) FRTB 合規(guī)的數(shù)據(jù)挑戰(zhàn) 白皮書】

    來源: 畢馬威,彭博 本報告將重點聚焦中國銀行業(yè)在實施 FRTB 過程中面臨的主要數(shù)據(jù)挑戰(zhàn),并探討可行的解決方案,旨在幫助機(jī)構(gòu)了解 FRTB 新規(guī)實施的要點與難點,充分評估現(xiàn)狀與差距,尋找到適合自身特點的 FRTB 實施路徑。本報告由來自全球領(lǐng)先的金融數(shù)據(jù)提供商彭博(

    2024年02月03日
    瀏覽(23)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包