涨点技巧:Detect系列---Yolov5/Yolov7加入解耦头Decoupled_Detect,涨点明显

article/2025/8/6 10:48:43

目录

1. Decoupled Head介绍

 2.Yolov5加入Decoupled_Detect

2.1 DecoupledHead加入common.py中:

2.2 Decoupled_Detect加入yolo.py中: 

2.3修改yolov5s_decoupled.yaml

3.数据集下验证性能


🏆 🏆🏆🏆🏆🏆🏆Yolov5/Yolov7成长师🏆🏆🏆🏆🏆🏆🏆
🍉🍉进阶专栏Yolov5/Yolov7魔术师:http://t.csdn.cn/D4NqB 🍉🍉
✨✨✨魔改网络、复现前沿论文,组合优化创新
🚀🚀🚀小目标、遮挡物、难样本性能提升
🌰 🌰 🌰在不同数据集验证能够涨点,对小目标涨点明显
 

1. Decoupled Head介绍

为什么要用到解耦头?

因为分类和定位的关注点不同;
分类更关注目标的纹理内容;
定位更关注目标的边缘信息;

        YOLOv6 采用了解耦检测头(Decoupled Head)结构,同时综合考虑到相关算子表征能力和硬件上计算开销这两者的平衡,采用 Hybrid Channels 策略重新设计了一个更高效的解耦头结构,在维持精度的同时降低了延时,缓解了解耦头中 3x3 卷积带来的额外延时开销。

          原始 YOLOv5 的检测头是通过分类和回归分支融合共享的方式来实现的,因此加入 Decoupled Head。

 2.Yolov5加入Decoupled_Detect

2.1 DecoupledHead加入common.py中:

class DecoupledHead(nn.Module):def __init__(self, ch=256, nc=80,  anchors=()):super().__init__()self.nc = nc  # number of classesself.nl = len(anchors)  # number of detection layersself.na = len(anchors[0]) // 2  # number of anchorsself.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 out

2.2 Decoupled_Detect加入yolo.py中: 

class Decouple(nn.Module):# Decoupled convolutiondef __init__(self, c1, nc=80, na=3):  # ch_in, num_classes, num_anchorssuper().__init__()c_ = min(c1, 256)  # min(c1, nc * na)self.na = na  # number of anchorsself.nc = nc  # number of classesself.a = Conv(c1, c_, 1)c = [int(x + na * 5) for x in (c_ - na * 5) * torch.linspace(1, 0, 4)]  # linear channel descentself.b1, self.b2, self.b3 = Conv(c_, c[1], 3), Conv(c[1], c[2], 3), nn.Conv2d(c[2], na * 5, 1)  # vcself.c1, self.c2, self.c3 = Conv(c_, c_, 1), Conv(c_, c_, 1), nn.Conv2d(c_, na * nc, 1)  # clsdef forward(self, x):bs, nc, ny, nx = x.shape  # BCHWx = self.a(x)b = self.b3(self.b2(self.b1(x)))c = self.c3(self.c2(self.c1(x)))return torch.cat((b.view(bs, self.na, 5, ny, nx), c.view(bs, self.na, self.nc, ny, nx)), 2).view(bs, -1, ny, nx)  class Decoupled_Detect(nn.Module):stride = None  # strides computed during buildonnx_dynamic = False  # ONNX export parameterexport = False  # export modedef __init__(self, nc=80, anchors=(), ch=(), inplace=True):  # detection layersuper().__init__()self.nc = nc  # number of classesself.no = nc + 5  # number of outputs per anchorself.nl = len(anchors)  # number of detection layersself.na = len(anchors[0]) // 2  # number of anchorsself.grid = [torch.zeros(1)] * self.nl  # init gridself.anchor_grid = [torch.zeros(1)] * self.nl  # init anchor gridself.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2))  # shape(nl,na,2)      self.m=nn.ModuleList(Decouple(x, self.nc, self.na)  for x in ch)   #yolov5 provide ,  old Decouple too much FLOPself.inplace = inplace  # use in-place ops (e.g. slice assignment)def forward(self, x):z = []  # inference outputfor i in range(self.nl):x[i] = self.m[i](x[i])  # convbs, _, 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:  # inferenceif 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]  # xyy[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i]  # whelse:  # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953xy, wh, conf = y.split((2, 2, self.nc + 1), 4)  # y.tensor_split((2, 4, 5), 4)  # torch 1.8.0xy = (xy * 2 + self.grid[i]) * self.stride[i]  # xywh = (wh * 2) ** 2 * self.anchor_grid[i]  # why = 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, 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

class BaseModel(nn.Module):

    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,Decoupled_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 self

 class DetectionModel(BaseModel):

    def _initialize_dh_biases(self, cf=None):  # initialize biases into Detect(), cf is class frequency# 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):  # from# reg_bias = mi.reg_preds.bias.view(m.na, -1).detach()# reg_bias += math.log(8 / (640 / s) ** 2)# mi.reg_preds.bias = torch.nn.Parameter(reg_bias.view(-1), requires_grad=True)# cls_bias = mi.cls_preds.bias.view(m.na, -1).detach()# cls_bias += math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum())  # cls# mi.cls_preds.bias = torch.nn.Parameter(cls_bias.view(-1), requires_grad=True)b = mi.b3.bias.view(m.na, -1)b.data[:, 4] += math.log(8 / (640 / s) ** 2)  # obj (8 objects per 640 image)mi.b3.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)b = mi.c3.bias.datab += math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum())  # clsmi.c3.bias = torch.nn.Parameter(b, requires_grad=True)
  if isinstance(m, (Detect, Segment,ASFF_Detect)):s = 256  # 2x min stridem.inplace = self.inplaceforward = lambda x: self.forward(x)[0] if isinstance(m, Segment) else self.forward(x)m.stride = torch.tensor([s / x.shape[-2] for x in forward(torch.zeros(1, ch, s, s))])  # forwardcheck_anchor_order(m)m.anchors /= m.stride.view(-1, 1, 1)self.stride = m.strideself._initialize_biases()  # only run onceelif isinstance(m, Decoupled_Detect):s = 256  # 2x min stridem.inplace = self.inplacem.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))])  # forwardcheck_anchor_order(m)  # must be in pixel-space (not grid-space)m.anchors /= m.stride.view(-1, 1, 1)self.stride = m.strideself._initialize_dh_biases()  # only run once

 def parse_model(d, ch):  # model_dict, input_channels(3)

        elif m in {Detect, Segment,Decoupled_Detect}:args.append([ch[x] for x in f])if isinstance(args[1], int):  # number of anchorsargs[1] = [list(range(args[1] * 2))] * len(f)if m is Segment:args[3] = make_divisible(args[3] * gw, 8)

2.3修改yolov5s_decoupled.yaml

