一般情况来说,在处理数据样本的代码可能会变得很混乱,难以管理,需要把数据代码和训练代码进行分离,让代码获得更好的可读性和模块化。
在 PyTorch 中,提供了两个数据处理单元,torch.utils.data.DataLoader
和 torch.utils.data.Datasets
帮助我们处理自己的数据。
Dataset
存储样本以及其对应的标签,DataLoader
封装了一个围绕在 Dataset
周围的迭代器,以便很容易的访问样本数据。
在这部分主要通过 torchvision.datasets
的子类创建数据集,比如 Fashion-MNIST,Fashion-MNIST 是一个由 Zalando 的文章图像组成的数据集,包括 60000 个训练示例和 10000 个测试示例。每个示例包含一个 28x28 灰度图像和一个标签(10分类)。
加载 Fashion-MNIST Dataset 需要设置如下参数:
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()
)
Out:
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
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.gzExtracting 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
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.gzExtracting data/FashionMNIST/raw/t10k-labels-idx1-ubyte.gz to data/FashionMNIST/raw
接下来使用 matplotlib
查看下 Fashion-MNIST 的数据内容。
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):
# torch的item方法请参考Tensor模块
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")
Out:
创建自定义数据集,需要继承 Dataset
类,并且这个类 必须 需要实现三个函数:__init__
, __len__
, __getitem__
。
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):
'''
annotations_file: image labels
img_dir: image direction
'''
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
初始化函数,创建对象时运行一次,包含图像文件,图像标签目录。
labels.csv 文件内容如下格式:
tshirt1.jpg, 0
tshirt2.jpg, 0
......
ankleboot999.jpg, 9
返回自定义数据集中的样本数量。
这个函数从给定索引 idx 的数据集中加载并返回一个示例。利用 idx 找到对应图片的索引,然后通过 read_image 读取整个图片和标签,最后判断是否需要 transform 和 target_transform 进行相应转换,最后返回 image 和 label。
Dataset每次检索数据的特征并标记一个样本,当训练模型时,每次采取小批量(minibatches)的样本进行训练,这样可以减少模型的过拟合,并且通过 Python 的多处理来加快检索速度。
DataLoader 是一个抽象复杂功能为简单 API 的迭代器。
from torch.utils.data import DataLoader
# shuffle表示打乱数据顺序
train_dataloader = DataLoader(training_data, batch_size=64, shuffle=True)
test_dataloader = DataLoader(test_data, batch_size=64, shuffle=True)
将数据加载到 DataLoader 后,就可以迭代该数据集。每次迭代返回 64 (batch_size)个 train_features 和 train_lables。
train_features, train_labels = next(iter(train_dataloader))
print(f"Feature batch shape: {train_features.size()}")
print(f"Labels batch shape: {train_labels.size()}")
# squeeze就是去除维度为1的维度
img = train_features[0].squeeze()
label = train_labels[0]
plt.imshow(img, cmap="gray")
plt.show()
print(f"label: {label}")
Out:
Feature batch shape: torch.Size([64, 1, 28, 28])
Labels batch shape: torch.Size([64])
label: 9
TORCH.UTILS.DATA