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

深度学习中评估指标计算库TorchMetrics的使用

TorchMetrics是一个包含100多个PyTorch指标实现的集合(如分类、检测、分割、回归等)并提供易于使用的API来创建自定义指标。可以将TorchMetrics与任何PyTorch模型或PyTorch Lightning结合使用。源码地址https://github.com/Lightning-AI/torchmetrics最新发布版本为v1.9.0license为Apache-2.0。安装完YOLO环境后执行以下命令评估指标任务不同安装命令也不同pip install torchmetrics pip install torchmetrics[detection]YOLOv8/YOLO11/YOLO26有自己内置的评估逻辑一般不建议直接在训练循环内部强行替换其指标计算。这里训练完YOLOv8后评估只是为了演示TorchMetrics的使用。Classify主要测试代码如下def _parse_label_file(label_file): idx_to_class {} class_to_idx {} with open(label_file, moder, encodingutf-8) as f: for line in f: line line.strip() if not line: continue idx, name line.split() idx int(idx) idx_to_class[idx] name class_to_idx[name] idx return idx_to_class, class_to_idx def _get_images(images_path): image_files list(Path(images_path).rglob(*.*)) image_files [p for p in image_files if p.suffix.lower() in [.jpg, .jpeg, .png, .bmp, .webp]] if len(image_files) 0: raise RuntimeError(colorama.Fore.RED fno images found: {images_path}) return image_files def test_classify(model_name, images_path, label_file): if model_name is None or not model_name or not Path(model_name).is_file(): raise FileNotFoundError(colorama.Fore.RED f{model_name} is not a file) if images_path is None or not images_path or not Path(images_path).is_dir(): raise FileNotFoundError(colorama.Fore.RED f{images_path} is not a directory) if label_file is None or not label_file or not Path(label_file).is_file(): raise FileNotFoundError(colorama.Fore.RED f{label_file} is not a file) _, class_to_idx _parse_label_file(label_file) print(fclass to idx: {class_to_idx}) num_classes len(class_to_idx) acc_metric MulticlassAccuracy(num_classesnum_classes) f1_metric MulticlassF1Score(num_classesnum_classes) acc_metric.reset() f1_metric.reset() image_files _get_images(images_path) model YOLO(model_name) model.eval() with torch.no_grad(): for img_path in image_files: class_name img_path.parent.name if class_name not in class_to_idx: print(colorama.Fore.YELLOW finvalid image file: {img_path}) continue gt_label class_to_idx[class_name] results model(str(img_path), verboseFalse) probs results[0].probs.data pred_label int(torch.argmax(probs).item()) pred_tensor torch.tensor([pred_label]) gt_tensor torch.tensor([gt_label]) acc_metric.update(pred_tensor, gt_tensor) f1_metric.update(pred_tensor, gt_tensor) acc acc_metric.compute().item() f1 f1_metric.compute().item() print(colorama.Fore.GREEN fAccuracy: {acc:.4f}\nF1 Score: {f1:.4f})执行结果如下图所示Detect主要测试代码如下def test_detect(model_name, images_path, txts_path): if model_name is None or not model_name or not Path(model_name).is_file(): raise FileNotFoundError(colorama.Fore.RED f{model_name} is not a file) if images_path is None or not images_path or not Path(images_path).is_dir(): raise FileNotFoundError(colorama.Fore.RED f{images_path} is not a directory) if txts_path is None or not txts_path or not Path(txts_path).is_dir(): raise FileNotFoundError(colorama.Fore.RED f{txts_path} is not a directory) image_files _get_images(images_path) preds_all [] targets_all [] model YOLO(model_name) model.eval() with torch.no_grad(): for img_path in image_files: txt_path txts_path / img_path.stem .txt if not Path(txt_path).exists(): raise FileNotFoundError(colorama.Fore.RED f{txt_path} does not exist) img cv2.imread(str(img_path)) if img is None: raise FileNotFoundError(colorama.Fore.RED funable to load image file: {img_path}) h, w img.shape[:2] gt_boxes [] gt_labels [] with open(txt_path, moder, encodingutf-8) as f: for line in f: parts line.strip().split() if len(parts) ! 5: raise RuntimeError(colorama.Fore.RED f{txt_path}: file content is incorrect) cls int(parts[0]) cx, cy, bw, bh map(float, parts[1:]) x1 (cx - bw / 2) * w y1 (cy - bh / 2) * h x2 (cx bw / 2) * w y2 (cy bh / 2) * h gt_boxes.append([x1, y1, x2, y2]) gt_labels.append(cls) if len(gt_boxes) 0: gt_boxes torch.zeros((0, 4)) gt_labels torch.zeros((0,), dtypetorch.int64) else: gt_boxes torch.tensor(gt_boxes, dtypetorch.float32) gt_labels torch.tensor(gt_labels, dtypetorch.int64) results model(str(img_path), verboseFalse)[0] if results.boxes is None or len(results.boxes) 0: pred_boxes torch.zeros((0, 4)) pred_scores torch.zeros((0,)) pred_labels torch.zeros((0,), dtypetorch.int64) else: pred_boxes results.boxes.xyxy.cpu() pred_scores results.boxes.conf.cpu() pred_labels results.boxes.cls.cpu().to(torch.int64) preds_all.append({boxes: pred_boxes, scores: pred_scores, labels: pred_labels}) targets_all.append({boxes: gt_boxes, labels: gt_labels}) print(ftotal samples: {len(preds_all)}) metric MeanAveragePrecision(iou_typebbox, class_metricsTrue) metric.update(preds_all, targets_all) result metric.compute() print(fmetrics result: {result}) map50 result[map_50].item() map5095 result[map].item() print(colorama.Fore.GREEN fmAP50: {map50:.4f}\nmAP50-95: {map5095:.4f})执行结果如下图所示Segment主要测试代码如下def _polygon_to_mask(polygons, h, w): mask np.zeros((h, w), dtypenp.uint8) for poly in polygons: pts np.array(poly, dtypenp.int32).reshape(-1, 2) cv2.fillPoly(mask, [pts], 1) return mask def test_segment(model_name, images_path, txts_path): if model_name is None or not model_name or not Path(model_name).is_file(): raise FileNotFoundError(colorama.Fore.RED f{model_name} is not a file) if images_path is None or not images_path or not Path(images_path).is_dir(): raise FileNotFoundError(colorama.Fore.RED f{images_path} is not a directory) if txts_path is None or not txts_path or not Path(txts_path).is_dir(): raise FileNotFoundError(colorama.Fore.RED f{txts_path} is not a directory) image_files _get_images(images_path) model YOLO(model_name) num_classes len(model.names) 1 # 0:background metric MeanIoU(num_classesnum_classes, per_classTrue, input_formatindex) metric.reset() total 0 target_size (480, 480) model.eval() with torch.no_grad(): for img_path in image_files: txt_path txts_path / img_path.stem .txt if not Path(txt_path).exists(): raise FileNotFoundError(colorama.Fore.RED f{txt_path} does not exist) img cv2.imread(str(img_path)) if img is None: raise FileNotFoundError(colorama.Fore.RED funable to load image file: {img_path}) h, w img.shape[:2] gt_mask np.zeros((h, w), dtypenp.uint8) pred_mask np.zeros((h, w), dtypenp.uint8) with open(txt_path, moder, encodingutf-8) as f: for line in f: parts list(map(float, line.strip().split())) cls int(parts[0]) coords parts[1:] pts [] for i in range(0, len(coords), 2): x coords[i] * w y coords[i 1] * h pts.append([x, y]) mask _polygon_to_mask([pts], h, w) gt_mask[mask 1] cls 1 results model(str(img_path), verboseFalse)[0] if results.masks is not None: masks results.masks.data.cpu().numpy() classes results.boxes.cls.cpu().numpy().astype(int) for i in range(len(masks)): m masks[i] cls classes[i] m (m 0.5).astype(np.uint8) m cv2.resize(m, (w, h), interpolationcv2.INTER_NEAREST) pred_mask[m 1] cls 1 pred_tensor torch.tensor(cv2.resize(pred_mask, target_size, interpolationcv2.INTER_NEAREST)).long() gt_tensor torch.tensor(cv2.resize(gt_mask, target_size, interpolationcv2.INTER_NEAREST)).long() metric.update(pred_tensor.unsqueeze(0), gt_tensor.unsqueeze(0)) total 1 miou_per_class metric.compute() print(fmetrics result(per class): {miou_per_class}) miou miou_per_class[1:].mean().item() # remove backgroud print(colorama.Fore.GREEN ftotal samples: {total}\nmIoU: {miou:.4f})执行结果如下图所示GitHubhttps://github.com/fengbingchun/NN_Test

