官网链接
Datasets & DataLoaders — PyTorch Tutorials 2.0.1+cu117 documentation
数据集和数据加载器
处理样本数据的代码可能会变得混乱并且难以维护。理想情况下,我们希望我们的数据集代码与模型训练代码解耦,以获得更好的可读性和模块化。PyTorch提供了两个数据源:torch.utils.data.DataLoader和torch.utils.data.Dataset,它们允许你使用预加载的数据集和你自己的数据集。Dataset存储样本及其相应的标签,DataLoader在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/26421880 [00:00<?, ?it/s]
0%| | 65536/26421880 [00:00<01:12, 363415.33it/s]
1%| | 229376/26421880 [00:00<00:38, 679946.01it/s]
3%|2 | 753664/26421880 [00:00<00:12, 2072129.51it/s]
7%|6 | 1802240/26421880 [00:00<00:06, 3878939.55it/s]
16%|#6 | 4358144/26421880 [00:00<00:02, 9473273.38it/s]
25%|##4 | 6553600/26421880 [00:00<00:01, 10918007.48it/s]
34%|###4 | 9011200/26421880 [00:01<00:01, 14051286.10it/s]
43%|####3 | 11370496/26421880 [00:01<00:01, 14100224.63it/s]
52%|#####2 | 13762560/26421880 [00:01<00:00, 16167133.39it/s]
61%|######1 | 16187392/26421880 [00:01<00:00, 15640376.47it/s]
70%|####### | 18612224/26421880 [00:01<00:00, 17384518.47it/s]
80%|#######9 | 21069824/26421880 [00:01<00:00, 16443689.83it/s]
89%|########8 | 23429120/26421880 [00:01<00:00, 17854523.89it/s]
98%|#########8| 25952256/26421880 [00:01<00:00, 16957283.54it/s]
100%|##########| 26421880/26421880 [00:02<00:00, 13185733.62it/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, 327080.02it/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:12, 361139.75it/s]
5%|5 | 229376/4422102 [00:00<00:06, 678952.39it/s]
19%|#9 | 851968/4422102 [00:00<00:01, 2356375.68it/s]
44%|####3 | 1933312/4422102 [00:00<00:00, 4134961.37it/s]
100%|##########| 4422102/4422102 [00:00<00:00, 6052787.05it/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, 43184553.98it/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()
文章来源地址https://www.toymoban.com/news/detail-501510.html
通过文件创建自定义数据集
自定义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对象时运行一次。我们初始化的目录包含图像、注释文件和两个transforms(下一节将详细介绍)
label .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
__len__
__len__函数返回数据集中的样本数。
示例:
def __len__(self):
return len(self.img_labels)
__getitem__
__getitem__函数使用给定的索引idx,从数据集中加载并返回一个样本。基于索引,它识别图像在磁盘上的位置,使用read_image函数将其转换为张量,从self.img_labels中的CSV数据中检索相应的标签。调用它们的transform函数(如果可用)。并在元组中返回张量图像和相应的标签。
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的多进程来加速数据检索。
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}")
输出
文章来源:https://www.toymoban.com/news/detail-501510.html
Feature batch shape: torch.Size([64, 1, 28, 28])
Labels batch shape: torch.Size([64])
Label: 0
到了这里,关于PyTorch翻译官网教程3-DATASETS & DATALOADERS的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!