- 🍨 本文為🔗365天深度學習訓練營 中的學習記錄博客
- 🍖 原作者:K同學啊
本次任務:將YOLOv5s網絡模型中的C3模塊按照下圖方式修改形成C2模塊,并將C2模塊插入第2層與第3層之間,且跑通YOLOv5s。
任務提示:
提示1:需要修改common.yaml、yolo.py、yolov5s.yaml文件。
提示2:C2模塊與C3模塊是非常相似的兩個模塊,我們要插入C2到模型當中,只需要找到哪里有C3模塊,然后在其附近加上C2即可。
文章目錄
- 1、前言
- 2、導入需要的包和基本配置
- 3、parse_model函數
- 4、Detect類
- 5、Model類
- 6、文件修改
- 1、./models/common.py 增加C2模塊
- 2、./models/yolo.py 在parse_model中增加C2
- 3、./models/yolov5s.yaml 在原第2層和原第3層之間插入C2模塊
- 4、訓練
1、前言
文件位置:./models/yolo.py
這個文件是YOLOv5網絡模型的搭建文件。如果需要改進YOLOv5,這個文件就是必須修改的文件之一。文件內容看起來多,真正有用的代碼不多,重點理解好穩重提到的一個函數和兩個類即可。
注: 由于YOLOv5版本眾多,同一個文件對于細節處可能會看到不同的版本,不用擔心這是正常的,注意把握好整體架構即可。
2、導入需要的包和基本配置
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
"""
YOLO-specific modules.Usage:$ python models/yolo.py --cfg yolov5s.yaml
"""import argparse
import contextlib
import math
import os
import platform
import sys
from copy import deepcopy
from pathlib import Pathimport torch
import torch.nn as nnFILE = 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())) # relativefrom models.common import *
from models.experimental import *
from utils.autoanchor import check_anchor_order
from utils.general import LOGGER, check_version, check_yaml, colorstr, 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
3、parse_model函數
這個函數用于將模型的模塊拼接起來,搭建完成的網絡模型。后續如果需要動模型框架的話,你需要對這個函數做相應的改動。
def parse_model(d, ch): # model_dict, input_channels(3)# Parse a YOLOv5 model.yaml dictionary''' 用在上面DetectionModel模塊中解析模型文件(字典形式),并搭建網絡結構這個函數其實主要做的就是:更新當前層的args(參數),計算c2(當前層的輸出channel)->使用當前層的參數搭建當前層->生成 layers + save:params d: model_dict模型文件,字典形式{dice: 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)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: 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) # number of outputs = anchors * (classes + 5)''' 開始搭建網絡layers: 保存每一層的層結構save: 記錄下所有層結構中from不是-1的層結構序號c2: 保存當前層的輸出channel'''layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out# from: 當前層輸入來自哪些層# number: 當前層數,初定# module: 當前層類別# args: 當前層類參數,初定# 遍歷backbone和head的每一層for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args# 得到當前層的真實類名,例如:m = Focus -> <class 'models.common.Focus'>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# --------------------更新當前層的args(參數),計算c2(當前層的輸出channel)--------------------# depth gain 控制深度,如yolov5s: 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, nn.ConvTranspose2d, DWConvTranspose2d, C3x}:# c1: 當前層的輸入channel數; c2: 當前層的輸出channel數(初定); ch: 記錄著所有層的輸出channel數c1, c2 = ch[f], args[0]# no=75,只有最后一層c2=no,最后一層不用控制寬度,輸出channel必須是noif c2 != no: # if not output# width gain 控制寬度,如yolov5s: c2*0.5; c2: 當前層的最終輸出channel數(間接控制寬度)c2 = make_divisible(c2 * gw, 8)# 在初始args的基礎上更新,加入當前層的輸入channel并更新當前層# [in_channels, out_channels, *args[1:]]args = [c1, c2, *args[1:]]# 如果當前層是BottleneckCSP/C3/C3TR/C3Ghost/C3x,則需要在args中加入Bottleneck的個數# [in_channels, out_channels, Bottleneck個數, Bool(shortcut有無標記)]if m in {BottleneckCSP, C3, C3TR, C3Ghost, C3x}:args.insert(2, n) # number of repeats 在第二個位置插入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)# TODO: channel, gw, gdelif m in {Detect, Segment}: # Detect/Segment(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)if m is Segment:args[3] = make_divisible(args[3] * gw, 8)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就創建一個mm_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module# 打印當前層結構的一些基本信息t = str(m)[8:-2].replace('__main__.', '') # module type <'modules.common.Focus'>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 paramsLOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print# 把所有層結構中的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)
4、Detect類
Detect模塊是用來構建Detect層的,將輸入的feature map通過一個卷積操作和公式計算到我們想要的shape,為后面的計算損失率或者NMS做準備。
Detect類代碼如下:
class Detect(nn.Module):# YOLOv5 Detect head for detection models''' Detect模塊是用來構建Detect層的將輸入的feature map通過一個卷積操作和公式計算到我們想要的shape,為后面的計算損失率或者NMS做準備'''stride = None # strides computed during builddynamic = False # force grid reconstructionexport = False # export modedef __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer''' detection layer 相當于yolov3中的YOLO Layer層:params nc: number of classes:params anchors: 傳入3個feature map上的所有anchor的大小(P3/P4/P5):params ch: [128,256,512] 3個輸出feature map的channel'''super().__init__()self.nc = nc # number of classes VOC: 20self.no = nc + 5 # number of outputs per anchor VOC: 5(xywhc)+20(classes)=25self.nl = len(anchors) # number of detection layers Detect的個數=3self.na = len(anchors[0]) // 2 # number of anchors 每個feature map的anchor個數=3self.grid = [torch.empty(0) for _ in range(self.nl)] # init grid {list: 3} tensor([0.])X3self.anchor_grid = [torch.empty(0) for _ in range(self.nl)] # init anchor grid''' 模型中需要保存的參數一般有兩種:一種是反向傳播需要被optimizer更新的,稱為parameter;另一種不需要被更新,稱為bufferbuffer的參數更新是在forward中,而optim.step只能更新nn.parameter參數'''self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2)# output conv 對每個輸出的feature map都要調用一次conv1 x 1self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv# 一般都是True,默認不使用AWS,Inferentia加速self.inplace = inplace # use inplace ops (e.g. slice assignment)def forward(self, x):''':return train: 一個tensor list,存放三個元素[bs, anchor_num, grid_w, grid_h, xywh+c+classes]分別是[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+classes]'''z = [] # inference outputfor i in range(self.nl): # 對3個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)# [bs,75,80,80] to [1,3,25,80,80] to [1,3,80,80,25]x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()''' 構造網格因為推理返回的不是歸一化后的網絡偏移量,需要加上網格的位置,得到最終的推理坐標,再送入NMS所以這里構建網絡就是為了記錄每個grid的網格坐標,方便后面使用'''if not self.training: # inferenceif 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] # xywh = (wh.sigmoid() * 2) ** 2 * self.anchor_grid[i] # why = 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] # xywh = (wh * 2) ** 2 * self.anchor_grid[i] # why = torch.cat((xy, wh, conf), 4)# z是一個tensor list,有三個元素,分別是[1,19200,25] [1,4800,25] [1,1200,25]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].devicet = self.anchors[i].dtypeshape = 1, self.na, ny, nx, 2 # grid shapey, 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 compatibilitygrid = torch.stack((xv, yv), 2).expand(shape) - 0.5 # add grid offset, i.e. y = 2.0 * x - 0.5anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape)return grid, anchor_grid
5、Model類
這個模塊是整個模型的搭建模塊。且yolov5的作者將這個模塊的功能寫的很全,不光包含模型的搭建,還擴展了很多功能,如:特征可視化、打印模型信息、TTA推理增強、融合Conv + BN加速推理、模型搭載NMS功能、Autoshape函數(模型包含前處理、推理、后處理的模塊(預處理 + 推理 + NMS))。感興趣的可以仔細看看,不感興趣的可以直接看__init__、forward兩個函數即可。
Model類代碼如下:
class BaseModel(nn.Module):# YOLOv5 base modeldef forward(self, x, profile=False, visualize=False):return self._forward_once(x, profile, visualize) # single-scale inference, traindef _forward_once(self, x, profile=False, visualize=False):''':params x: 輸入圖像:params profile: True 可以做一些性能評估:params visualize: True 可以做一些特征可視化:return train: 一個tensor,存放三個元素 [bs, anchor_num, grid_w, grid_h, xywh+c+classes]inference: 0 [1,19200+4800+1200,25]=[bs,anchor_num*grid_w*grid_h,xywh+c+classes]'''# 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 parametersif m.f != -1: # if not from previous layer m.f=當前層的輸入來自哪一層的輸出,-1表示上一層# 這里需要做4個Concat操作和一個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 正向推理# 存放著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 _profile_one_layer(self, m, x, dt):c = m == self.model[-1] # 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 fuse(self): # fuse model Conv2d() + BatchNorm2d() layers''' 用在detect.py、val.py中fuse model Conv2d() + BatchNorm2d() layers調用torch_utils.py中的fuse_conv_and_bn函數和common.py中的forward_fuse函數'''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 conv 融合delattr(m, 'bn') # remove batchnorm 移除BNm.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, 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 selfclass DetectionModel(BaseModel):# YOLOv5 detection modeldef __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes''':params cfg: 模型配置文件:params ch: input img channels 一般是3(RGB文件):params nc: number of classes 數據集的類別個數:params anchors: 一般是None'''super().__init__()if isinstance(cfg, dict):self.yaml = cfg # model dictelse: # 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: # encoding='utf-8'self.yaml = yaml.safe_load(f) # model dict# Define modelch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels ch=3# 設置類別數,一般不執行,因為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# 重寫anchors,一般不執行,因為傳進來的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)# Build strides, anchors# 獲取Detect模塊的stride(相對輸入圖像的下采樣率)和anchors在當前Detect輸出的feature map的尺寸m = self.model[-1] # Detect()if isinstance(m, (Detect, Segment)):s = 256 # 2x min stridem.inplace = self.inplaceforward = lambda x: self.forward(x)[0] if isinstance(m, Segment) else self.forward(x)# 計算三個feature map的anchor大小,如[10,13]/8 -> [1.25,1.625]m.stride = torch.tensor([s / x.shape[-2] for x in forward(torch.zeros(1, ch, s, s))]) # forward# 檢查anchor順序與stride順序是否一致check_anchor_order(m)m.anchors /= m.stride.view(-1, 1, 1)self.stride = m.strideself._initialize_biases() # only run once 初始化偏置# Init weights, biasesinitialize_weights(self) # 調用torch_utils.py下initialize_weights初始化模型權重self.info() # 打印模型信息LOGGER.info('')def forward(self, x, augment=False, profile=False, visualize=False):# 是否在測試時也使用數據增強 Test Time Augmentation(TTA)if augment:return self._forward_augment(x) # augmented inference, None 上下flip/左右flip# 默認執行,正常前向推理return self._forward_once(x, profile, visualize) # single-scale inference, traindef _forward_augment(self, x):''' TTA Test Time Augmentation '''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 _descale_pred(self, p, flips, scale, img_size):# de-scale predictions following augmented inference (inverse operation)''' 用在上面的__init__函數上將推理結果恢復到原圖圖片尺寸上 TTA中用到:params p: 推理結果:params flips: 翻轉標記(2-ud上下, 3-lr左右):params scale: 圖片縮放比例:params img_size: 原圖圖片尺寸'''# 不同的方式前向推理使用公式不同,具體可看Detect函數if self.inplace: # 默認執行True,不使用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 _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency''' 用在上面的__init__函數上 '''# 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() 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:5 + m.nc] += math.log(0.6 / (m.nc - 0.99999)) if cf is None else torch.log(cf / cf.sum()) # clsmi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
Model = DetectionModel
6、文件修改
1、./models/common.py 增加C2模塊
2、./models/yolo.py 在parse_model中增加C2
3、./models/yolov5s.yaml 在原第2層和原第3層之間插入C2模塊
4、訓練
python train.py --img 900 --batch 24 --epoch 100 --data data/ab.yaml --cfg models/yolov5s.yaml --weights yolov5s.pt
結果如下: