【加载数据--自定义自己的Dataset类】

【加载数据自定义自己的Dataset类】

  • [1 加载数据](#1 加载数据)
  • [2 数据转换](#2 数据转换)
  • [3 自定义Dataset类](#3 自定义Dataset类)
  • [4 划分训练集和测试集](#4 划分训练集和测试集)
  • [5 提取一批次数据并绘制样例图](#5 提取一批次数据并绘制样例图)

假设有四种天气图片数据全部存放与一个文件夹中,如下图所示:

python 复制代码
├─dataset2
│      cloudy1.jpg
│      cloudy10.jpg
│      cloudy100.jpg
│      cloudy101.jpg
│      cloudy102.jpg
│      cloudy103.jpg
│      cloudy104.jpg
│      cloudy105.jpg
......

1 加载数据

python 复制代码
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import torchvision
import glob
from torchvision import transforms
from torch.utils.data import Dataset
from PIL import Image

import glob
img_dir = r'./dataset2/*.jpg'
imgs = glob.glob(img_dir) # 读取所有图片路径
print(imgs[:3]) # 打印前3张图片

species = ['cloudy', 'rain', 'shine', 'sunrise']

species_to_idx = dict((c, i) for i, c in enumerate(species))		# 建立类别和序号字典
print(species_to_idx)

idx_to_species = dict((v, k) for k, v in species_to_idx.items())	# 反转类别和序号
print(idx_to_species)

输出如下:

复制代码
['./dataset2\\cloudy1.jpg',
 './dataset2\\cloudy10.jpg',
 './dataset2\\cloudy100.jpg']
 
 {'cloudy': 0, 'rain': 1, 'shine': 2, 'sunrise': 3}

{0: 'cloudy', 1: 'rain', 2: 'shine', 3: 'sunrise'}

读取路径加载序号作为标签

python 复制代码
labels = []
for img in imgs:
    for i, c in enumerate(species):
        if c in img:
            labels.append(i)

print(labels[:3])

输出如下:

复制代码
[0, 0, 0]

方法1:提前划分训练集和测试集,使用乱序后的index进行划分

python 复制代码
np.random.seed(2022)
index = np.random.permutation(count)
imgs = np.array(imgs)[index]
labels = np.array(labels, dtype=np.int64)[index]

sep = int(count*0.8)
train_imgs = imgs[ :sep]
train_labels = labels[ :sep]
test_imgs = imgs[sep: ]
test_labels = labels[sep: ]

2 数据转换

python 复制代码
transforms = transforms.Compose([
    transforms.Resize((96, 96)),
    transforms.ToTensor(),
    transforms.Normalize(mean=[.5, .5, .5], std=[.5, .5, .5])
])

3 自定义Dataset类

python 复制代码
class WT_dataset(Dataset):
    def __init__(self, imgs_path, lables):
        self.imgs_path = imgs_path
        self.lables = lables

    def __getitem__(self, index):
        img_path = self.imgs_path[index]
        lable = self.lables[index]
        
        pil_img = Image.open(img_path)
        pil_img = pil_img.convert("RGB")
        pil_img = transforms(pil_img)
        return pil_img, lable

    def __len__(self):
        return len(self.imgs_path)

# 加载数据
dataset = WT_dataset(imgs, labels)

4 划分训练集和测试集

python 复制代码
count = len(dataset)
print(count)

# 方法2:划分训练集和测试集
train_count = int(0.8*count)
test_count = count - train_count
train_dataset, test_dataset = data.random_split(dataset, [train_count, test_count])
print(len(train_dataset), len(test_dataset))

# 批量加载数据
BTACH_SIZE = 16
train_dl = torch.utils.data.DataLoader(
                                       train_dataset,
                                       batch_size=BTACH_SIZE,
                                       shuffle=True
)

test_dl = torch.utils.data.DataLoader(
                                       test_dataset,
                                       batch_size=BTACH_SIZE,
)

5 提取一批次数据并绘制样例图

python 复制代码
imgs, labels = next(iter(train_dl))	#提取一批次数据
print(imgs.shape)
im = imgs[0].permute(1, 2, 0)	# 将通道所在列放在后
print(im.shape)


plt.figure(figsize=(12, 8))
for i, (img, label) in enumerate(zip(imgs[:6], labels[:6])):
    img = (img.permute(1, 2, 0).numpy() + 1)/2
    plt.subplot(2, 3, i+1)
    plt.title(idx_to_species.get(label.item()))
    plt.imshow(img)
plt.savefig('pics/example1.jpg', dpi=400)

输出如下:

复制代码
torch.Size([16, 3, 96, 96])

torch.Size([3, 96, 96])

torch.Size([96, 96, 3])
相关推荐
看我干嘛!2 分钟前
python第四次作业
开发语言·python
疯狂的喵3 分钟前
使用Flask快速搭建轻量级Web应用
jvm·数据库·python
smj2302_796826526 分钟前
解决leetcode第3826题.最小分割分数问题
数据结构·python·算法·leetcode
zandy101121 分钟前
AI驱动全球销售商机管理:钉钉DingTalk A1的跨域管理智能解决方案
人工智能·百度·钉钉
福将~白鹿21 分钟前
Qwen3-VL-32B-Instruct vs Qwen2.5-VL-32B-Instruct 能力评分对比
人工智能
paul_chen2129 分钟前
openclaw配置教程(linux+局域网ollama)
人工智能·飞书
铁蛋AI编程实战30 分钟前
ChatWiki 开源 AI 文档助手搭建教程:多格式文档接入,打造专属知识库机器人
java·人工智能·python·开源
Loacnasfhia930 分钟前
【深度学习】【目标检测】YOLO11-C3k2-Faster-EMA模型实现草莓与番茄成熟度及病害识别系统
人工智能·深度学习·目标检测
程序员小远30 分钟前
UI自动化测试用例管理平台搭建
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
Horizon_Ruan32 分钟前
从零开始掌握AI:LLM、RAG到Agent的完整学习路线图
人工智能·学习·ai编程