# YOLOv5 🚀 by Ultralytics, GPL-3.0 license# Parameters
nc: 1  # number of classes
depth_multiple: 0.33  # model depth multiple
width_multiple: 0.50  # layer channel multiple
anchors:- [10,13, 16,30, 33,23]  # P3/8- [30,61, 62,45, 59,119]  # P4/16- [116,90, 156,198, 373,326]  # P5/32# 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, 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]# YOLOv5 v6.0 head
head:[[-1, 1, Conv, [512, 1, 1]],[-1, 1, nn.Upsample, [None, 2, 'nearest']],[[-1, 6], 1, Concat, [1]],  # cat backbone P4[-1, 3, C3, [512, False]],  # 13[-1, 1, Conv, [256, 1, 1]],[-1, 1, nn.Upsample, [None, 2, 'nearest']],[[-1, 4], 1, Concat, [1]],  # cat backbone P3[-1, 3, C3, [256, False]],  # 17 (P3/8-small)[-1, 1, Conv, [256, 3, 2]],[[-1, 14], 1, Concat, [1]],  # cat head P4[-1, 3, C3, [512, False]],  # 20 (P4/16-medium)[-1, 1, Conv, [512, 3, 2]],[[-1, 10], 1, Concat, [1]],  # cat head P5[-1, 3, C3, [1024, False]],  # 23 (P5/32-large)[[17, 20, 23], 1, Decoupled_Detect, [nc, anchors]],  # Detect(P3, P4, P5),解耦]

3.数据集下验证性能

基于Yolov5的道路缺陷识别,加入ASFF和EVC优化_AI&CV的博客-CSDN博客


http://chatgpt.dhexx.cn/article/yY3kK3yf.shtml

相关文章

Decoupled Contrastive Learning 论文解读和感想

本文首先提出了当前对比学习的三大痛点: 1、当前的sota方法结构都过于复杂 2、对比学习要想取得效果,必须要用大batch 3、超参敏感(个人认为这里说的超参是指数据增强方式) 然后本文以SimCLR为例,通过对对比损失的梯度进行分析,发…

DECOUPLED WEIGHT DECAY REGULARIZATION

引言 Adam作为一个常用的深度学习优化方法,提出来的时候论文里的数据表现都非常好,但实际在使用中发现了不少问题,在许多数据集上表现都不如SGDM这类方法。 后续有许多工作针对Adam做了研究,之前整理过关于优化算法的发展历程&am…

Decoupled Dynamic Filter Networks

转载自:https://www.cnblogs.com/liuyangcode/p/14755924.html 对depth-wise的改进,将卷积核的参数改为根据输入变化的方式 Introduction 卷积缺点在于:内容不变,计算量高动态filter可以根据内容自适应,但是会提高计算量。depth…

Analyzing and Leveraging Decoupled L1 Caches in GPUs

introduction 我们都知道L1/L2/L3cache解决了内存墙的问题,但是作者分析出现有的缓存架构有着天然缺陷, 作者列出的many to few communication,也就是L1ache中大量的数据传输到L2cache中,可能对于L1cache的带宽使用率不是很高&a…

Decoupled network

Decoupled network https://zhuanlan.zhihu.com/p/37598903 神经网络机制存在的缺陷? 过拟合,梯度消失或者是膨胀,训练依靠大量样本,对网络初始化及其敏感记忆协迁移等等。 Decupled network是对operator的改进 现在的卷积操作…

Decoupled Knowledge Distillation论文阅读+代码解析

本文来自2022年CVPR的文章,论文地址点这里 一. 介绍 知识蒸馏(KD)的通过最小化师生预测对数之间的KL-Divergence来传递知识(下图a)。目前大部分的研究注意力都被吸引到从中间层的深层特征中提取知识。与基于logit的精馏方法相比&#xff0c…

令牌桶算法

一 算法 令牌桶算法和漏桶算法不同的是,有时后端能够处理一定的突发情况,只是为了系统稳定,一般不会让请求超过正常情况的60%,给容灾留有余地。但漏桶算法中后端处理速度是固定的,对于短时的突发情况,后端…

动态分区分配算法(1、首次适应算法 2、最佳适应算法 3、最坏适应算法 4、邻近适应算法)

文章目录 前言知识总览1、首次适应算法2、最佳适应算法3、最坏适应算法4、邻近适应算法知识回顾与重要考点 前言 此篇文章是我在B站学习时所做的笔记,大部分图片都是课件老师的PPT,方便复习用。此篇文章仅供学习参考。 提示:以下是本篇文章…

《算法4》读书笔记(一)

写在前面:配套网站algs4.cs.princeton.edu,可以把这个网站作为编程的时候的参考资料。这本书比较实用(某瓣评分9.3),但没有动态规划部分,作为两三年没怎么碰过算法和数据结构的菜狗,看了《图解算…

《算法4》深入理解红黑树

红黑树是一种性能非常优秀的数据结构,关键在于它能保证最坏的性能也是对数的,主要是因为它是一种平衡的树,所以也叫平衡查找树。要理解红黑树,最好先看看我的上一篇博客《算法4》符号表以及二叉查找树,了解二叉查找树以…

【算法4总结】第四章:图

目录备份 第四章:图 概述 图可以根据是否有向和带权分成以下四种: 无向图 (无向不带权)有向图 (有向不带权)加权无向图(无向带权)加权有向图(有向带权) …

算法4(一、递归学习)

每次用递归都感觉有点难,这个趁着恶补基础知识的时候,专门看了一遍递归,算法4的。 1.1 递归介绍 方法可以调用自己,例如:下面给出了bin_search的二分查找的一种实现。(算法4中使用的是Java,但…

【算法4总结】第一章:基础

目录备份 第一章:基础 我认为这一章主要介绍的是如何使用工具。 一共五节,前两节主要是对 Java 语法的回顾,第三节则是三个数据结构,背包,队列和栈的API讲解。 而第四节是讲解的是如何分析算法。第五节则是针对具体…

SQL修改语句

如果我们要修改数据库中表的数据&#xff0c;这个时候我们就要使用到UPDATE语句。 UPDATE语句的基本语法是&#xff1a; UPDATE <表名> SET 字段1值1, 字段2值2, ... WHERE ...; 例如&#xff0c;我们想更新employees表id100的记录的last_name和salary这两个字段&…

【数据库】SQL语句之修改语句(INSERT,UPDATE,DELETE)

1.INSERT INSERT INTO <表名> (字段1, 字段2, ...) VALUES (值1, 值2, ...); 例如&#xff1a; 一次插入一个 INSERT INTO students (class_id, name, gender, score) VALUES (2, 小明, M, 80);一次插入多条 INSERT INTO students (class_id, name, gender, score) VA…

SQL Server修改数据

本篇主要讲解的是SQL Server 中修改数据的几种语句&#xff1a; INSERT语句INSERT INTO SELECT语句UPDATE语句DELETE语句 一&#xff1a;INSERT语句 INSERT语句向表中添加新行&#xff0c;以下是INSERT语句的最基本形式&#xff1a; 首先&#xff1a;table_name指定要插入的…

使用SQL语句修改表数据

使用SQL语句修改表数据 文章目录 使用SQL语句修改表数据利用INSERT语句输入数据利用UPDATE语句更新表数据利用DELETE语句删除表中数据利用Truncate Table语句删除表中数据 利用INSERT语句输入数据 INSERT语句的基本语法格式如下&#xff1a; 上述格式主要参数说明如下&#xf…

初探POC编写

文章目录 前言什么是POC什么是 ExpPOC注意事项尝试编写第一个POCpikachu sql盲注poc参考 前言 想锻炼一下编程能力&#xff0c;师兄说以后很重要的&#xff0c;最好学好一点 但是我又想学习安全相关的&#xff0c;那就来练练poc吧 什么是POC PoC(全称: Proof of Concept), …

POC_MeterSphere-RCE

MeterSphere-RCE 漏洞详情影响范围指纹- fingerPOC-YAML《飞致云MeterSphere开源测试平台远程代码执行漏洞》 漏洞详情 MeterSphere一站式开源持续测试平台存在的远程代码执行漏洞。由于自定义插件功能处存在缺陷,未经身份验证的攻击者可利用该漏洞在目标系统上远程执行任意…

【POC---概念验证】

文章目录 前言一、Proof of Concept是什么&#xff1f;验证内容 PoC测试工作准备前提PoC测试工作参与者PoC测试工作准备文档PoC测试工作第一阶段 工作启动第二阶段 产品宣讲及现场集中测试第三阶段 技术测评第四阶段 间歇性测试工作 第五阶段 商务验证第六阶段 背书归档、分析总…