当前位置: 首页 > news >正文

DETR中的损失计算

DETRTransformer用于目标检测的开山之作。不同于传统Anchor Based多个Anchor回归一个目标框的"多对一"方案,其在损失计算阶段使用二分图匹配(使用匈牙利算法)来一对一地选择目标框进行损失。得益于query作为一种可学习的先验且其能与整个图像交互,不断修正自身的特点;query的数目能够远远小于Anchor的数目。少量的query为使用一对一匹配创造了条件,无需使用多对一增加正样本数目,即可缓解正负样本不平衡带来的问题。除此之外一对一匹配的使用进一步移除了为多对一不优雅的NMS后处理,帮助DETR实现了真正优雅的端到端。

image

下面结合代码分析一下这部分。

损失计算入口

# dert.py/forwardimages = self.preprocess_image(batched_inputs)
output = self.detr(images)if self.training:gt_instances = [x["instances"].to(self.device) for x in batched_inputs]targets = self.prepare_targets(gt_instances)# 损失计算入口loss_dict = self.criterion(output, targets)# 加权计算损失weight_dict = self.criterion.weight_dictfor k in loss_dict.keys():if k in weight_dict:loss_dict[k] *= weight_dict[k]return loss_dict## 损失计算```python
# matcher.py/HungarianMatcher/forward
# 源代码注释十分详细啊,首先并行计算batch_size个图像中的代价矩阵,在DETR中该代价/损失为
# query与target之间的 分类损失+回归L1损失+回归Giou损失
# 代价矩阵并行计算完成后拆分成每个Batch,传递到scipy库中实现的linear_sum_assignment函数中,其作用是在N个query和M个target中
# 寻找到一个一对一的匹配使得损失最小化@torch.no_grad()def forward(self, outputs, targets):""" Performs the matchingParams:outputs: This is a dict that contains at least these entries:"pred_logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits"pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinatestargets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing:"labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truthobjects in the target) containing the class labels"boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinatesReturns:A list of size batch_size, containing tuples of (index_i, index_j) where:- index_i is the indices of the selected predictions (in order)- index_j is the indices of the corresponding selected targets (in order)For each batch element, it holds:len(index_i) = len(index_j) = min(num_queries, num_target_boxes)"""bs, num_queries = outputs["pred_logits"].shape[:2]# We flatten to compute the cost matrices in a batchout_prob = outputs["pred_logits"].flatten(0, 1).softmax(-1)  # [batch_size * num_queries, num_classes]out_bbox = outputs["pred_boxes"].flatten(0, 1)  # [batch_size * num_queries, 4]# Also concat the target labels and boxestgt_ids = torch.cat([v["labels"] for v in targets])tgt_bbox = torch.cat([v["boxes"] for v in targets])# Compute the classification cost. Contrary to the loss, we don't use the NLL,# but approximate it in 1 - proba[target class].# The 1 is a constant that doesn't change the matching, it can be ommitted.cost_class = -out_prob[:, tgt_ids]# Compute the L1 cost between boxescost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1)# Compute the giou cost betwen boxescost_giou = -generalized_box_iou(box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox))# Final cost matrixC = self.cost_bbox * cost_bbox + self.cost_class * cost_class + self.cost_giou * cost_giouC = C.view(bs, num_queries, -1).cpu()sizes = [len(v["boxes"]) for v in targets]indices = [linear_sum_assignment(c[i]) for i, c in enumerate(C.split(sizes, -1))]return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices]
http://www.jsqmd.com/news/415045/

相关文章:

  • 2026国内食堂承包公司哪家好TOP8|实力口碑实测榜单 - 企业推荐师
  • 2026年徐州办公设备租赁企业最新推荐榜:徐州租复印机、徐州租打印机、徐州会展复印机出租、徐州彩色复印机、徐州彩色打印机、聚焦服务品质与租赁方案竞争力深度剖析 - 海棠依旧大
  • EOM的逻辑构架(BIS 业务信息系统和MIS管理信息系统)(之四)--SMP(软件制作平台)语言基础知识之六十八
  • 2026年评价高的成都抚养权分割律师事务所公司推荐:成都法律辩护律师事务所咨询/成都经济律师事务所/选择指南 - 优质品牌商家
  • 【已解决】艾尔登法环提示d3dcompiler_47.dll丢失怎么办? - PC修复电脑医生
  • 2026年二手服务器与电子产品回收服务商推荐:至诚电脑/八方园通全解析 - 品牌推荐官
  • 西安直饮水机厂家怎么选?靠谱供应商推荐+专业科普 - 小坤哥
  • 武汉净水器服务商怎么选?专业科普+5家靠谱供应商推荐 - 小坤哥
  • 杨宝峰/梁海海团队发现RNA结合蛋白RBMS1的缺失可改善心力衰竭
  • 2026年国内靠谱的投影机出租品牌排名,8K投影机/30000流明投影机/6000流明投影机,投影机出租销售厂家哪家好 - 品牌推荐师
  • 2026年售楼处展厅厂家推荐:可定制的售楼处、可拆卸售楼处、可移动售楼处、可移动样板间、模块化样板间选择指南 - 优质品牌商家
  • 上古开源资源下载网站gforge.osdn.net.cn已彻底无法访问 —— 彻底关闭,消失了
  • 2026五大劳务派遣公司推荐,助力国企+实习生派遣需求 - 包罗万闻
  • 2026年全自动纸袋设备厂家推荐:纸袋机器、全自动纸袋机、卷筒纸袋机、圆绳内折纸袋机、尖底纸袋机、手提纸袋设备选择指南 - 优质品牌商家
  • 西安直饮水机一站式服务:详解服务内涵+靠谱供应商推荐 - 小坤哥
  • LLM+DevOps双驱联动:TestNG AI价值评分插件重构用例维护范式
  • 热销榜单:2026年二次元测量仪品牌推荐,提升测量精度的最佳选择 - 睿易优选
  • MATLAB运动估计基本算法详解
  • Pa11y自动化合规测试:WCAG 3.0时代的高效引擎
  • 涂装工艺:从经验依赖到数据驱动的系统性跃迁
  • 环保部门推荐!高口碑空气质量监测系统生产厂家TOP5名单发布 - 品牌推荐大师
  • 一文看懂蓝牙网关:主控芯片如何选型
  • 资源工具:Keda的自动扩缩容测试验证器
  • 全网热议!2026年智能马桶品牌推荐:市面上舒适性高的智能马桶厂商大对比 - 睿易优选
  • 2026年广州招标采购信息机构推荐:立达标讯与e交易基于数据覆盖与交易规模的双维选型指南 - 品牌推荐官
  • 压力小了! 降AI率软件 千笔 VS speedai,MBA专属更高效!
  • 建议收藏!普通人怎么抓住AI这波红利?AI时代,这是普通人翻身的好机会
  • 深度测评AI论文网站,千笔·专业学术智能体 VS 云笔AI,专为本科生打造!
  • 2026京东e卡如何回收?实测3种有效途径,安全变现不踩坑! - 京回收小程序
  • 255_尚硅谷_结构体 map 切片序列化