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
The Image Classification Dataset: Fashion-MNIST & Data Pipelines
Fashion-MNIST benchmark · DataModule API · tensor layouts · minibatch loaders · pipeline throughput · visual debugging
Benchmark Selection
An effective development benchmark must separate weak models from strong architectures while fitting in memory and training in seconds:
Class Taxonomy
Fashion-MNIST contains 6{,}000 training and 1{,}000 test images for each of q = 10 clothing categories (0-based indices 0, \ldots, 9):
0, 2, 4, 6), 3 footwear items (5, 7, 9), and 3 distinct shapes (1 trouser, 3 dress, 8 bag).Object-Oriented Data Pipeline
FashionMNIST subclasses d2l.DataModule; resize=(h, w) changes resolution without new training code:
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)Object-Oriented Data Pipeline
uint8 in [0, 255], dark background = 0) rescale to float32 in [0, 1] before a minibatch leaves the loader.DataModule, every model that loads Fashion-MNIST sees the same [0, 1] inputs.Dataset Splits & Pitfalls
Instantiating FashionMNIST() loads the official 60{,}000-image training split and 10{,}000-image evaluation split into memory:
(60000, 10000)
uint8 or \approx 188\text{ MB} in float32.data.val uses the 10\text{k} test split (§3.5 quantifies reuse inflation).Shuffling & Batching
The get_dataloader(train) method wraps the dataset in an iterable minibatch loader:
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, yShuffling & Batching
shuffle=train): Training reshuffles all 60{,}000 indices every epoch; validation iterates in deterministic order.batch_size=64, 60{,}000 = 937 \times 64 + 32 yields 938 batches per epoch with zero dropped examples.Framework Tensor Conventions
A single grayscale image (c = 1, h = 28, w = 28) is stored as a 3D tensor whose channel-axis position depends on the framework:
torch.Size([1, 28, 28])
NCHW for a minibatch).NHWC) stores the channels of each pixel together; both flatten to the same 784 features.4D Image Tensors & 1D Label Vectors
Stacking n = 64 images prepends a leading batch axis to X and pairs it with a 1D integer vector y:
torch.Size([64, 1, 28, 28]) torch.float32 torch.Size([64]) torch.int64
X to (-1, 784) produces \mathbf{X} \in \mathbb{R}^{n \times 784} in both NCHW and NHWC.Systems Bottleneck Analysis
Before attaching any neural network, always time one complete pass over train_dataloader() by itself:
'0.42 sec'
Producer–Consumer Overlap
When background CPU workers prefetch batch b + 1 while the GPU computes on batch b, epoch wall-clock time obeys:
T_{\text{epoch}} \;\ge\; \max\!\big(T_{\text{load}},\; T_{\text{compute}}\big)
T_load >> T_compute), starving the GPU.num_workers=0 blocks serially between steps; once T_{\text{load}} < T_{\text{compute}}, extra workers add zero speedup.Defensive Data Inspection
Silent data bugs—shifted label mappings, transposed spatial axes, or scrambled channels—never raise syntax errors. Always plot a labeled gallery first:
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 to (-1, *self.resize) strips the length-1 channel axis from either (n, 1, h, w) or (n, h, w, 1).Visual Error Preview
Displaying the first three validation images of each category (one column per class) immediately reveals where a linear template classifier will struggle:
Silhouette clusters: Trousers (1) and bags (8) have unmistakable outlines; sandals (5), sneakers (7), and ankle boots (9) form a footwear cluster; and the four upper-body tops (T-shirt 0, pullover 2, coat 4, shirt 6) share nearly identical boxy silhouettes at 28 \times 28 resolution.
Concept Check
Test your understanding of the FashionMNIST pipeline on three practical questions:
batch_size=256 in §3.3, how many minibatches does one training epoch (60{,}000 images) produce, and how many images are in the final minibatch?data.visualize gallery expose immediately by eye, and which will it miss: (a) labels shifted by +1, (b) images transposed (h \leftrightarrow w), (c) pixels left unnormalized in [0, 255.0], (d) every image duplicated twice per epoch?resize=(32, 32) (1{,}024 pixels via bilinear interpolation \mathbf{x}' = \mathbf{A}\mathbf{x}), does a linear softmax classifier gain any new expressive power?Answers: (1) 60{,}000 = 234 \times 256 + 96, so 235 minibatches per epoch with 96 images in the last batch (validation has 39 \times 256 + 16 \to 40 batches). (2) (a) and (b) are obvious by eye (wrong titles, sideways clothes); (c) is hidden because imshow auto-rescales [vmin, vmax]; (d) requires checking len(dataloader). (3) No: any linear score \mathbf{w}'^\top(\mathbf{A}\mathbf{x}) + b = (\mathbf{A}^\top\mathbf{w}')^\top\mathbf{x} + b is already a linear score on the original 784 pixels.
Section Summary
| Pipeline Stage | Specification / Shape | Systems & Modelling Takeaway |
|---|---|---|
| Dataset splits | 60{,}000 train / 10{,}000 val (6\text{k} / 1\text{k} per class) | Perfectly balanced across 10 apparel categories; \approx 188\text{ MB} in float32 |
| Pixel encoding | Raw uint8 \in [0, 255] \to float32 \in [0, 1] |
Dark background = 0; rescaling keeps initial linear logits \mathbf{W}^\top\mathbf{x} near 0 |
Minibatch tensor X |
(n, 1, 28, 28) (channel-first) or (n, 28, 28, 1) (channel-last), per the framework |
n = 64 \to 200\text{ KB}; n = 256 \to 803\text{ KB}; flattens to (n, 784) for linear layers |
Label vector y |
1D integer tensor (n,) with values in \{0, \ldots, 9\} |
Stores 0-based class index directly; text_labels maps indices to garment names |
| Epoch iteration | 938 batches at n=64 (235 at n=256) | Shuffles training split every epoch; retains partial final batch so no data are dropped |
| Throughput bound | T_{\text{epoch}} \ge \max(T_{\text{load}}, T_{\text{compute}}) | Always benchmark the standalone loader; tune batch_size and worker parallelism |