本节展示如何获取Fashion-MNIST数据集以及将图片展示出来
参考3.5 图像分类数据集(Fashion-MNIST)
代码如下
# -*- coding: utf-8 -*-
"""
Fashion-MNIST
"""
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import time
import sys
sys.path.append("..") # 为了导入上层目录的d2lzh_pytorch
import d2lzh_pytorch as d2l
#参数transform = transforms.ToTensor()使所有数据转换为Tensor,如果不进行转换则返回的是PIL图片
# transforms.ToTensor()将尺寸为 (H x W x C) 且数据位于[0, 255]的PIL图片
# 或者数据类型为np.uint8的NumPy数组转换为尺寸为(C x H x W),
# 第一维是通道数,因为数据集中是灰度图像,所以通道数为1。后面两维分别是图像的高和宽
# 且数据类型为torch.float32且位于[0.0, 1.0]的Tensor
mnist_train = torchvision.datasets.FashionMNIST(root='~/Datasets/FashionMNIST', train=True, download=False, transform=transforms.ToTensor())
mnist_test = torchvision.datasets.FashionMNIST(root='~/Datasets/FashionMNIST', train=False, download=False, transform=transforms.ToTensor())
#用len()来获取该数据集的大小
print(type(mnist_train))
print(len(mnist_train), len(mnist_test))
#还可以用下标来获取具体的一个样本。
feature, label = mnist_train[0]
print(feature.shape, label) # Channel x Height x Width
# 本函数已保存在d2lzh包中方便以后使用,或者直接用
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]
# 本函数已保存在d2lzh包中方便以后使用
def show_fashion_mnist(images, labels):
# d2l.use_svg_display()
# 这里的_表示我们忽略(不使用)的变量
_, figs = plt.subplots(1, len(images), figsize=(12, 12)) #在一张图上显示多张图片
for f, img, lbl in zip(figs, images, labels):
f.imshow(img.view((28, 28)).numpy()) #转成 28*28像素
f.set_title(lbl)
f.axes.get_xaxis().set_visible(False) #不显示XY轴
f.axes.get_yaxis().set_visible(False)
plt.show()
#训练数据集中前10个样本的图像内容和文本标签
X, y = [], []
for i in range(10):
X.append(mnist_train[i][0])
y.append(mnist_train[i][1])
show_fashion_mnist(X, get_fashion_mnist_labels(y))
#读取小批量
batch_size = 256
if sys.platform.startswith('win'):
num_workers = 0 # 0表示不用额外的进程来加速读取数据
else:
num_workers = 4 #允许使用多进程来加速数据读取
train_iter = torch.utils.data.DataLoader(mnist_train, batch_size=batch_size, shuffle=True, num_workers=num_workers)
test_iter = torch.utils.data.DataLoader(mnist_test, batch_size=batch_size, shuffle=False, num_workers=num_workers)
start = time.time()
for X, y in train_iter:
continue
print('%.2f sec' % (time.time() - start))