相关文章:

深度学习中评估指标计算库TorchMetrics的使用

TorchMetrics是一个包含100多个PyTorch指标实现的集合(如分类、检测、分割、回归等),并提供易于使用的API来创建自定义指标。可以将TorchMetrics与任何PyTorch模型或PyTorch Lightning结合使用。源码地址:https://github.com/Lightning-AI/torchmetrics&…...

Flutter 鸿蒙跨端开发实战:集成三方库实现鸿蒙设备 TODO 清单应用

欢迎加入开源鸿蒙跨平台社区: https://openharmonycrossplatform.csdn.net 本文专为鸿蒙入门开发者打造,以可直接运行的 TODO 清单项目为实战案例,手把手教你用 Flutter 跨端框架开发鸿蒙应用,全程包含Flutter 核心配置、三方库集…...

coze(扣子)5分钟产出爆火短视频操作详解

以前想做个短视频,得先拍摄,然后用PR、喀秋莎等专业软件剪辑,即使用后来面世的会声会影、剪映这类快捷软件,也得操作上一阵子。不过现在各种AI生成视频智能体层出不穷,大大降低了普通人玩短视频的门槛。今天送上一个使…...

47.网络基础

看课件,网络基础网络是操作系统一部分。多个局域网构成广域网。...

Unsloth Sglang Vllm核心区别和使用场景

