注意
单击 此处 下载完整的示例代码
学习基础知识 || 快速入门 || 张量 || 数据集与数据加载器 || 变换 || 构建模型 || 自动微分 || 优化 || 保存和加载模型
数据集与数据加载器¶
处理数据样本的代码可能很混乱且难以维护;理想情况下,我们希望将数据集代码与模型训练代码分离,以提高可读性和模块化。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
指定特征和标签转换。
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.00/26.4M [00:00<?, ?B/s]
0%| | 65.5k/26.4M [00:00<01:13, 361kB/s]
1%| | 164k/26.4M [00:00<00:56, 466kB/s]
1%| | 262k/26.4M [00:00<00:52, 500kB/s]
1%|1 | 393k/26.4M [00:00<00:44, 586kB/s]
2%|1 | 524k/26.4M [00:00<00:40, 635kB/s]
3%|2 | 688k/26.4M [00:01<00:35, 724kB/s]
3%|3 | 852k/26.4M [00:01<00:32, 782kB/s]
4%|3 | 1.02M/26.4M [00:01<00:30, 820kB/s]
5%|4 | 1.21M/26.4M [00:01<00:27, 901kB/s]
5%|5 | 1.44M/26.4M [00:01<00:24, 1.01MB/s]
6%|6 | 1.67M/26.4M [00:01<00:20, 1.18MB/s]
7%|6 | 1.84M/26.4M [00:02<00:20, 1.18MB/s]
8%|7 | 2.10M/26.4M [00:02<00:19, 1.27MB/s]
9%|9 | 2.39M/26.4M [00:02<00:15, 1.51MB/s]
10%|9 | 2.59M/26.4M [00:02<00:16, 1.48MB/s]
11%|#1 | 2.92M/26.4M [00:02<00:13, 1.75MB/s]
12%|#1 | 3.15M/26.4M [00:02<00:13, 1.72MB/s]
13%|#3 | 3.54M/26.4M [00:02<00:11, 2.07MB/s]
14%|#4 | 3.80M/26.4M [00:03<00:11, 2.01MB/s]
16%|#5 | 4.23M/26.4M [00:03<00:09, 2.35MB/s]
17%|#7 | 4.52M/26.4M [00:03<00:09, 2.29MB/s]
19%|#9 | 5.05M/26.4M [00:03<00:07, 2.76MB/s]
20%|## | 5.37M/26.4M [00:03<00:07, 2.64MB/s]
23%|##2 | 6.00M/26.4M [00:03<00:06, 3.22MB/s]
24%|##4 | 6.39M/26.4M [00:03<00:06, 3.11MB/s]
27%|##6 | 7.08M/26.4M [00:04<00:05, 3.71MB/s]
29%|##8 | 7.54M/26.4M [00:04<00:05, 3.58MB/s]
32%|###1 | 8.32M/26.4M [00:04<00:04, 4.26MB/s]
33%|###3 | 8.85M/26.4M [00:04<00:04, 4.11MB/s]
37%|###7 | 9.80M/26.4M [00:04<00:03, 4.98MB/s]
39%|###9 | 10.4M/26.4M [00:04<00:03, 4.76MB/s]
43%|####3 | 11.5M/26.4M [00:04<00:02, 5.74MB/s]
46%|####6 | 12.2M/26.4M [00:05<00:02, 5.50MB/s]
51%|##### | 13.4M/26.4M [00:05<00:01, 6.62MB/s]
54%|#####3 | 14.2M/26.4M [00:05<00:01, 6.39MB/s]
59%|#####9 | 15.7M/26.4M [00:05<00:01, 7.68MB/s]
63%|######2 | 16.6M/26.4M [00:05<00:01, 7.42MB/s]
69%|######9 | 18.3M/26.4M [00:05<00:00, 8.86MB/s]
73%|#######3 | 19.4M/26.4M [00:05<00:00, 8.58MB/s]
80%|######## | 21.3M/26.4M [00:05<00:00, 10.6MB/s]
85%|########4 | 22.4M/26.4M [00:06<00:00, 10.6MB/s]
90%|########9 | 23.7M/26.4M [00:06<00:00, 10.6MB/s]
94%|#########4| 24.9M/26.4M [00:06<00:00, 10.9MB/s]
100%|##########| 26.4M/26.4M [00:06<00:00, 4.14MB/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.00/29.5k [00:00<?, ?B/s]
100%|##########| 29.5k/29.5k [00:00<00:00, 327kB/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.00/4.42M [00:00<?, ?B/s]
1%|1 | 65.5k/4.42M [00:00<00:12, 359kB/s]
4%|3 | 164k/4.42M [00:00<00:09, 464kB/s]
6%|5 | 262k/4.42M [00:00<00:08, 498kB/s]
9%|8 | 393k/4.42M [00:00<00:06, 583kB/s]
12%|#1 | 524k/4.42M [00:00<00:06, 632kB/s]
15%|#4 | 655k/4.42M [00:01<00:05, 661kB/s]
19%|#8 | 819k/4.42M [00:01<00:04, 737kB/s]
23%|##2 | 1.02M/4.42M [00:01<00:04, 844kB/s]
27%|##7 | 1.21M/4.42M [00:01<00:03, 916kB/s]
32%|###1 | 1.41M/4.42M [00:01<00:03, 966kB/s]
37%|###7 | 1.64M/4.42M [00:02<00:02, 1.05MB/s]
43%|####2 | 1.90M/4.42M [00:02<00:02, 1.17MB/s]
50%|####9 | 2.20M/4.42M [00:02<00:01, 1.30MB/s]
57%|#####7 | 2.52M/4.42M [00:02<00:01, 1.45MB/s]
65%|######5 | 2.88M/4.42M [00:02<00:00, 1.60MB/s]
73%|#######3 | 3.24M/4.42M [00:02<00:00, 1.72MB/s]
83%|########2 | 3.67M/4.42M [00:03<00:00, 1.90MB/s]
94%|#########4| 4.16M/4.42M [00:03<00:00, 2.13MB/s]
100%|##########| 4.42M/4.42M [00:03<00:00, 1.31MB/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.00/5.15k [00:00<?, ?B/s]
100%|##########| 5.15k/5.15k [00:00<00:00, 31.2MB/s]
Extracting data/FashionMNIST/raw/t10k-labels-idx1-ubyte.gz to data/FashionMNIST/raw
迭代和可视化数据集¶
我们可以像列表一样手动索引 Datasets
: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()
为您的文件创建自定义数据集¶
自定义 Dataset 类必须实现三个函数:__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__ 函数在实例化 Dataset 对象时运行一次。我们初始化包含图像的目录、注释文件和两种转换(将在下一节中详细介绍)。
labels.csv 文件的格式如下
tshirt1.jpg, 0
tshirt2.jpg, 0
......
ankleboot999.jpg, 9
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
__getitem__
¶
__getitem__ 函数加载并返回给定索引 idx
处的数据集中的样本。根据索引,它识别图像在磁盘上的位置,使用 read_image
将其转换为张量,从 self.img_labels
中的 csv 数据中检索相应的标签,对它们调用转换函数(如果适用),并将张量图像和相应的标签以元组形式返回。
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
一次获取数据集的特征和标签。在训练模型时,我们通常希望以“小批量”的形式传递样本,在每个 epoch 中重新洗牌数据以减少模型过拟合,并使用 Python 的 multiprocessing
来加速数据检索。
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_features
和 train_labels
(分别包含 batch_size=64
个特征和标签)。因为我们指定了 shuffle=True
,所以在我们遍历完所有批次后,数据会进行洗牌(要对数据加载顺序进行更细粒度的控制,请查看 采样器)。
# 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}")
Feature batch shape: torch.Size([64, 1, 28, 28])
Labels batch shape: torch.Size([64])
Label: 5