Image Classification Data

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

Why Fashion-MNIST Is Our Running Vision Benchmark

Benchmark Selection

An effective development benchmark must separate weak models from strong architectures while fitting in memory and training in seconds:

  • MNIST (1998) is too easy: Linear models reach \approx 92\% and small CNNs pass 99\%, leaving almost no headroom to test new ideas.
  • ImageNet-1K (ILSVRC-2012) is too heavy: 1.2\text{M} color photos across 1{,}000 classes require hours of multi-GPU compute per experiment.
  • Fashion-MNIST (2017) hits the sweet spot: Drop-in 70{,}000-image (28\times 28) footprint where linear softmax reaches \sim 83\% and CNNs exceed 90\%.

Ten Balanced Apparel Categories

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):

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]
  • Silhouette clusters: 4 boxy upper-body tops (0, 2, 4, 6), 3 footwear items (5, 7, 9), and 3 distinct shapes (1 trouser, 3 dress, 8 bag).

Encapsulating Fashion-MNIST in a DataModule

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)

Rescaling Pixels in the Data Module

Object-Oriented Data Pipeline

  • Normalization before the model: Raw 8-bit pixels (uint8 in [0, 255], dark background = 0) rescale to float32 in [0, 1] before a minibatch leaves the loader.
  • One place to change: Because the rescaling lives in the DataModule, every model that loads Fashion-MNIST sees the same [0, 1] inputs.

Verifying the Official Train and Validation Splits

Dataset Splits & Pitfalls

Instantiating FashionMNIST() loads the official 60{,}000-image training split and 10{,}000-image evaluation split into memory:

data = FashionMNIST()
len(data.train), len(data.val)
(60000, 10000)
  • Compact memory footprint: At 784 pixels/image, 60{,}000 training images take \approx 47\text{ MB} in uint8 or \approx 188\text{ MB} in float32.
  • Test-set reuse caveat: Because Fashion-MNIST ships with only two splits, data.val uses the 10\text{k} test split (§3.5 quantifies reuse inflation).

Building the Minibatch Loader

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, y

Epoch Reshuffling and the Short Final Batch

Shuffling & Batching

  • Epoch reshuffling (shuffle=train): Training reshuffles all 60{,}000 indices every epoch; validation iterates in deterministic order.
  • Retaining the short final minibatch: At batch_size=64, 60{,}000 = 937 \times 64 + 32 yields 938 batches per epoch with zero dropped examples.

Single-Image Layouts: Channel-First vs. Channel-Last

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:

X, y = next(iter(data.train_dataloader()))
X[0].shape  # Channel-first: (channels, height, width)
torch.Size([1, 28, 28])
  • Channel-first (c, h, w) = (1, 28, 28): This framework puts the channel axis first (NCHW for a minibatch).
  • The other convention: Channel-last (h, w, c) (NHWC) stores the channels of each pixel together; both flatten to the same 784 features.

Inspecting a Full Minibatch of Images and Labels

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:

print(X.shape, X.dtype, y.shape, y.dtype)
torch.Size([64, 1, 28, 28]) torch.float32 torch.Size([64]) torch.int64
  • Minibatch footprint: 64 \times 1 \times 28 \times 28 \times 4\text{ B} \approx 200\text{ KB} (\approx 803\text{ KB} at n = 256).
  • Flattening for linear models: Reshaping X to (-1, 784) produces \mathbf{X} \in \mathbb{R}^{n \times 784} in both NCHW and NHWC.

Benchmarking Loader Throughput in Isolation

Systems Bottleneck Analysis

Before attaching any neural network, always time one complete pass over train_dataloader() by itself:

tic = time.time()
for X, y in data.train_dataloader():
    continue
f'{time.time() - tic:.2f} sec'
'0.42 sec'
  • Hard lower bound on epoch time: Because data loading and model execution form a producer–consumer pipeline, no training epoch can ever run faster than the data loader alone.

Diagnosing Data Pipeline Bottlenecks

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)

  • Small batch sizes (n = 1 or 16): Per-batch Python dispatch overhead dominates (T_load >> T_compute), starving the GPU.
  • Worker scaling: num_workers=0 blocks serially between steps; once T_{\text{load}} < T_{\text{compute}}, extra workers add zero speedup.

Visualizing Labeled Minibatches Before Training

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')
  • Dropping the singleton channel: Reshaping X to (-1, *self.resize) strips the length-1 channel axis from either (n, 1, h, w) or (n, h, w, 1).

What the Garment Silhouettes Predict About Model Errors

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: Shapes, Batches & Visual Debugging

Concept Check

Test your understanding of the FashionMNIST pipeline on three practical questions:

  1. Minibatch counts: When we switch to 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?
  2. Visual vs. numerical bugs: Which of these four bugs will a 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?
  3. Upsampling invariance: If we set 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.

Summary: Fashion-MNIST Data Pipeline

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