(一)核心总结 Unsloth:主打「微调/训练加速」,推理只是附带 vLLM:通用推理引擎,主打「高吞吐、高显存利用率」 SGLang:推理引擎,主打「前缀复用、结构化输出、低延迟」 下面从定位、核心技术、性能、适用场景四个维度拆开讲。 一、定位 1. Unsloth 定位:微调优先、推…...

微信AI双开方案:HermesClaw实现iLink协议代理与多AI助手集成

1. 项目概述:一个微信账号,两个AI大脑如果你和我一样,既想体验 Hermes Agent 在代码生成和逻辑推理上的强大能力,又舍不得 OpenClaw 在文件处理和日常对话上的贴心与便捷,那么你肯定也遇到了那个让人头疼的问题&#x…...

AI 编程神器:MonkeyCode 使用心得 —— 重塑开发效率,

我使用 MonkeyCode 的心得分享 大家好!作为一名热爱编程刚入门不久的新手,我想分享一下我最近使用 MonkeyCode 的心得。MonkeyCode 是一款基于人工智能的编程辅助工具,它彻底改变了我的编码体验。从安装到日常使用,整个过程流畅无…...

ImageNet挑战赛:计算机视觉革命的里程碑

1. 计算机视觉领域的"奥林匹克":ImageNet挑战赛全景解读2010年那个闷热的夏天,当李飞飞教授团队首次发布ImageNet大规模视觉识别挑战赛(ILSVRC)时,恐怕没人能预料到这个比赛会成为引爆AI革命的导火索。作为计…...

Transformer跳跃连接:原理、实现与优化实践

