pytorch升级打怪(三)

数据集合数据加载器

简介

处理数据样本的代码可能会变得混乱且难以维护;理想情况下,我们希望我们的数据集代码与模型训练代码解耦,以提高可读性和模块化。PyTorch提供了两个数据原语:torch.utils.data.DataLoader和torch.utils.data.Dataset,允许您使用预加载的数据集以及您自己的数据。Dataset存储样本及其相应的标签,DataLoader在Dataset周围包装一个可以可以方便地访问样本。

PyTorch域库提供一些预加载的数据集(如FashionMNIST),该子类为torch.utils.data.Dataset,并实现特定于特定数据的功能。它们可用于原型和基准测试您的模型。您可以在这里找到它们:图像数据集文本数据集音频数据集

加载数据集

以下是如何从TorchVision加载Fashion-MNIST数据集的示例。Fashion-MNIST是Zalando文章图像的数据集,包括60,000个训练示例和10,000个测试示例。每个示例都包括一个28×28的灰度图像和来自10个班级之一的相关标签。

我们用以下参数加载FashionMNIST数据集:

  • root是存储火车/测试数据的路径,
  • train指定训练或测试数据集,
  • download=True如果root上没有数据,则从互联网上下载数据。
  • transform和target_transform指定功能和标签转换
python 复制代码
import torch
from torch.utils.data import Dataset
from torchvision import datasets
from torchvision.transforms import ToTensor
import matplotlib.pyplot as plt


training_data = datasets.FashionMNIST(
    root="data",
    train=True,
    download=True,
    transform=ToTensor()
)

test_data = datasets.FashionMNIST(
    root="data",
    train=False,
    download=True,
    transform=ToTensor()
)
shell 复制代码
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz to data/FashionMNIST/raw/train-images-idx3-ubyte.gz

  0%|          | 0/26421880 [00:00<?, ?it/s]
  0%|          | 65536/26421880 [00:00<01:12, 363720.69it/s]
  1%|          | 229376/26421880 [00:00<00:38, 682917.83it/s]
  3%|3         | 917504/26421880 [00:00<00:12, 2109774.93it/s]
 12%|#2        | 3211264/26421880 [00:00<00:03, 6286038.17it/s]
 28%|##8       | 7438336/26421880 [00:00<00:01, 14838321.45it/s]
 41%|####      | 10747904/26421880 [00:00<00:00, 16477772.21it/s]
 57%|#####7    | 15138816/26421880 [00:01<00:00, 22904288.96it/s]
 71%|#######   | 18644992/26421880 [00:01<00:00, 21979092.87it/s]
 92%|#########2| 24346624/26421880 [00:01<00:00, 30077676.52it/s]
100%|##########| 26421880/26421880 [00:01<00:00, 18141478.99it/s]
Extracting data/FashionMNIST/raw/train-images-idx3-ubyte.gz to data/FashionMNIST/raw

Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz to data/FashionMNIST/raw/train-labels-idx1-ubyte.gz

  0%|          | 0/29515 [00:00<?, ?it/s]
100%|##########| 29515/29515 [00:00<00:00, 327742.46it/s]
Extracting data/FashionMNIST/raw/train-labels-idx1-ubyte.gz to data/FashionMNIST/raw

Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz to data/FashionMNIST/raw/t10k-images-idx3-ubyte.gz

  0%|          | 0/4422102 [00:00<?, ?it/s]
  1%|1         | 65536/4422102 [00:00<00:11, 363330.31it/s]
  5%|5         | 229376/4422102 [00:00<00:06, 684189.84it/s]
 21%|##1       | 950272/4422102 [00:00<00:01, 2195763.19it/s]
 87%|########6 | 3833856/4422102 [00:00<00:00, 7634326.84it/s]
100%|##########| 4422102/4422102 [00:00<00:00, 6105857.14it/s]
Extracting data/FashionMNIST/raw/t10k-images-idx3-ubyte.gz to data/FashionMNIST/raw

Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz
Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz to data/FashionMNIST/raw/t10k-labels-idx1-ubyte.gz

  0%|          | 0/5148 [00:00<?, ?it/s]
100%|##########| 5148/5148 [00:00<00:00, 37228063.78it/s]
Extracting data/FashionMNIST/raw/t10k-labels-idx1-ubyte.gz to data/FashionMNIST/raw

迭代和可视化数据集

我们可以像列表一样手动索引Datasets:training_data[index]。我们使用matplotlib在训练数据中可视化一些样本。

python 复制代码
labels_map = {
    0: "T-Shirt",
    1: "Trouser",
    2: "Pullover",
    3: "Dress",
    4: "Coat",
    5: "Sandal",
    6: "Shirt",
    7: "Sneaker",
    8: "Bag",
    9: "Ankle Boot",
}
figure = plt.figure(figsize=(8, 8))
cols, rows = 3, 3
for i in range(1, cols * rows + 1):
    sample_idx = torch.randint(len(training_data), size=(1,)).item()
    img, label = training_data[sample_idx]
    figure.add_subplot(rows, cols, i)
    plt.title(labels_map[label])
    plt.axis("off")
    plt.imshow(img.squeeze(), cmap="gray")
