2.3 DataSet和DataLoader

Dataset 和 DataLoader

用于处理数据样本的代码可能会变得凌乱且难以维护;理想情况下,我们希望数据集代码与模型训练代码解耦,以获得更好的可读性和模块化。PyTorch提供的torch.utils.data.DataLoader torch.utils.data.Dataset允许你使用预下载的数据集或自己制作的数据。Dataset用于存储样本及其相应的标签,而DataLoader能为数据集提供一个迭代器,以便于访问样本。

PyTorch域库提供了许多预加载的数据集(如FashionMNIST),且都是torch.utils.data.Dataset的子类。这些数据集子类可用于对模型进行原型设计和基准测试。比如图像数据集、文本数据集和音频数据集。

加载数据集

以torchvision加载Fashion MNIST数据集为例。Fashion MNIST是Zalando文章里的图像数据集,包括60000个训练样本和10000个测试样本。每个示例包括一个28×28灰度图像(特征图)和10个类别之一的标签。

我们使用以下参数加载Fashion MNIST数据集:

  • root是要存储训练/测试数据的路径
  • train指定数据集为训练集或测试集,
  • download=True表示如果在root无法获取数据集,则从网上下载。
  • transformtarget_transform分别指定特征和标签数据类型变换。
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()
)
点击查看输出
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%|          | 32768/26421880 [00:00<01:28, 298418.99it/s]
  0%|          | 65536/26421880 [00:00<01:28, 297447.18it/s]
  0%|          | 131072/26421880 [00:00<01:00, 432659.27it/s]
  1%|          | 229376/26421880 [00:00<00:42, 613822.88it/s]
  2%|1         | 491520/26421880 [00:00<00:20, 1248151.07it/s]
  4%|3         | 950272/26421880 [00:00<00:11, 2235164.64it/s]
  7%|7         | 1933312/26421880 [00:00<00:05, 4410751.56it/s]
 15%|#4        | 3833856/26421880 [00:00<00:02, 8482675.38it/s]
 26%|##6       | 6946816/26421880 [00:00<00:01, 14638531.48it/s]
 38%|###8      | 10092544/26421880 [00:01<00:00, 18857562.51it/s]
 50%|####9     | 13205504/26421880 [00:01<00:00, 21738321.85it/s]
 62%|######1   | 16318464/26421880 [00:01<00:00, 23683108.47it/s]
 73%|#######3  | 19398656/26421880 [00:01<00:00, 24943785.13it/s]
 85%|########5 | 22478848/26421880 [00:01<00:00, 25818859.89it/s]
 97%|#########6| 25591808/26421880 [00:01<00:00, 26519866.60it/s]
100%|##########| 26421880/26421880 [00:01<00:00, 15875212.40it/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, 270949.99it/s]
100%|##########| 29515/29515 [00:00<00:00, 269555.29it/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%|          | 32768/4422102 [00:00<00:14, 298407.97it/s]
  1%|1         | 65536/4422102 [00:00<00:14, 297769.82it/s]
  3%|2         | 131072/4422102 [00:00<00:09, 433162.72it/s]
  5%|5         | 229376/4422102 [00:00<00:06, 614009.14it/s]
 11%|#1        | 491520/4422102 [00:00<00:03, 1248619.50it/s]
 21%|##1       | 950272/4422102 [00:00<00:01, 2239414.32it/s]
 44%|####3     | 1933312/4422102 [00:00<00:00, 4419930.79it/s]
 87%|########6 | 3833856/4422102 [00:00<00:00, 8498340.50it/s]
100%|##########| 4422102/4422102 [00:00<00:00, 5002629.78it/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, 28485853.55it/s]
Extracting data/FashionMNIST/raw/t10k-labels-idx1-ubyte.gz to data/FashionMNIST/raw

迭代和可视化数据集

我们可以像列表一样手动索引“数据集”,形如:training_data[index]
我们使用matplotlib来可视化训练数据中的一些样本。

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()

输出的图像样本如下

自定义数据集

自定义数据集类必须实现三个函数:__init____len____getitem__
看看这个实现;FashionMNIST图像被存储在目录img_dir中,它们的标签分别存储在CSV文件annotations_file中。
在接下来的部分中,我们将对这些函数中的每一个进行分解。

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__函数在实例化数据集对象时运行一次,用于初始化包含图像、注释文件和这两个转换的目录(在下一节中详细介绍)。
labels.csv文件看起来像:

tshirt1.jpg, 0
tshirt2.jpg, 0
......
ankleboot999.jpg, 9

__len__

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

__getitem___

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

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

Dataset检索数据集的特征,并一次标记一个样本。在训练模型时,我们通常希望在minibatches(迷你批次)中传递样本,在每个时期重新排列数据以减少模型过拟合,并使用Python的多线程来加快数据检索。DataLoader是一个可迭代程序,它在一个简单的API中为我们抽象了这种复杂性。

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_featurestrain_labels(分别包含batch_size=64个特征和标签)。
因为我们指定了shuffle=True,所以在我们迭代所有批次之后,数据会被打乱。

显示图像和标签:

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}")

返回目录

posted @ 2023-04-10 00:25  周XX  阅读(81)  评论(0编辑  收藏  举报