YOLO?v5引入解耦頭部完整步驟
前言
在 YOLO x中,使用了解耦頭部的方法,從而加快網(wǎng)絡(luò)收斂速度和提高精度,因此解耦頭被廣泛應(yīng)用于目標(biāo)檢測算法任務(wù)中。因此也想在YOLO v5的檢測頭部引入了解耦頭部的方法,從而來提高檢測精度和加快網(wǎng)絡(luò)收斂,但這里與 YOLO x 解耦頭部使用的檢測方法稍微不同,在YOLO v5中引入的解耦頭部依舊還是基于 anchor 檢測的方法。
一、解耦頭部示意圖
在YOLO x中,使用了解耦頭部的方法,具體論文請參考:https://arxiv.org/pdf/2107.08430.pdf
于是按照論文中的介紹就可以簡單的畫出解耦頭部,在YOLO v5中引入的解耦頭部最終還是基于 anchor 檢測的方法。

二、在YOLO v5 中引入解耦頭部
1.修改common.py文件
在common.py文件中加入以下代碼。
class DecoupledHead(nn.Module):
def __init__(self, ch=256, nc=80, anchors=()):
super().__init__()
self.nc = nc # number of classes
self.nl = len(anchors) # number of detection layers
self.na = len(anchors[0]) // 2 # number of anchors
self.merge = Conv(ch, 256, 1, 1)
self.cls_convs1 = Conv(256, 256, 3, 1, 1)
self.cls_convs2 = Conv(256, 256, 3, 1, 1)
self.reg_convs1 = Conv(256, 256, 3, 1, 1)
self.reg_convs2 = Conv(256, 256, 3, 1, 1)
self.cls_preds = nn.Conv2d(256, self.nc * self.na, 1)
self.reg_preds = nn.Conv2d(256, 4 * self.na, 1)
self.obj_preds = nn.Conv2d(256, 1 * self.na, 1)
def forward(self, x):
x = self.merge(x)
x1 = self.cls_convs1(x)
x1 = self.cls_convs2(x1)
x1 = self.cls_preds(x1)
x2 = self.reg_convs1(x)
x2 = self.reg_convs2(x2)
x21 = self.reg_preds(x2)
x22 = self.obj_preds(x2)
out = torch.cat([x21, x22, x1], 1)
return out2.修改yolo.py文件
修改后common.py文件后,需要修改yolo.py文件,主要修改兩個(gè)部分:
1.在model函數(shù),只需修改一句代碼,修改后如下:
if isinstance(m, Detect) or isinstance(m, Decoupled_Detect):
2.在parse_model函數(shù)中,修改后代碼如下:

3.在yolo.py增加Decoupled_Detect代碼
class Decoupled_Detect(nn.Module):
stride = None # strides computed during build
onnx_dynamic = False # ONNX export parameter
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.zeros(1)] * self.nl # init grid
self.anchor_grid = [torch.zeros(1)] * 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(DecoupledHead(x, nc, anchors) for x in ch)
self.inplace = inplace # use in-place 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.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()
if self.inplace:
y[..., 0:2] = (y[..., 0:2] * 2 + self.grid[i]) * self.stride[i] # xy
y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953
xy, wh, conf = y.split((2, 2, self.nc + 1), 4) # y.tensor_split((2, 4, 5), 4) # torch 1.8.0
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, -1, 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):
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)
if check_version(torch.__version__, '1.10.0'): # torch>=1.10.0 meshgrid workaround for torch>=0.7 compatibility
yv, xv = torch.meshgrid(y, x, indexing='ij')
else:
yv, xv = torch.meshgrid(y, x)
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_grid3.在model函數(shù)中,修改Build strides, anchors部分代碼,修改后代碼如下:
# Build strides, anchors
m = self.model[-1] # Detect()
if isinstance(m, Detect) or isinstance(m, Decoupled_Detect):
s = 256 # 2x min stride
m.inplace = self.inplace
m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
check_anchor_order(m) # must be in pixel-space (not grid-space)
m.anchors /= m.stride.view(-1, 1, 1)
self.stride = m.stride
# self._initialize_biases() # only run once
try :
self._initialize_biases() # only run once
LOGGER.info('initialize_biases done')
except :
LOGGER.info('decoupled no biase ')
initialize_weights(self)
self.info()
LOGGER.info('')3.修改模型的yaml文件
在模型的yaml文件中,修改最后一層檢測的頭的結(jié)構(gòu),我修改yolo v5s模型的最后一層檢測結(jié)構(gòu)如下:
[[17, 20, 23], 1, Decoupled_Detect, [nc, anchors]], # Detect(P3, P4, P5)
總結(jié)
至于單獨(dú)的增加解耦頭部,我還沒有對自己的數(shù)據(jù)集進(jìn)行單獨(dú)的訓(xùn)練,一般都是解耦頭部和其他模型結(jié)合在一起進(jìn)行訓(xùn)練,如果后期在訓(xùn)練的時(shí)候map有提升的話,我在把實(shí)驗(yàn)結(jié)果放在上面,最近也在跑實(shí)驗(yàn)結(jié)果對比。
到此這篇關(guān)于YOLO v5引入解耦頭部的文章就介紹到這了,更多相關(guān)YOLO v5引入解耦頭部內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python scipy.spatial.distance 距離計(jì)算函數(shù) ?
本文主要介紹了python scipy.spatial.distance 距離計(jì)算函數(shù),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
Python實(shí)現(xiàn)根據(jù)IP地址和子網(wǎng)掩碼算出網(wǎng)段的方法
這篇文章主要介紹了Python實(shí)現(xiàn)根據(jù)IP地址和子網(wǎng)掩碼算出網(wǎng)段的方法,涉及Python基于Linux平臺的字符串操作技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07
Python爬蟲基礎(chǔ)之簡單說一下scrapy的框架結(jié)構(gòu)
今天給大家?guī)淼氖顷P(guān)于Python爬蟲的相關(guān)知識,文章圍繞著scrapy的框架結(jié)構(gòu)展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06
在PyTorch中實(shí)現(xiàn)高效的多進(jìn)程并行處理
PyTorch是一個(gè)流行的深度學(xué)習(xí)框架,一般情況下使用單個(gè)GPU進(jìn)行計(jì)算時(shí)是十分方便的,但是當(dāng)涉及到處理大規(guī)模數(shù)據(jù)和并行處理時(shí),需要利用多個(gè)GPU,所以這篇文章我們將介紹如何利用torch.multiprocessing模塊,在PyTorch中實(shí)現(xiàn)高效的多進(jìn)程處理,需要的朋友可以參考下2024-07-07
Python實(shí)現(xiàn)求數(shù)列和的方法示例
這篇文章主要介紹了Python實(shí)現(xiàn)求數(shù)列和的方法,涉及Python數(shù)值運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2018-01-01
python flask框架實(shí)現(xiàn)重定向功能示例
這篇文章主要介紹了python flask框架實(shí)現(xiàn)重定向功能,結(jié)合實(shí)例形式分析了flask框架重定向功能的實(shí)現(xiàn)與使用方法,需要的朋友可以參考下2019-07-07

