import torch
import torchvision
from torch.utils import data
from torchvision import transforms
from d2l import torch as d2l
from matplotlib import pyplot as plt
trans = transforms.ToTensor() #用来将图像从LIP类型转换为tensor类型,且将像素值除以255,归一化为[0,1]
#下载mnist训练集到data文件夹中
mnist_train = torchvision.datasets.FashionMNIST(root="./data", train=True, transform=trans, download=True)
#下载mnist测试集到data文件夹中
mnist_test = torchvision.datasets.FashionMNIST(root="./data", train=False, transform=trans, download=True)
#(层,行,列)
print(mnist_train[0][0].shape)
#获取一个批量的数字标签所对应的文本标签
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:
# PIL图片
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)))
#(批量,层,行,列)
print(X.shape)
#显示一个批量的训练集图像以及其所对应的标签
show_images(X.reshape(18, 28, 28), 2, 9, titles=get_fashion_mnist_labels(y));
#保存图像
plt.savefig('OutPut.png')