MNIST数据集 [LeCun et al., 1998] 是图像分类中广泛使用的数据集之一,但作为基准数据集过于简单。 我们将使用类似但更复杂的Fashion-MNIST数据集 [Xiao et al., 2017]。
%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() #d2l自定义函数:以矢量图svg形式输出
# 通过ToTensor实例将图像数据从PIL类型变换成32位浮点数格式,
# 并除以255使得所有像素的数值均在0到1之间
mnist_train = torchvision.datasets.FashionMNIST(
root = "E:/Coding/Jupyter/data", train = True, transform = transforms.ToTensor(), download=True)
mnist_test = torchvision.datasets.FashionMNIST(
root = "E:/Coding/Jupyter/data", train = False, transform = transforms.ToTensor(), download=True)
def get_fashion_mnist_labels(labels): #@save
"""返回Fashion-MNIST数据集的文本标签"""
text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat',
'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']
return [text_labels[int(i)] for i in labels]
X1, y1 = mnist_train[0] #取第一张图片的数据,X为像素矩阵,y为图像类别
X2, y2 = mnist_train[1]
import matplotlib.pyplot as plt
plt.figure(0)
plt.imshow(X1.numpy().squeeze())#X为[1,28,28]不能直接输出为图像,squeeze()去除第一维1,变为[28,28]
plt.title(get_fashion_mnist_labels([y1,y2])[0])#将图像类别序号转换为文本名称
plt.figure(1)
plt.imshow(X2.numpy().squeeze())
plt.title(get_fashion_mnist_labels([y1,y2])[1])
def show_images(imgs, num_rows, num_cols, titles=None, scale=1.5): #@save
"""绘制图像列表
参数:imgs即数据集中各个图片的像素矩阵,即mnist_train[i][0];
num_rows, num_cols 展示图片时的行列值,如下设置为3行6列
titles 图片的类别; scale各子图的尺寸
"""
figsize = (num_cols * scale, num_rows * scale) #整图的size
fig, axes = plt.subplots(num_rows, num_cols, figsize=figsize) #axes对应划分出来的每一个子图对应的轴空间
axes = axes.flatten() #展开为一个向量
for i, (ax, img) in enumerate(zip(axes, imgs)):
if torch.is_tensor(img):
# 图片张量
ax.imshow(img.numpy())
else:
# PIL图片
ax.imshow(img)
ax.axes.get_xaxis().set_visible(False) #是否显示绘图轴x
ax.axes.get_yaxis().set_visible(False) #轴y
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), 3, 6, titles=get_fashion_mnist_labels(y));
使用内置的数据迭代器data.DataLoader
batch_size = 256
def get_dataloader_workers(): #@save
"""使用4个进程来读取数据"""
return 4
train_iter = data.DataLoader(mnist_train, batch_size, shuffle=True, num_workers=get_dataloader_workers())
def load_data_fashion_mnist(batch_size, resize=None): #@save
"""下载Fashion-MNIST数据集,然后将其加载到内存中"""
trans = [transforms.ToTensor()]
if resize:
trans.insert(0, transforms.Resize(resize))
trans = transforms.Compose(trans)
mnist_train = torchvision.datasets.FashionMNIST(root="E:/Coding/Jupyter/data", train=True, transform=trans, download=True)
mnist_test = torchvision.datasets.FashionMNIST(root="E:/Coding/Jupyter/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()))
train_iter, test_iter = load_data_fashion_mnist(32, resize=64)
for X, y in train_iter:
print(X.shape, X[0].shape, X.dtype, y.shape, y.dtype)
break
fig,ax = plt.subplots(nrows=2, ncols=2)
axes = ax.flatten()
CSDN话题挑战赛第2期
参赛话题:学习笔记