MNIST数据集是图像分类中广泛使用的数据集之一,但作为基准数据集过于简单,我们将使用类似但更复杂的Fashion-MNIST数据集。
3.5 图像分类数据集
%matplotlib inline
import torch
import torchvision
from torch.utils import data
from torchvision import transforms
from d2l import torch as d2l
d2l.use_svg_display()
3.5.1 读取数据集
-通过框架中的内置函数将Fashion-MNIST数据集下载并读取到内存中
trans = transforms.ToTensor()
mnist_train = torchvision.datasets.FashionMNIST(root = "../data", train = True, transform = trans, download = True)
mnist_test = torchvision.datasets.FashionMNIST(root = "../data", train = False, transforms = trans, download = True)
Fashion-MNIST由10个类别的图像组成,每个类别由训练数据集的6000张图像和测试数据集中的1000张图像组成。
len(mnist_train), len(mnist_test)
每个输入图像的高度和宽度均为28像素,数据集由灰度图像组成,其通道数为1。
mnist_train[0][0].shape
Fashion-MNIST中包含10个类别,以下函数用于在数字标签索引及其文本名称之间进行转换。
def get_fashion_mnist_labels(labels):
text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']
return [text_labels[int(i)] for i in labels]
定义可视化样本函数
def show_images(imgs, num_rows, num_cols, titles = None, scale = 1.5):
figsize = (num_cols * scale, num_rows * scale)
_, axes = d2l.plt.subplots(num_rows, num_cols, figsize = figsize)
axes = axes.flatten()
for i, (ax, img) in enumerate(zip(axes, imgs)):
if torch.is_tensor(img):
ax.imshow(img.numpy())
else:
ax.imshow(img)
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
if titles:
ax.set_title(titles[i])
return axes
可视化训练数据集中的前几个样本的图像及其标签
X, y = next(iter(data.DataLoader(mnist_train, batch_size=18)))
show_images(X.reshape(18, 28, 28), 2, 9, titles=get_fashion_mnist_labels(y));
3.5.2 读取小批量
使用内置的数据迭代器读取一小批量数据。
batch_size = 256
def get_dataloader_workers():
return 4
train_iter = data.DataLoader(mnist_train, batch_size, shuffle=True, num_workers=get_dataloader_workers())
看一下读取训练数据所需的时间
timer = d2l.Timer()
for X, y in train_iter:
continue
f'{timer.stop():.2f} sec'
3.5.3 整合所有组件
定义load_data_fashion_mnist函数,用于获取和读取Fashion-MNIST数据集,函数返回训练集和验证集的数据迭代器。
def load_data_fashion_mnist(batch_size, resize = None):
trans = [transforms.ToTensor()]
if resize:
trans.insert(0, transforms.Resize(resize))
trans = transforms.Compose(trans)
mnist_train = torchvision.datasets.FashionMNIST(root = "../data", train = True, transform = trans, download = True)
mnist_test = torchvision.datasets.FashionMNIST(root = "../data", train = False, transform = trans, download = True)
return (data.DataLoader(mnist_train, batch_size, shuffle = True, num_workers = get_dataloader_workers()), data.DataLoader(mnist_test, batch_size, shuffle = False, num_workers = get_dataloader_workers()))
通过指定resize参数来测试load_data_fashion_mnist函数的图像大小调整功能。
train_iter, test_iter = load_data_fashion_mnist(32, resize=64)
for X, y in train_iter:
print(X.shape, X.dtype, y.shape, y.dtype)
break