pytorch导入数据集

1、概念:

Dataset:一种数据结构,存储数据及其标签

Dataloader:一种工具,可以将Dataset里的数据分批、打乱、批量加载并进行迭代等

(方便模型训练和验证)

Dataset就像一个大书架,存放着带有标签的数据书籍,并且这些书有编号(0,1,2...);

而Dataloader就像一个图书管理员,负责从书架上按需取出书籍并分批提供给读者。

2、Dataset的组织形式

train:训练集 val:验证集

一种方式是label作为数据文件夹的名字,

另一种方式是label和数据本身分开成两个文件夹(label文件夹里装的是和每个数据对应的.txt)

3、处理图像:PIL(Python Imaging Library).Image

|--------------------------------------|--------------------------------------|
| pip install Pillow | 安装PIL |
| from PIL import Image | 引入Image类(代表图像对象, 可以通过创建Image实例来操作图像) |
| img=Image.open('图像路径') 打开图像 | img.show() 显示图像 |
| print(img.size) 输出(宽度,高度) | print(img.format) 输出图像格式(JPEG、PNG等) |
| resized_img=img.resize((宽度,高度)) 调整大小 | |
| resized_img=img.save('新路径') 保存为新文件 | |

4、处理目录和文件:os

|---------------------------------------------|--------------------------------------|
| import os | |
| cur_dir=os.getcwd() | 获取当前工作目录 |
| files=os.listdir(cur_dir) | 列举当前目录下的所有子目录(文件和文件夹) |
| os.makedirs('new_folder') | 创建新文件夹(如果不存在) |
| os.remove('file.txt') | 删除文件(os.rmdir('empty_folder')删除空文件夹) |
| os.path.exists('some_path') | 检查路径是否存在 |
| file_path=os.path.join('folder','file.txt') | 拼接路径 |
| abs_path=os.path.abspath('file.txt) | 获取文件的绝对路径 |

5、代码

python 复制代码
from torch.utils.data import Dataset #从torch的常用工具箱utils中拿data工具,然后引入Dataset类
from PIL import Image #处理图片要用到
import os #访问目录、获取图片的地址要用到

class MyData(Dataset): #让MyData类继承Dataset类
    def __init__(self,root_dir,label_dir): #数据集的初始化:要用到根目录和标签目录(这里把label作为数据文件夹的名字了)
        self.root_dir=root_dir
        self.label_dir=label_dir
        self.path=os.path.join(self.root_dir,self.label_dir) #根目录+标签目录=数据集的路径
        self.img_dir_list=os.listdir(self.path) #列举数据集目录下的每个数据(文件)

    def __getitem__(self,idx): #获取索引对应的数据
        img_dir=self.img_dir_list[idx] #得到索引对应的数据文件
        img_path=os.path.join(self.root_dir,self.label_dir,img_dir) #数据集路径+数据文件=数据文件路径
        img=Image.open(img_path)
        label=self.label_dir
        return img,label

    def __len__(self):
        return len(self.img_dir_list) #数据长度=数据集目录下的子文件数量

root_dir=r"dataset/hymenoptera_data/train"
ants_label_dir="ants"
ants_dataset=MyData(root_dir,ants_label_dir)
bees_label_dir="bees"
bees_dataset=MyData(root_dir,bees_label_dir)

train_dataset=ants_dataset+bees_dataset
相关推荐
lovingsoft几秒前
vscode 这几个文件夹是做什么用的。
人工智能
进击的阿三姐2 分钟前
AI工作流:用 Claude + Obsidian 打造全自动技术笔记系统
人工智能·ai
早睡早起好好code2 分钟前
InternNav 论文回看
笔记·python·深度学习·学习·算法
kcuwu.4 分钟前
Python文件操作零基础及进阶
android·服务器·python
傻啦嘿哟4 分钟前
使用 Python 实现 Word 文档文本格式化全解析
开发语言·python·word
Elastic 中国社区官方博客4 分钟前
使用 Elasticsearch Inference API 结合 Hugging Face 模型
大数据·人工智能·elasticsearch·搜索引擎·ai·全文检索
九硕智慧建筑一体化厂家4 分钟前
能碳 IBMS 集成平台:打破数据孤岛,实现建筑全维度智能管控
人工智能
2501_921649495 分钟前
外汇实时汇率 API | 24 小时 架构设计与实战指南
大数据·python·websocket·金融·restful
badhope6 分钟前
Matplotlib实战30例:全类型图表代码库
人工智能·python·plotly·github·matplotlib