前言
这一节介绍pytorch中提供的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
print(torch.__version__)
print(torchvision.__version__)
二、获取数据集
1.引入库
pytorch版本在2.0之后会出现下面的报错
AttributeError: module ‘torch’ has no attribute ‘_six’
解决地址
link
mnist_train = torchvision.datasets.FashionMNIST(root='~/Datasets/FashionMNIST', train=True, download=True, transform=transforms.ToTensor())
mnist_test = torchvision.datasets.FashionMNIST(root='~/Datasets/FashionMNIST', train=False, download=True, transform=transforms.ToTensor())
下载结果
2.观察下载到的数据
# mnist_train和mnist_test都是torch.utils.data.Dataset子类实例,所以能使用len()和下标访问
print(type(mnist_train))
print(len(mnist_train), len(mnist_test))
feature, label = mnist_train[0]
print(feature.shape, feature.dtype) # Channel x Height X Width
print(label)
# 本函数已保存在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是画布的坐标轴,分成十份
_, figs = plt.subplots(1, len(images), figsize=(10, 10))
for f, img, lbl in zip(figs, images, labels):
f.imshow(img.view((28, 28)).numpy())
f.set_title(lbl)
# 消除每个子画布的坐标
f.axes.get_xaxis().set_visible(False)
f.axes.get_yaxis().set_visible(False)
plt.show()
# 在每个子画布中添加对应的第一个图片并显示
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))
三、读取小批量
# mnist_train是Dataset类数据,因此能使用torch提供的DataLoader读取
batch_size = 256
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))
2.43 sec
总结
这一节了解了对torchvision和matplotlib.pyplot模块的使用,掌握了对Fashion-MNIST数据集下载和读取。