import d2l import torch import torchvision import torchvision.transforms as transforms import matplotlib.pyplot as plt import sys sys.path.append("..") # 获取训练集 mnist_train = torchvision.datasets.FashionMNIST(root='~/Datasets/FashionMNIST', train=True, download=True, transform=transforms.ToTensor()) # 获取测试集 mnist_test = torchvision.datasets.FashionMNIST(root='~/Datasets/FashionMNIST', train=True, download=True, transform=transforms.ToTensor()) # len(mnist_train) # 输出训练集的样本数 # mnist_train[0] # 通过下标访问任意一个样本,返回值为两个torch,一个特征tensor和一个标签tensor 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] # labels是一个列表 # 数值标签转文本标签 def show_fashion_mnist(images, labels): d2l.use_svg_display() # 绘制矢量图 _, figs = plt.subplots(1, len(images), figsize=(12, 12)) # 创建子图,一行len(images)列,图片大小12*12 for f, img, lbl in zip(figs, images, labels): # zip函数将他们压缩成由多个元组组成的列表 f.imshow(img.view((28, 28)).numpy()) # 将img转形为28*28大小的张量,然后转换成numpy数组 f.set_title(lbl) # 设置每个子图的标题为标签 f.axes.get_xaxis().set_visible(False) f.axes.get_yaxis().set_visible(False) # 关闭x轴y轴 plt.show() X, y = [], [] # 初始化两个列表 for i in range(10): X.append(mnist_train[i][0]) # 循环向X列表添加图像 y.append(mnist_train[i][1]) # 循环向y列表添加标签 show_fashion_mnist(X, get_fashion_mnist_labels(y)) # 显示图像和列表 batch_size = 256 # 小批量数目 train_iter = torch.utils.data.DataLoader(mnist_train, batch_size=batch_size, shuffle=True, num_workers=0) # num_workers=0,不开启多线程读取。 test_iter = torch.utils.data.DataLoader(mnist_test, batch_size=batch_size, shuffle=False, num_workers=0)