YOLOv5 分类模型 数据集加载 3
YOLOv5 分类模型 数据集加载 3 自定义类别
flyfish
YOLOv5 分类模型 数据集加载 1 样本处理
YOLOv5 分类模型 数据集加载 2 切片处理
YOLOv5 分类模型的预处理(1) Resize 和 CenterCrop
YOLOv5 分类模型的预处理(2)ToTensor 和 Normalize
YOLOv5 分类模型 Top 1和Top 5 指标说明
YOLOv5 分类模型 Top 1和Top 5 指标实现
之前的处理方式是类别名字是文件夹名字,类别ID是按照文件夹名字的字母顺序
现在是类别名字是文件夹名字,按照文件列表名字顺序 例如
classes_name=['n02086240', 'n02087394', 'n02088364', 'n02089973', 'n02093754',
'n02096294', 'n02099601', 'n02105641', 'n02111889', 'n02115641']
n02086240 类别ID是0
n02087394 类别ID是1
代码处理是
if classes_name is None or not classes_name:classes, class_to_idx = self.find_classes(self.root)print("not classes_name")else:classes = classes_nameclass_to_idx ={cls_name: i for i, cls_name in enumerate(classes)}print("is classes_name")
完整
import time
from models.common import DetectMultiBackend
import os
import os.path
from typing import Any, Callable, cast, Dict, List, Optional, Tuple, Union
import cv2
import numpy as npimport torch
from PIL import Image
import torchvision.transforms as transformsimport sysclasses_name=['n02086240', 'n02087394', 'n02088364', 'n02089973', 'n02093754', 'n02096294', 'n02099601', 'n02105641', 'n02111889', 'n02115641']class DatasetFolder:def __init__(self,root: str,) -> None:self.root = rootif classes_name is None or not classes_name:classes, class_to_idx = self.find_classes(self.root)print("not classes_name")else:classes = classes_nameclass_to_idx ={cls_name: i for i, cls_name in enumerate(classes)}print("is classes_name")print("classes:",classes)print("class_to_idx:",class_to_idx)samples = self.make_dataset(self.root, class_to_idx)self.classes = classesself.class_to_idx = class_to_idxself.samples = samplesself.targets = [s[1] for s in samples]@staticmethoddef make_dataset(directory: str,class_to_idx: Optional[Dict[str, int]] = None,) -> List[Tuple[str, int]]:directory = os.path.expanduser(directory)if class_to_idx is None:_, class_to_idx = self.find_classes(directory)elif not class_to_idx:raise ValueError("'class_to_index' must have at least one entry to collect any samples.")instances = []available_classes = set()for target_class in sorted(class_to_idx.keys()):class_index = class_to_idx[target_class]target_dir = os.path.join(directory, target_class)if not os.path.isdir(target_dir):continuefor root, _, fnames in sorted(os.walk(target_dir, followlinks=True)):for fname in sorted(fnames):path = os.path.join(root, fname)if 1: # 验证:item = path, class_indexinstances.append(item)if target_class not in available_classes:available_classes.add(target_class)empty_classes = set(class_to_idx.keys()) - available_classesif empty_classes:msg = f"Found no valid file for the classes {', '.join(sorted(empty_classes))}. "return instancesdef find_classes(self, directory: str) -> Tuple[List[str], Dict[str, int]]:classes = sorted(entry.name for entry in os.scandir(directory) if entry.is_dir())if not classes:raise FileNotFoundError(f"Couldn't find any class folder in {directory}.")class_to_idx = {cls_name: i for i, cls_name in enumerate(classes)}return classes, class_to_idxdef __getitem__(self, index: int) -> Tuple[Any, Any]:path, target = self.samples[index]sample = self.loader(path)return sample, targetdef __len__(self) -> int:return len(self.samples)def loader(self, path):print("path:", path)#img = cv2.imread(path) # BGR HWCimg=Image.open(path).convert("RGB") # RGB HWCreturn imgdef time_sync():return time.time()#sys.exit()
dataset = DatasetFolder(root="/media/a/flyfish/source/yolov5/datasets/imagewoof/val")#image, label=dataset[7]#
weights = "/home/a/classes.pt"
device = "cpu"
model = DetectMultiBackend(weights, device=device, dnn=False, fp16=False)
model.eval()
print(model.names)
print(type(model.names))mean=[0.485, 0.456, 0.406]
std=[0.229, 0.224, 0.225]
def preprocess(images):#实现 PyTorch Resizetarget_size =224img_w = images.widthimg_h = images.heightif(img_h >= img_w):# hwresize_img = images.resize((target_size, int(target_size * img_h / img_w)), Image.BILINEAR)else:resize_img = images.resize((int(target_size * img_w / img_h),target_size), Image.BILINEAR)#实现 PyTorch CenterCropwidth = resize_img.widthheight = resize_img.heightcenter_x,center_y = width//2,height//2left = center_x - (target_size//2)top = center_y- (target_size//2)right =center_x +target_size//2bottom = center_y+target_size//2cropped_img = resize_img.crop((left, top, right, bottom))#实现 PyTorch ToTensor Normalizeimages = np.asarray(cropped_img)print("preprocess:",images.shape)images = images.astype('float32')images = (images/255-mean)/stdimages = images.transpose((2, 0, 1))# HWC to CHWprint("preprocess:",images.shape)images = np.ascontiguousarray(images)images=torch.from_numpy(images)#images = images.unsqueeze(dim=0).float()return imagespred, targets, loss, dt = [], [], 0, [0.0, 0.0, 0.0]
# current batch size =1
for i, (images, labels) in enumerate(dataset):print("i:", i)im = preprocess(images)images = im.unsqueeze(0).to("cpu").float()print(images.shape)t1 = time_sync()images = images.to(device, non_blocking=True)t2 = time_sync()# dt[0] += t2 - t1y = model(images)y=y.numpy()#print("y:", y)t3 = time_sync()# dt[1] += t3 - t2#batch size >1 图像推理结果是二维的#y: [[ 4.0855 -1.1707 -1.4998 -0.935 -1.9979 -2.258 -1.4691 -1.0867 -1.9042 -0.99979]]tmp1=y.argsort()[:,::-1][:, :5]#batch size =1 图像推理结果是一维的, 就要处理下argsort的维度#y: [ 3.7441 -1.135 -1.1293 -0.9422 -1.6029 -2.0561 -1.025 -1.5842 -1.3952 -1.1824]#print("tmp1:", tmp1)pred.append(tmp1)#print("labels:", labels)targets.append(labels)#print("for pred:", pred) # list#print("for targets:", targets) # list# dt[2] += time_sync() - t3pred, targets = np.concatenate(pred), np.array(targets)
print("pred:", pred)
print("pred:", pred.shape)
print("targets:", targets)
print("targets:", targets.shape)
correct = ((targets[:, None] == pred)).astype(np.float32)
print("correct:", correct.shape)
print("correct:", correct)
acc = np.stack((correct[:, 0], correct.max(1)), axis=1) # (top1, top5) accuracy
print("acc:", acc.shape)
print("acc:", acc)
top = acc.mean(0)
print("top1:", top[0])
print("top5:", top[1])
相关文章:
YOLOv5 分类模型 数据集加载 3
YOLOv5 分类模型 数据集加载 3 自定义类别 flyfish YOLOv5 分类模型 数据集加载 1 样本处理 YOLOv5 分类模型 数据集加载 2 切片处理 YOLOv5 分类模型的预处理(1) Resize 和 CenterCrop YOLOv5 分类模型的预处理(2)ToTensor 和 …...
『亚马逊云科技产品测评』活动征文|AWS 存储产品类别及其适用场景详细说明
授权声明:本篇文章授权活动官方亚马逊云科技文章转发、改写权,包括不限于在 Developer Centre, 知乎,自媒体平台,第三方开发者媒体等亚马逊云科技官方渠道 目录 前言、AWS 存储产品类别 1、Amazon Elastic Block Store (EBS) …...
Mac | Vmware Fusion | 分辨率自动还原问题解决
1. 问题 Mac的Vmware Fusion在使用Windows10虚拟机时,默认显示器配置如下: 开机进入系统并变更默认分辨率后,只要被 ⌘Tab 切换分辨率就会还原到默认,非常影响体验。 2. 解决方式 调整 设置 -> 显示器 -> 虚拟机分辨率…...
SQL知多少?这篇文章让你从小白到入门
个人网站 本文首发公众号小肖学数据分析 SQL(Structured Query Language)是一种用于管理和处理关系型数据库的编程语言。 对于想要成为数据分析师、数据库管理员或者Web开发人员的小白来说,学习SQL是一个很好的起点。 本文将为你提供一个…...
centos7安装MySQL—以MySQL5.7.30为例
centos7安装MySQL—以MySQL5.7.30为例 本文以MySQL5.7.30为例。 官网下载 进入MySQL官网:https://www.mysql.com/ 点击DOWNLOADS 点击链接; 点击如上链接: 选择对应版本: 点击下载。 安装 将下载后的安装包上传到/usr/local下…...
3.计算机网络补充
2.5 HTTPS 数字签名:发送端将消息使⽤ hash 函数⽣成摘要,并使⽤私钥加密后得到“数字签名”,并将其附在消息之后。接收端使⽤公钥对“数字签名”解密,确认发送端身份,之后对消息使⽤ hash 函数处理并与接收到的摘要对…...
【云原生】Spring Cloud Alibaba 之 Gateway 服务网关实战开发
目录 一、什么是网关 ⛅网关的实现原理 二、Gateway 与 Zuul 的区别? 三、Gateway 服务网关 快速入门 ⛄需求 ⏳项目搭建 ✅启动测试 四、Gateway 断言工厂 五、Gateway 过滤器 ⛽过滤器工厂 ♨️全局过滤器 六、源码地址 ⛵小结 一、什么是网关 Spri…...
opencv-直方图均衡化
直方图均衡化是一种用于增强图像对比度的图像处理技术。它通过调整图像的灰度级别分布,使得图像中各个灰度级别的像素分布更均匀,从而提高图像的对比度。 在OpenCV中,你可以使用cv2.equalizeHist()函数来进行直方图均衡化。 以下是一个简单…...
npm install安装报错
npm WARN notsup Not compatible with your version of node/npm: v-click-outside-x3.7.1 npm ERR! Error while executing: npm ERR! /usr/bin/git ls-remote -h -t ssh://gitgithub.com/itargaryen/simple-hotkeys.git 解决办法1:(没有解决我的问题…...
Spring Boot创建和使用(重要)
Spring的诞生是为了简化Java程序开发的! Spring Boot的诞生是为了简化Spring程序开发的! Spring Boot就是Spring框架的脚手架,为了快速开发Spring框架而诞生的!! Spring Boot的优点: 快速集成框架&#x…...
python 基于gdal,richdem,pysheds实现 实现洼填、D8流向,汇流累计量计算,河网连接,分水岭及其水文分析与斜坡单元生成
python gdal实现水文分析算法及其斜坡单元生成 实现洼填、D8流向,汇流累计量计算,河网连接,分水岭 # utf-8 import richdem as rdre from River import * from pysheds.grid import Grid import time from time import time,sleep import numpy as np from osgeo import g…...
帝国cms开发一个泛知识类的小程序的历程记录
#帝国cms小程序# 要开发一个泛知识类的小程序,要解决以下几个问题。 1。知识内容的分类。 2。知识内容的内容展示。 3。知识内容的价格设置。 4。用户体系,为简化用户的操作,在用户进行下载的时候,请用户输入手机号ÿ…...
Kafka官方生产者和消费者脚本简单使用
问题 怎样使用Kafka官方生产者和消费者脚本进行消费生产和消费?这里假设已经下载了kafka官方文件,并已经解压. 生产者配置文件 producer_hr.properties bootstrap.servers10.xx.xx.xxx:9092,10.xx.xx.xxx:9092,10.xx.xx.xxx:9092 compression.typenone security.protocolS…...
如何开发干洗店用的小程序
洗护行业现在都开始往线上的方向发展了,越来越多的干洗店都推出了上门取送服务,那么就需要开发一个干洗店专用的小程序去作为用户和商家的桥梁,这样的小程序该如何开发呢? 一、功能设计:根据干洗店的业务需求和小程序的…...
回溯算法详解
目录 什么是回溯? 回溯常用来解决什么问题? 回溯的效率如何? 回溯在面试中的考察频率 如何学好回溯? 回溯通用模板 什么是回溯? 回溯:你处理了之后,再进行”撤销“处理,”撤销…...
边云协同架构设计
文章目录 一. "边云协同"是什么?二. "边云协同"主要包括6种协同2.1 资源协同2.2 数据协同2.3 智能协同2.4 应用管理协同2.5 业务管理协同2.6 服务协同 三. "边云协同"的优势 其它相关推荐: 系统架构之微服务架构 系统架构…...
【c++】——类和对象(下) 万字解答疑惑
作者:chlorine 专栏:c专栏 目录 🚩再谈构造函数 🎓构造函数体赋值 🎓初始化列表 🚩explicit关键字 🚩static成员 🎓概念 面试题:计算创建多少个类对象 🎓特性 【问题】(非)…...
Appium自动化测试:通过appium的inspector功能无法启动app的原因
在打开appium-desktop程序,点击inspector功能,填写app的配置信息,启动服务提示如下: 报错信息: An unknown server-side error occurred while processing the command. Original error: Cannot start the cc.knowyo…...
易点易动设备管理系统:提升企业设备维修效率的工具
在现代企业运营中,设备的正常运行和及时维修至关重要。然而,传统的设备维修管理方法往往效率低下、易出错,给企业带来了不小的困扰。为了解决这一问题,易点易动设备管理系统应运而生。作为一款先进的智能化系统,易点易…...
JVM中判断对象是否需要回收的方法
在堆里面存放着Java 世界中几乎所有的对象实例,垃圾收集器在对堆进行回收前,第一件事情就是要确定这些对象之中哪些还“ 存活 ” 着,哪些已经 “ 死去 ”。 引用计数算法 引用计数法是一种内存管理技术,它是通过对每个对象进行引用…...
【Python】 -- 趣味代码 - 小恐龙游戏
文章目录 文章目录 00 小恐龙游戏程序设计框架代码结构和功能游戏流程总结01 小恐龙游戏程序设计02 百度网盘地址00 小恐龙游戏程序设计框架 这段代码是一个基于 Pygame 的简易跑酷游戏的完整实现,玩家控制一个角色(龙)躲避障碍物(仙人掌和乌鸦)。以下是代码的详细介绍:…...
C++初阶-list的底层
目录 1.std::list实现的所有代码 2.list的简单介绍 2.1实现list的类 2.2_list_iterator的实现 2.2.1_list_iterator实现的原因和好处 2.2.2_list_iterator实现 2.3_list_node的实现 2.3.1. 避免递归的模板依赖 2.3.2. 内存布局一致性 2.3.3. 类型安全的替代方案 2.3.…...
51c自动驾驶~合集58
我自己的原文哦~ https://blog.51cto.com/whaosoft/13967107 #CCA-Attention 全局池化局部保留,CCA-Attention为LLM长文本建模带来突破性进展 琶洲实验室、华南理工大学联合推出关键上下文感知注意力机制(CCA-Attention),…...
day52 ResNet18 CBAM
在深度学习的旅程中,我们不断探索如何提升模型的性能。今天,我将分享我在 ResNet18 模型中插入 CBAM(Convolutional Block Attention Module)模块,并采用分阶段微调策略的实践过程。通过这个过程,我不仅提升…...
多场景 OkHttpClient 管理器 - Android 网络通信解决方案
下面是一个完整的 Android 实现,展示如何创建和管理多个 OkHttpClient 实例,分别用于长连接、普通 HTTP 请求和文件下载场景。 <?xml version"1.0" encoding"utf-8"?> <LinearLayout xmlns:android"http://schemas…...
vscode(仍待补充)
写于2025 6.9 主包将加入vscode这个更权威的圈子 vscode的基本使用 侧边栏 vscode还能连接ssh? debug时使用的launch文件 1.task.json {"tasks": [{"type": "cppbuild","label": "C/C: gcc.exe 生成活动文件"…...
【SQL学习笔记1】增删改查+多表连接全解析(内附SQL免费在线练习工具)
可以使用Sqliteviz这个网站免费编写sql语句,它能够让用户直接在浏览器内练习SQL的语法,不需要安装任何软件。 链接如下: sqliteviz 注意: 在转写SQL语法时,关键字之间有一个特定的顺序,这个顺序会影响到…...
鱼香ros docker配置镜像报错:https://registry-1.docker.io/v2/
使用鱼香ros一件安装docker时的https://registry-1.docker.io/v2/问题 一键安装指令 wget http://fishros.com/install -O fishros && . fishros出现问题:docker pull 失败 网络不同,需要使用镜像源 按照如下步骤操作 sudo vi /etc/docker/dae…...
【RockeMQ】第2节|RocketMQ快速实战以及核⼼概念详解(二)
升级Dledger高可用集群 一、主从架构的不足与Dledger的定位 主从架构缺陷 数据备份依赖Slave节点,但无自动故障转移能力,Master宕机后需人工切换,期间消息可能无法读取。Slave仅存储数据,无法主动升级为Master响应请求ÿ…...
【C++从零实现Json-Rpc框架】第六弹 —— 服务端模块划分
一、项目背景回顾 前五弹完成了Json-Rpc协议解析、请求处理、客户端调用等基础模块搭建。 本弹重点聚焦于服务端的模块划分与架构设计,提升代码结构的可维护性与扩展性。 二、服务端模块设计目标 高内聚低耦合:各模块职责清晰,便于独立开发…...
