def text_labels(self, indices):
"""Return text labels."""
labels = ['T-shirt', 'trouser', 'pullover', 'dress', 'coat',
'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']
return [labels[int(i)] for i in indices]Dive into Deep Learning · §3.2
图像分类数据集:Fashion-MNIST 与数据流水线
Fashion-MNIST 基准 · DataModule API · 张量布局 · 小批量加载器 · 流水线吞吐量 · 可视化调试
基准选择
理想的开发基准既要能区分弱模型与强架构,又要能装入内存并在几秒内完成训练:
类别体系
Fashion-MNIST 的 q = 10 个服饰类别(从 0 开始编号 0, \ldots, 9)各有 6{,}000 张训练图和 1{,}000 张测试图:
0, 2, 4, 6)、3 种鞋类(5, 7, 9)和 3 种辨识度高的类别(1 裤子、3 连衣裙、8 包)。面向对象数据流水线
FashionMNIST 继承 d2l.DataModule,通过 resize=(h, w) 调整分辨率而无需改动训练代码:
class FashionMNIST(d2l.DataModule):
"""The Fashion-MNIST dataset."""
def __init__(self, batch_size=64, resize=(28, 28)):
super().__init__()
self.save_hyperparameters()
trans = transforms.Compose([transforms.Resize(resize),
transforms.ToTensor()])
self.train = torchvision.datasets.FashionMNIST(
root=self.root, train=True, transform=trans, download=True)
self.val = torchvision.datasets.FashionMNIST(
root=self.root, train=False, transform=trans, download=True)面向对象数据流水线
uint8,深色背景 = 0)在离开加载器前缩放到 [0, 1] 的 float32。DataModule 中,所有加载 Fashion-MNIST 的模型都获得一致的 [0, 1] 输入。数据集划分与陷阱
打乱与分批
get_dataloader(train) 方法将数据集封装为可迭代的小批量加载器:
def get_dataloader(self, train):
data = self.train if train else self.val
# Serve the 8-bit image tensor directly, not one PIL image at a time
X = data.data.unsqueeze(1) # Add the channel axis
return torch.utils.data.DataLoader(
torch.utils.data.TensorDataset(X, data.targets), self.batch_size,
shuffle=train, collate_fn=self.batchify)
def batchify(self, examples):
"""Stack examples into a minibatch, scale to [0, 1], resize if asked."""
X, y = torch.utils.data.default_collate(examples)
X = X.float() / 255
if X.shape[2:] != tuple(self.resize):
X = F.interpolate(X, size=self.resize, mode='bilinear', antialias=True)
return X, y打乱与分批
shuffle=train):训练时每轮重新打乱 60{,}000 个索引,验证时按确定顺序遍历。batch_size=64 时,60{,}000 = 937 \times 64 + 32,每轮共 938 批,不丢弃任何样本。框架张量约定
四维图像张量与一维标签向量
堆叠 n = 64 张图像会为 X 增添前置批量轴,并配以一维整数向量 y:
torch.Size([64, 1, 28, 28]) torch.float32 torch.Size([64]) torch.int64
NCHW 还是 NHWC,将 X 重塑为 (-1, 784) 均得 \mathbf{X} \in \mathbb{R}^{n \times 784}。系统瓶颈分析
接入神经网络之前,先单独计时完整遍历一次 train_dataloader():
'0.42 sec'
生产者–消费者重叠
当后台 CPU 工作进程在 GPU 计算第 b 批的同时预取第 b + 1 批时,每轮挂钟时间满足:
T_{\text{epoch}} \;\ge\; \max\!\big(T_{\text{load}},\; T_{\text{compute}}\big)
T_load >> T_compute),导致 GPU 饥饿。num_workers=0 会串行阻塞;一旦 T_{\text{load}} < T_{\text{compute}},增加进程不再提速。防御性数据检查
静默数据缺陷(标签错位、空间轴转置或通道错乱)不会报语法错误,务必先画出带标签的图像网格:
def visualize(self, batch, nrows=1, ncols=8, labels=None):
"""Show the images of a batch in grayscale, titled by their labels."""
X, y = batch
if labels is None:
labels = self.text_labels(y)
X = d2l.reshape(X, (-1, *self.resize)) # Drop the channel axis
d2l.show_images(X, nrows, ncols, titles=labels, cmap='gray')X 重塑为 (-1, *self.resize),即可从 (n, 1, h, w) 或 (n, h, w, 1) 中移除长度为 1 的通道轴。视觉误差预览
按每列一类展示各类别前三张验证图像,一眼就能看出线性模板分类器的难点所在:
轮廓分组:裤子(1)和包(8)轮廓鲜明;凉鞋(5)、运动鞋(7)和短靴(9)形成鞋类簇;四种上装(T 恤 0、套衫 2、外套 4、衬衫 6)在 28 \times 28 分辨率下有着几乎相同的方正轮廓。
概念自测
通过三个实际问题检验你对 FashionMNIST 流水线的理解:
batch_size=256 时,一轮训练(60{,}000 张图像)产生多少个小批量?最后一个小批量有多少张图像?data.visualize 图像网格能肉眼立见哪些、会漏掉哪些:(a) 标签偏移 +1,(b) 图像转置 (h \leftrightarrow w),(c) 像素未缩放仍留在 [0, 255.0],(d) 每轮每张图像重复出现两次?resize=(32, 32)(通过双线性插值 \mathbf{x}' = \mathbf{A}\mathbf{x} 得到 1{,}024 个像素),线性 softmax 分类器的表达能力会增强吗?答案:(1) 60{,}000 = 234 \times 256 + 96,每轮 235 个小批量,末批 96 张图(验证集 39 \times 256 + 16 \to 40 批)。(2) (a) 和 (b) 肉眼立见(标题错位、服饰横置);(c) 因 imshow 自动缩放 [vmin, vmax] 而隐藏;(d) 需检查 len(dataloader)。(3) 不会:任意线性分数 \mathbf{w}'^\top(\mathbf{A}\mathbf{x}) + b = (\mathbf{A}^\top\mathbf{w}')^\top\mathbf{x} + b 本身就是原始 784 像素上的线性分数。
本节小结
| 流水线阶段 | 规格 / 形状 | 系统与建模要点 |
|---|---|---|
| 数据集划分 | 60{,}000 训练 / 10{,}000 验证(每类 6\text{k} / 1\text{k}) | 10 个服饰类别完全均衡;float32 约占 \approx 188\text{ MB} |
| 像素编码 | 原始 uint8 \in [0, 255] \to float32 \in [0, 1] |
深色背景 = 0;缩放使初始线性 logit \mathbf{W}^\top\mathbf{x} 保持在 0 附近 |
小批量张量 X |
(n, 1, 28, 28)(通道优先)或 (n, 28, 28, 1)(通道在后),依框架而定 |
n = 64 \to 200\text{ KB};n = 256 \to 803\text{ KB};线性层展平为 (n, 784) |
标签向量 y |
一维整数张量 (n,),取值 \{0, \ldots, 9\} |
直接存储从 0 开始的类别索引;text_labels 将索引映射为服饰名称 |
| 每轮迭代 | n=64 时 938 批(n=256 时 235 批) | 每轮打乱训练集;保留末尾残余批量,不丢弃数据 |
| 吞吐量下界 | T_{\text{epoch}} \ge \max(T_{\text{load}}, T_{\text{compute}}) | 始终单独评测加载器;调优 batch_size 与工作进程并行度 |