1. 跳跃连接的本质与价值 在Transformer架构中,跳跃连接(Skip Connection)早已不是新鲜概念,但它的实际价值常常被低估。我第一次在Vision Transformer项目中系统性地测试不同位置的跳跃连接效果时,意外发现合理配置的…...

Weaviate向量数据库实战:从部署到多模态搜索与生产优化

1. 从零开始:理解Weaviate与向量数据库的核心价值 如果你正在机器学习和AI应用领域摸索,尤其是在处理文本、图像、音频这类非结构化数据时,一定绕不开一个核心问题:如何快速、准确地找到“相似”的内容?传统的基于关键…...

网络初级第五次作业(真机实验配置)

一、实验要求二、实验步骤1. 实验扩扑图2. 配置VLANSW1和SW2:SW3和SW4:3. 配置DHCP服务为PC1和PC2应用DHCP服务并查询IP地址4. 配置OSPF动态路由三、实验结果PC1与PC2通过DHCP动态获取IP地址,三层设备间运行OSPF动态路由协议,PC1可成功ping通PC2&#xf…...

Hugo博客自动化发布:基于OpenClaw的智能工作流实践

1. 项目概述与核心价值作为一名长期维护个人技术博客的开发者,我深知从写作到发布的流程中,那些看似微小却极其消耗心力的“最后一公里”问题。你可能也遇到过:写完一篇精心打磨的 Markdown 文章后,还需要手动编写 Hugo 的 Front …...

深度学习在影评情感分析中的应用与实践

1. 项目概述:基于深度学习的影评情感分析影评情感分析是自然语言处理(NLP)领域的经典任务,也是商业场景中应用最广泛的文本分类技术之一。我在多个电商和社交平台的内容分析系统中都实践过类似方案。这个项目的核心是通过深度学习…...

神经网络基础:从 RNN 的局限到 Transformer 的巅峰

