【YOLOV5-6.x讲解】模型搭建模块 models/yolo.py
生活随笔
收集整理的這篇文章主要介紹了
【YOLOV5-6.x讲解】模型搭建模块 models/yolo.py
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
??主干目錄:
【YOLOV5-6.x 版本講解】整體項目代碼注釋導航現在YOLOV5已經更新到6.X版本,現在網上很多還停留在5.X的源碼注釋上,因此特開一貼傳承開源精神!5.X版本的可以看其他大佬的帖子本文章主要從6.X版本出發,主要解決6.X版本的項目注釋與代碼分析!......https://blog.csdn.net/qq_39237205/article/details/125729662
以下內容為本欄目的一部分,更多關注以上鏈接目錄,查找YOLOV5的更多信息
祝福你朋友早日發表sci!
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license# https://blog.csdn.net/qq_39237205/category_11911202.html""" YOLO-specific modules這個模塊是yolov5的模型搭建模塊,非常的重要,不過代碼量并不大,不是很難,只是yolov5的作者把封裝的太好了,模型擴展了很多的額外的功能,導致看起來很難,其實真正有用的代碼不多的。重點是抓住三個函數是在哪里調用的,誰調用誰的。Usage:$ python path/to/models/yolo.py --cfg yolov5s.yaml """import argparse # 解析命令行參數模塊 import sys # sys系統模塊 包含了與Python解釋器和它的環境有關的函數 from copy import deepcopy # 數據拷貝模塊 深拷貝 from pathlib import Path # Path將str轉換為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 # ROOT = ROOT.relative_to(Path.cwd()) # relativefrom 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, scale_img, select_device, time_sync# 導入thop包 用于計算FLOPs try:import thop # for FLOPs computation except ImportError:thop = Noneclass Detect(nn.Module):"""Detect模塊是用來構建Detect層的,將輸入feature map 通過一個卷積操作和公式計算到我們想要的shape, 為后面的計算損失或者NMS作準備"""stride = None # strides computed during buildonnx_dynamic = False # ONNX export parameter 再export中這個參數會重新設為Truedef __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layersuper().__init__()"""detection layer 相當于yolov3中的YOLOLayer層:params nc: number of classes:params anchors: 傳入3個feature map上的所有anchor的大小(P3、P4、P5):params ch: [128, 256, 512] 3個輸出feature map的channel"""self.nc = nc # number of classes,若是VOC,則類別為20self.no = nc + 5 # number of outputs per anchor。 若是VOC: 5+20=25 該數為:xywhc+classesself.nl = len(anchors) # number of detection layers Detect的個數 3self.na = len(anchors[0]) // 2 # number of anchors 每個feature map的anchor個數 3self.grid = [torch.zeros(1)] * self.nl # init grid {list: 3} tensor([0.]) X 3self.anchor_grid = [torch.zeros(1)] * self.nl # init anchor grid# a=[3, 3, 2] anchors以[w, h]對的形式存儲 3個feature map 每個feature map上有三個anchor(w,h)# a = torch.tensor(anchors).float().view(self.nl, -1, 2)# register_buffer# 模型中需要保存的參數一般有兩種:# 一種是反向傳播需要被optimizer更新的,即參與訓練的參數稱為parameter,optim.step只能更新nn.parameter類型的參數# 另一種不要被更新,即不參與訓練的參數稱為buffer,buffer的參數更新是在forward中。# shape(nl,na,2)# self.register_buffer('anchors', a)self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2)# output conv 對每個輸出的feature map都要調用一次conv1x1self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv# use in-place ops (e.g. slice assignment) 一般都是True 默認不使用AWS Inferentia加速self.inplace = inplace # use in-place ops (e.g. slice assignment)def forward(self, x): # x:[[],[],[]]分別對應1/8 1/16 1/32 三個維度大小的寬高輸入# forward函數在Model類的forward_once中調用""":returntrain: 一個tensor list 存放三個元素 [bs, anchor_num, grid_w, grid_h, xywh+c+20classes]分別是 [1, 3, 80, 80, 25] [1, 3, 40, 40, 25] [1, 3, 20, 20, 25]inference: 0 [1, 19200+4800+1200, 25] = [bs, anchor_num*grid_w*grid_h, xywh+c+20classes]1 一個tensor list 存放三個元素 [bs, anchor_num, grid_w, grid_h, xywh+c+20classes][1, 3, 80, 80, 25] [1, 3, 40, 40, 25] [1, 3, 20, 20, 25]"""z = [] # inference outputfor i in range(self.nl): # 對三個feature map分別進行處理,遍歷一共多少層x[i] = self.m[i](x[i]) # conv xi[bs, 128/256/512, 80, 80] to [bs, 75, 80, 80]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()# inference,預測部分if not self.training: # inference# 構造網格# 因為推理返回的不是歸一化后的網格偏移量 需要再加上網格的位置 得到最終的推理坐標 再送入nms# 所以這里構建網格就是為了記錄每個grid的網格坐標 方面后面使用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() # 將每一層的特征歸一化到0到1之間if self.inplace:# 默認執行 不使用AWS Inferentia# 這里的公式和yolov3、v4中使用的不一樣 是yolov5作者自己用的效果更好,邊框預測公式,ppt有# 計算中心點坐標,將0到1之間處理到原圖大小的區間y[..., 0:2] = (y[..., 0:2] * 2 - 0.5 + self.grid[i]) * self.stride[i] # xy # xy||||| × self.stride[i]是為了放大到原圖# 計算寬高,將0到1之間處理到原圖大小的區間y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # whelse: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953xy = (y[..., 0:2] * 2 - 0.5 + self.grid[i]) * self.stride[i] # xywh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # why = torch.cat((xy, wh, y[..., 4:]), -1)# z是一個tensor list 三個元素 分別是[1, 19200, 25] [1, 4800, 25] [1, 1200, 25]z.append(y.view(bs, -1, self.no))return x if self.training else (torch.cat(z, 1), x)def _make_grid(self, nx=20, ny=20, i=0):"""構造網格"""d = self.anchors[i].deviceif check_version(torch.__version__, '1.10.0'): # torch>=1.10.0 meshgrid workaround for torch>=0.7 compatibilityyv, xv = torch.meshgrid([torch.arange(ny, device=d), torch.arange(nx, device=d)], indexing='ij')else:yv, xv = torch.meshgrid([torch.arange(ny, device=d), torch.arange(nx, device=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()return grid, anchor_gridclass Model(nn.Module):def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes"""Model主要包含模型的搭建與擴展功能,yolov5的作者將這個模塊的功能寫的很全,擴展功能如:特征可視化,打印模型信息、TTA推理增強、融合Conv+Bn加速推理、模型搭載nms功能、autoshape函數:模型搭建包含前處理、推理、后處理的模塊(預處理 + 推理 + nms)。感興趣的可以仔細看看,不感興趣的可以直接看__init__和__forward__兩個函數即可。: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 dictelse: # is *.yaml# is *.yaml 一般執行這里import yaml # for torch hubself.yaml_file = Path(cfg).name # cfg file name = yolov5s.yaml# 如果配置文件中有中文,打開時要加encoding參數with open(cfg, encoding='ascii', errors='ignore') as f:# model dict 取到配置文件中每條的信息(沒有注釋內容)self.yaml = yaml.safe_load(f) # model dict# Define modelch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels# 設置類別數 一般不執行, 因為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# 重寫anchor,一般不執行, 因為傳進來的anchors一般都是Noneif 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的序號,并排好序 [4, 6, 10, 14, 17, 20, 23]self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist# default class names ['0', '1', '2',..., '19']self.names = [str(i) for i in range(self.yaml['nc'])] # default names# self.inplace=True 默認True 不使用加速推理# AWS Inferentia Inplace compatiability# https://github.com/ultralytics/yolov5/pull/2953self.inplace = self.yaml.get('inplace', True)# 獲取Detect模塊的stride(相對輸入圖像的下采樣率)和anchors在當前Detect輸出的feature map的尺度# Build strides, anchorsm = self.model[-1] # Detect()if isinstance(m, Detect):s = 256 # 2x min stridem.inplace = self.inplace# 計算三個feature map下采樣的倍率 [8, 16, 32]# 假設640X640的圖片大小,在最后三層時分別乘1/8 1/16 1/32,得到80,40,20m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # 前向傳播的處理,為了得到最后輸出的stride的大小 # forward# 將當前圖片的大小處理成相對當前feature map的anchor大小 如[10, 13]/8 -> [1.25, 1.625]m.anchors /= m.stride.view(-1, 1, 1)# 檢查anchor順序與stride順序是否一致check_anchor_order(m)self.stride = m.strideself._initialize_biases() # only run once # only run once 初始化偏置# logger.info('Strides: %s' % m.stride.tolist())# Init weights, biasesinitialize_weights(self) # 調用torch_utils.py下initialize_weights初始化模型權重self.info() # 打印模型信息LOGGER.info('')def forward(self, x, augment=False, profile=False, visualize=False):# augmented inference, None 上下flip/左右flip# 是否在測試時也使用數據增強 Test Time Augmentation(TTA)if augment:return self._forward_augment(x) # augmented inference, None# 默認執行 正常前向推理# single-scale inference, trainreturn self._forward_once(x, profile, visualize) # single-scale inference, traindef _forward_augment(self, x):img_size = x.shape[-2:] # height, widths = [1, 0.83, 0.67] # scalesf = [None, 3, None] # flips (2-ud, 3-lr)y = [] # outputsfor 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# cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save# _descale_pred將推理結果恢復到相對原圖圖片尺寸yi = self._descale_pred(yi, fi, si, img_size)y.append(yi)y = self._clip_augmented(y) # clip augmented tailsreturn torch.cat(y, 1), None # augmented inference, traindef _forward_once(self, x, profile=False, visualize=False):""":params x: 輸入圖像:params profile: True 可以做一些性能評估:params feature_vis: True 可以做一些特征可視化:return train: 一個tensor list 存放三個元素 [bs, anchor_num, grid_w, grid_h, xywh+c+20classes]分別是 [1, 3, 80, 80, 25] [1, 3, 40, 40, 25] [1, 3, 20, 20, 25]inference: 0 [1, 19200+4800+1200, 25] = [bs, anchor_num*grid_w*grid_h, xywh+c+20classes]1 一個tensor list 存放三個元素 [bs, anchor_num, grid_w, grid_h, xywh+c+20classes][1, 3, 80, 80, 25] [1, 3, 40, 40, 25] [1, 3, 20, 20, 25]"""# y: 存放著self.save=True的每一層的輸出,因為后面的層結構concat等操作要用到# dt: 在profile中做性能評估時使用y, dt = [], [] # outputsfor m in self.model:# 前向推理每一層結構 m.i=index m.f=from m.type=類名 m.np=number of params# if not from previous layer m.f=當前層的輸入來自哪一層的輸出 s的m.f都是-1if m.f != -1: # if not from previous layer# 這里需要做4個concat操作和1個Detect操作# concat操作如m.f=[-1,6] x就有兩個元素,一個是上一層的輸出,另一個是index=6的層的輸出 再送到x=m(x)做concat操作# Detect操作m.f=[17, 20, 23] x有三個元素,分別存放第17層第20層第23層的輸出 再送到x=m(x)做Detect的forwardx = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers# 打印日志信息 FLOPs time等# 打印日志信息 前向推理時間if profile:self._profile_one_layer(m, x, dt)x = m(x) # run正向推理 執行每一層的forward函數(除Concat和Detect操作)# print('層數',i,'特征圖大小',x.shape)# 存放著self.save的每一層的輸出,因為后面需要用來作concat等操作要用到 不在self.save層的輸出就為Noney.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 xdef _descale_pred(self, p, flips, scale, img_size):"""用在上面的__init__函數上將推理結果恢復到原圖圖片尺寸 Test Time Augmentation(TTA)中用到de-scale predictions following augmented inference (inverse operation):params p: 推理結果:params flips::params scale::params img_size:"""# 不同的方式前向推理使用公式不同 具體可看Detect函數# de-scale predictions following augmented inference (inverse operation)if self.inplace: # 默認執行 不使用AWS Inferentiap[..., :4] /= scale # de-scaleif flips == 2:p[..., 1] = img_size[0] - p[..., 1] # de-flip udelif flips == 3:p[..., 0] = img_size[1] - p[..., 0] # de-flip lrelse:x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scaleif flips == 2:y = img_size[0] - y # de-flip udelif flips == 3:x = img_size[1] - x # de-flip lrp = torch.cat((x, y, wh, p[..., 4:]), -1)return pdef _clip_augmented(self, y):# Clip YOLOv5 augmented inference tailsnl = self.model[-1].nl # number of detection layers (P3-P5)g = sum(4 ** x for x in range(nl)) # grid pointse = 1 # exclude layer counti = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indicesy[0] = y[0][:, :-i] # largei = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indicesy[-1] = y[-1][:, i:] # smallreturn ydef _profile_one_layer(self, m, x, dt):c = isinstance(m, Detect) # is final layer, copy input as inplace fixo = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPst = 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 _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency"""用在上面的__init__函數上initialize biases into Detect(), cf is class frequencyhttps://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() modulefor mi, s in zip(m.m, m.stride): # fromb = 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()) # clsmi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)def _print_biases(self):"""打印模型中最后Detect層的偏置bias信息(也可以任選哪些層bias信息)"""m = self.model[-1] # Detect() modulefor mi in m.m: # fromb = 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 weightsdef fuse(self): # fuse model Conv2d() + BatchNorm2d() layers"""用在detect.py、val.pyfuse model Conv2d() + BatchNorm2d() layers調用torch_utils.py中的fuse_conv_and_bn函數和common.py中Conv模塊的fuseforward函數"""LOGGER.info('Fusing layers... ') # 日志# 遍歷每一層結構for m in self.model.modules():# 如果當前層是卷積層Conv且有bn結構, 那么就調用fuse_conv_and_bn函數講conv和bn進行融合, 加速推理if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):m.conv = fuse_conv_and_bn(m.conv, m.bn) # 融合 update convdelattr(m, 'bn') # 移除bn remove batchnormm.forward = m.forward_fuse # 更新前向傳播 update forward (反向傳播不用管, 因為這種推理只用在推理階段)self.info() # 打印conv+bn融合后的模型信息return selfdef info(self, verbose=False, img_size=640): # print model information"""用在上面的__init__函數上調用torch_utils.py下model_info函數打印模型信息"""model_info(self, verbose, img_size)def _apply(self, fn):# Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffersself = 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 selfdef parse_model(d, ch): # model_dict, input_channels(3)"""主要功能:parse_model模塊用來解析模型文件(從Model中傳來的字典形式),并搭建網絡結構。在上面Model模塊的__init__函數中調用這個函數其實主要做的就是: 更新當前層的args(參數),計算c2(當前層的輸出channel) =>使用當前層的參數搭建當前層 =>生成 layers + save:params d: model_dict 模型文件 字典形式 {dict:7} yolov5s.yaml中的6個元素 + ch:params ch: 記錄模型每一層的輸出channel 初始ch=[3] 后面會刪除:return nn.Sequential(*layers): 網絡的每一層的層結構:return sorted(save): 把所有層結構中from不是-1的值記下 并排序 [4, 6, 10, 14, 17, 20, 23]"""LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")# 讀取d字典中的anchors和parameters(nc、depth_multiple、width_multiple)# nc(number of classes)數據集類別個數;# depth_multiple,通過深度參數depth gain在搭建每一層的時候,實際深度 = 理論深度(每一層的參數n) * depth_multiple,起到一個動態調整模型深度的作用。# width_multiple,在模型中間層的每一層的實際輸出channel = 理論channel(每一層的參數c2) * width_multiple,起到一個動態調整模型寬度的作用。anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']# na: number of anchors 每一個predict head上的anchor數 = 3na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors# no: number of outputs 每一個predict head層的輸出channel = anchors * (classes + 5) = 75(VOC)no = na * (nc + 5) #總共預測的anchors個數 number of outputs = anchors * (classes + 5)# 開始搭建網絡# layers: 保存每一層的層結構# save: 記錄下所有層結構中from中不是-1的層結構序號# c2: 保存當前層的輸出channellayers, save, c2 = [], [], ch[-1] # layers, savelist, ch out# from(當前層輸入來自哪些層), number(當前層次數 初定), module(當前層類別), args(當前層類參數 初定)for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # 遍歷backbone和head的每一層 # from, number, module, args# eval(string) 得到當前層的真實類名# 例如: m= Focus -> <class 'models.common.Focus'>m = eval(m) if isinstance(m, str) else m # 將字符串處理成一個類名 或者 字符串,即實現名字向類的轉換for j, a in enumerate(args): # 主要照顧 yolo.yaml文件中最后一列的, [nc, anchors]try:args[j] = eval(a) if isinstance(a, str) else a # eval strings,當他是一個字符串,就試圖將它處理成一個變量名except NameError:pass# ------------------- 更新當前層的args(參數),計算c2(當前層的輸出channel) -------------------# depth gain 控制深度 如v5s: n*0.33 n: 當前模塊的次數(間接控制深度)n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gainif m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,BottleneckCSP, C3, C3TR, C3SPP, C3Ghost]:# c1: 當前層的輸入的channel數# c2: 當前層的輸出的channel數(初定)# ch: 記錄著所有層的輸出channel,f代表該ch中文最后一個,即對一下一層來說,這就是-1層的輸入c1, c2 = ch[f], args[0] # args[0]為[-1, 1, Conv, [128, 3, 2]]這的128# if not output no=75 只有最后一層c2=no 最后一層不用控制寬度,輸出channel必須是noif c2 != no: # if not output# width gain 控制寬度 如v5s: c2*width_multiple(yolo.yaml)# c2: 當前層的最終輸出的channel數(間接控制寬度)c2 = make_divisible(c2 * gw, 8)# 在初始arg的基礎上更新 加入當前層的輸入channel并更新當前層# [in_channel, out_channel, *args[1:]]args = [c1, c2, *args[1:]] # [-1, 1, Conv, [128, 3, 2]] 變為 [-1, 1, Conv, [-1的值,128 × width_multiple , 3, 2]]# 如果當前層是BottleneckCSP/C3/C3TR, 則需要在args中加入bottleneck的個數# [in_channel, out_channel, Bottleneck的個數n, bool(True表示有shortcut 默認,反之無)]if m in [BottleneckCSP, C3, C3TR, C3Ghost]: # 因為這幾個類的定義中,初始化中有n=1這個參數,整個過程就是在初始化卷積的參數罷了args.insert(2, n) # 在第二個位置插入bottleneck個數nn = 1 # 恢復默認值1elif m is nn.BatchNorm2d:# BN層只需要返回上一層的輸出channelargs = [ch[f]]elif m is Concat:# Concat層則將f中所有的輸出累加得到這層的輸出channelc2 = sum(ch[x] for x in f) # 因為這個[[-1, 6], 1, Concat, [1]] 的第一個是個列表,所以需要遍歷,然后將-1, 6層的輸入加起來elif m is Detect: # Detect(YOLO Layer)層# 在args中加入三個Detect層的輸出channelargs.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] ** 2elif m is Expand:c2 = ch[f] // args[0] ** 2else:# Upsamplec2 = ch[f] # args不變# m_: 得到當前層module 如果n>1就創建多個m(當前層結構), 如果n=1就創建一個m# n只有在[BottleneckCSP, C3, C3TR]中才會用到m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module# 打印當前層結構的一些基本信息t = str(m)[8:-2].replace('__main__.', '') # module typenp = sum(x.numel() for x in m_.parameters()) # number paramsm_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number paramsLOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print# append to savelist 把所有層結構中from不是-1的值記下 [6, 4, 14, 10, 17, 20, 23]save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist# 將當前層結構module加入layers中layers.append(m_)if i == 0:ch = [] # 去除輸入channel [3]# 把當前層的輸出channel數加入chch.append(c2)return nn.Sequential(*layers), sorted(save) # nn.Sequential(*layers) 處理成一個模型if __name__ == '__main__':parser = argparse.ArgumentParser()parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')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('--test', action='store_true', help='test all yolo*.yaml')opt = parser.parse_args()opt.cfg = check_yaml(opt.cfg) # check YAMLprint_args(FILE.stem, opt)device = select_device(opt.device)# Create modelmodel = Model(opt.cfg).to(device)model.train()# Profileif 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 modelsif 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
總結
以上是生活随笔為你收集整理的【YOLOV5-6.x讲解】模型搭建模块 models/yolo.py的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 天猫店群违规被降权,影响店铺权重的原因是
- 下一篇: 蔡德辉