plt.show()

为您的文件创建自定义数据集

自定义数据集类必须实现三个函数:

python 复制代码
__init__、__len__和__getitem__

。看看这个实现;FashionMNIST图像存储在目录img_dir中,其标签单独存储在CSV文件annotations_file。

在接下来的章节中,我们将分解每个函数中发生的事情。

python 复制代码
import os
import pandas as pd
from torchvision.io import read_image

class CustomImageDataset(Dataset):
    def __init__(self, annotations_file, img_dir, transform=None, target_transform=None):
        self.img_labels = pd.read_csv(annotations_file)
        self.img_dir = img_dir
        self.transform = transform
        self.target_transform = target_transform

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

    def __getitem__(self, idx):
        img_path = os.path.join(self.img_dir, self.img_labels.iloc[idx, 0])
        image = read_image(img_path)
        label = self.img_labels.iloc[idx, 1]
        if self.transform:
            image = self.transform(image)
        if self.target_transform:
            label = self.target_transform(label)
        return image, label

__init__

实例化数据集对象时,__init__函数运行一次。我们初始化包含图像、注释文件和两个转换的目录(下一节将更详细地介绍)。

python 复制代码
def __init__(self, annotations_file, img_dir, transform=None, target_transform=None):
    self.img_labels = pd.read_csv(annotations_file)
    self.img_dir = img_dir
    self.transform = transform
    self.target_transform = target_transform

__len__

__len__函数返回我们数据集中的样本数。

python 复制代码
def __len__(self):
    return len(self.img_labels)

__getitem__

__getitem__函数加载并返回给定索引idx的数据集的样本。基于索引,它识别图像在磁盘上的位置,使用read_image将其转换为张量,从self.img_labels中的csv数据中检索相应的标签,调用其上的转换函数(如果适用),并在元组中返回张量图像和相应标签。

python 复制代码
def __getitem__(self, idx):
    img_path = os.path.join(self.img_dir, self.img_labels.iloc[idx, 0])
    image = read_image(img_path)
    label = self.img_labels.iloc[idx, 1]
    if self.transform:
        image = self.transform(image)
    if self.target_transform:
        label = self.target_transform(label)
    return image, label

准备您的数据以使用DataLoaders进行训练

Dataset检索我们数据集的功能,并一次标记一个样本。在训练模型时,我们通常希望以"迷你批次"传递样本,在每个时代重新洗牌数据以减少模型过拟合,并使用Pythonmultiprocessing来加快数据检索速度。

DataLoader是一个可以在一个简单的API中为我们抽象这种复杂性的可以进行的。

python 复制代码
from torch.utils.data import DataLoader

train_dataloader = DataLoader(training_data, batch_size=64, shuffle=True)
test_dataloader = DataLoader(test_data, batch_size=64, shuffle=True)

通过DataLoader进行遍载

我们已经将该数据集加载到DataLoader,可以根据需要迭代数据集。下面的每个迭代都会返回一批train_features和train_labels(分别包含batch_size=64特征和标签)。因为我们指定了shuffle=True,在我们遍复所有批次后,数据被洗牌(为了更精细地控制数据加载顺序,请查看采样器)。

python 复制代码
# Display image and label.
train_features, train_labels = next(iter(train_dataloader))
print(f"Feature batch shape: {train_features.size()}")
print(f"Labels batch shape: {train_labels.size()}")
img = train_features[0].squeeze()
label = train_labels[0]
plt.imshow(img, cmap="gray")
plt.show()
print(f"Label: {label}")
shell 复制代码
Feature batch shape: torch.Size([64, 1, 28, 28])
Labels batch shape: torch.Size([64])
Label: 5
相关推荐
管二狗赶快去工作!1 分钟前
体系结构论文(五十四):Reliability-Aware Runahead 【22‘ HPCA】
人工智能·神经网络·dnn·体系结构·实时系统
Envyᥫᩣ8 分钟前
Python中的自然语言处理:从基础到高级
python·自然语言处理·easyui
哪 吒9 分钟前
华为OD机试 - 几何平均值最大子数(Python/JS/C/C++ 2024 E卷 200分)
javascript·python·华为od
AI绘画君10 分钟前
Stable Diffusion绘画 | AI 图片智能扩充,超越PS扩图的AI扩图功能(附安装包)
人工智能·ai作画·stable diffusion·aigc·ai绘画·ai扩图
AAI机器之心12 分钟前
LLM大模型:开源RAG框架汇总
人工智能·chatgpt·开源·大模型·llm·大语言模型·rag
我是陈泽12 分钟前
一行 Python 代码能实现什么丧心病狂的功能?圣诞树源代码
开发语言·python·程序员·编程·python教程·python学习·python教学
hakesashou12 分钟前
python全栈开发是什么?
python
创作小达人31 分钟前
家政服务|基于springBoot的家政服务平台设计与实现(附项目源码+论文+数据库)
开发语言·python
Evand J33 分钟前
物联网智能设备:未来生活的变革者
人工智能·物联网·智能手机·智能家居·智能手表
ZPC821041 分钟前
Python使用matplotlib绘制图形大全(曲线图、条形图、饼图等)
开发语言·python·matplotlib