前言 在第一课和第二课中,我们掌握了全连接网络和卷积网络(CNN)。全连接层擅长处理静态特征,卷积层擅长处理空间特征(图像)。 然而,当面对序列数据(如一句话、一段音频&#xff09…...

零基础秒落地!魔珐星云打造专属法务数字人

本次项目聚焦企业内部法务服务场景,依托魔珐星云具身智能数字人开放平台,打造专属企业法务数字人,简化交互形式,仅支持文字输入对话、数字人播报功能,适配企业内部法务咨询、内容传递需求。 项目开发简洁高效&#xf…...

杨校老师课堂之栈结构的专项训练

括号匹配 题目描述 假设表达式中允许包含圆括号和方括号两种括号,其嵌套的顺序随意,如()或[([][])]等为正确的匹配,[(])或(或(()))均为错误的匹配 本题的任务是检验一个给定的表达式中的括号是否匹配正确 输入一个只包含圆括号和方括号的字…...

项目实训——Werewolf-Agent 多智能体狼人杀中DSPy应用优化器优化

一、前言 上周,我在我们的项目中引入了dspy并使用它进行一个简单的测试,在测试过程中,我进行了几局游戏,发现预言家每次的输出结果都相差不大,这让我在玩起来比较无趣,因为在每个阶段,我都可以…...

2.3.2_3浮点数的加减运算(舍入问题)

IEEE754定义的4种舍入模式:舍入模式例子:0舍:1入:100类型:...

PR曲线绘制超简单

💓 博客主页:瑕疵的CSDN主页 📝 Gitee主页:瑕疵的gitee主页 ⏩ 文章专栏:《热点资讯》 PR曲线绘制超简单:从入门到自动化实战指南 目录 PR曲线绘制超简单:从入门到自动化实战指南 引言&#xff…...

【无人艇】基于matlab自适应多目标优化的UUV全覆盖路径规划【含Matlab源码 15379期】

💥💥💥💥💥💥💞💞💞💞💞💞💞💞欢迎来到海神之光博客之家💞💞💞&#x1f49…...

Linux USB驱动架构与性能优化实战

1. Linux USB驱动架构深度解析在嵌入式系统开发中,USB驱动作为连接主机与外围设备的关键桥梁,其性能直接影响整个系统的I/O效率。以TI的DaVinci平台为例,其USB驱动实现展现了Linux内核中USB子系统的典型架构与优化技巧。1.1 核心架构分层Linu…...

Python异常检测算法实战:隔离森林与LOF应用解析

1. 异常检测的核心价值与挑战在数据分析的实际场景中,异常点就像沙滩上的珍珠——它们可能代表最有价值的信息,也可能是需要剔除的噪声。我在金融风控领域第一次意识到异常检测的重要性,当时一个看似微小的数据异常背后隐藏着数百万美元的欺诈…...

NitroGen通用游戏AI:从像素到动作的行为克隆模型实战解析

1. 项目概述:从像素到操作,一个通用游戏智能体的诞生 如果你玩过游戏,尤其是那些需要快速反应的动作或射击游戏,你肯定有过这样的体验:看着高手行云流水的操作,心里想着“这操作我上我也行”,结…...

每一次科技的重大变化和政策的重大变化都是一次财富重新分配的机会,有变化就会有需求,你能满足需求就能获得利润

每一次科技的重大变化和政策的重大变化都是一次财富重新分配的机会,有变化就会有需求,你能满足需求就能获得利润 目录 每一次科技的重大变化和政策的重大变化都是一次财富重新分配的机会,有变化就会有需求,你能满足需求就能获得利润 一、第一句解析:稳态市场的利益固化,为…...

信自己,择热爱,事缓则圆

人这一辈子,最靠谱的活法:信自己,择热爱,事缓则圆 你有没有过这样的时刻? 站在人生的岔路口选行业,耳朵里全是外界的声音: “互联网大厂薪资高,挤破头也要进” “体制内才是铁饭碗,别瞎折腾” “这个赛道风口过了,你现在进来就是找死” 你跟着人流往前冲,选了别人…...

OpenClaw System Prompt 构建流程学习笔记

OpenClaw System Prompt 构建流程学习笔记 概述 本笔记详细记录了 OpenClaw 如何将 AGENTS.md 文件内容动态注入到 LLM 的 system 提示词中的完整调用链。该机制是 OpenClaw 工程化设计的核心:用户通过文件系统配置系统行为,而非硬编码。 ✅ 核心结论:AGENTS.md 的内容以原…...

小皮面板完全安装教程:2026年VPS新手从零到上线全攻略

目录 为什么选择小皮面板安装前的准备工作 选择合适的VPS系统要求连接到你的服务器 安装小皮面板 一键安装命令安装过程说明 首次登录与初始配置 访问面板后台修改默认密码开放防火墙端口 部署你的第一个网站 添加站点一键申请SSL证书上传网站文件 数据库管理安全设置建议常见…...

Python实现进化策略算法:原理与优化实践

1. 进化策略算法核心思想解析进化策略(Evolution Strategies, ES)作为一类基于种群的优化算法,其核心思想源于生物进化中的自然选择机制。与传统遗传算法不同,ES更强调参数向量的直接进化而非基因编码的交叉变异。在Python中实现这类算法,我们…...

小红书专业号主体变更流程

小红书专业号主体变更,核心就是把你当前专业号绑定的认证主体、经营主体或者账号归属关系,按照平台规则调整到新主体名下,整个流程资料齐全的话最快2到3个工作日就能完成,不用特意停更或者担心现有粉丝、历史内容受影响。小红书专…...

贝叶斯信念网络:原理、构建与应用实践

1. 贝叶斯信念网络入门指南第一次接触贝叶斯信念网络(Bayesian Belief Networks, BBN)是在研究生时期的一个医疗诊断项目里。当时我们需要建立一个能根据症状推断潜在疾病的概率模型,传统方法在变量间关系处理上捉襟见肘,直到导师推荐了这个"概率图…...