3.2  Image Classification Data

To train and test softmax regression, we need an image classification benchmark that is rich enough to separate weak models from strong ones yet compact enough to train in seconds inside an interactive notebook. Classic MNIST handwritten digits (LeCun et al. 1998) (\(70{,}000\) grayscale \(28 \times 28\) images across 10 digit classes) was a landmark benchmark in the 1990s, but today even trivial models clear \(97\%\) accuracy and convolutional networks exceed \(99\%\), leaving almost no headroom to see architectural improvements work. At the opposite extreme, ImageNet (Deng et al. 2009) (\(1.2\) million color photos across \(1{,}000\) categories) requires hours of GPU compute per run.

Fashion-MNIST (Xiao et al. 2017) hits the sweet spot: it keeps MNIST’s footprint (\(60{,}000\) training and \(10{,}000\) test grayscale images of size \(28 \times 28\) across \(10\) balanced classes) while replacing digits with articles of clothing (T-shirt, trouser, pullover, dress, coat, sandal, shirt, sneaker, bag, and ankle boot). On Fashion-MNIST, linear softmax regression reaches roughly \(83\%\) accuracy while convolutional networks climb past \(90\%\). In this section, we build the FashionMNIST(d2l.DataModule) class that feeds our image classifiers across the next several chapters.

import time
import torchvision
from torchvision import transforms
import time
import tensorflow as tf
import time
import gzip
import os
import time
d2l.use_svg_display()

3.2.1 Loading the Dataset

Fashion-MNIST contains \(6{,}000\) training images and \(1{,}000\) test images for each of its \(10\) garment categories (\(60{,}000\) and \(10{,}000\) in total), stored as 8-bit unsigned integers in \([0, 255]\) (\(0\) = dark background). Following our object-oriented design (Section 2.4), FashionMNIST subclasses d2l.DataModule and accepts batch_size and an optional spatial resize tuple (defaulting to \((28, 28)\)):

torchvision.datasets.FashionMNIST downloads the dataset and keeps all images of a split in one uint8 tensor. The data loader that we define below reads this tensor and converts whole minibatches at a time. The transforms.Compose pipeline resizes one image and scales its pixel intensities to a float32 tensor in \([0, 1]\). It applies whenever we index the dataset directly, as in data.train[i], or pass data.train to a loader of our own.

tf.keras.datasets.fashion_mnist.load_data() returns the official training and test splits as (images, labels) NumPy arrays.

tf.keras.datasets.fashion_mnist.load_data() returns the official training and test splits as (images, labels) NumPy arrays.

Because Gluon’s built-in Fashion-MNIST helper uses a nonstandard train/test split, FashionMNIST.read downloads and parses the official gzipped IDX byte files directly (skipping the 16-byte image header and 8-byte label header), and to_dataset scales the pixels to float32 in \([0, 1]\).

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)
class FashionMNIST(d2l.DataModule):
    """The Fashion-MNIST dataset."""
    def __init__(self, batch_size=64, resize=(28, 28)):
        super().__init__()
        self.save_hyperparameters()
        self.train, self.val = tf.keras.datasets.fashion_mnist.load_data()
class FashionMNIST(d2l.DataModule):
    """The Fashion-MNIST dataset."""
    def __init__(self, batch_size=64, resize=(28, 28)):
        super().__init__()
        self.save_hyperparameters()
        self.train, self.val = tf.keras.datasets.fashion_mnist.load_data()
class FashionMNIST(d2l.DataModule):
    """The Fashion-MNIST dataset."""
    def __init__(self, batch_size=64, resize=(28, 28)):
        super().__init__()
        self.save_hyperparameters()
        self.train = self.to_dataset(*self.read(train=True))
        self.val = self.to_dataset(*self.read(train=False))

    def read(self, train):
        """Images and labels of one split, read from the published files."""
        url = 'http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/'
        folder = os.path.join(self.root, 'FashionMNIST', 'raw')
        arrays = []
        for kind, header in (('images-idx3', 16), ('labels-idx1', 8)):
            fname = f"{'train' if train else 't10k'}-{kind}-ubyte.gz"
            if not os.path.exists(os.path.join(folder, fname)):
                d2l.download(url + fname, folder)
            with gzip.open(os.path.join(folder, fname)) as f:
                data = bytearray(f.read())[header:]  # One byte per value
            arrays.append(d2l.tensor(data, dtype='uint8'))
        images, labels = arrays
        return images.reshape(-1, 28, 28, 1), labels.astype('int32')

    def to_dataset(self, images, labels):
        """Convert all images at once: channel axis first, values in [0, 1]."""
        X = images.asnumpy().transpose(0, 3, 1, 2).astype('float32') / 255
        return gluon.data.ArrayDataset(X, labels.asnumpy())

Let us instantiate the dataset and verify the size of each split.

data = FashionMNIST()
len(data.train), len(data.val)
(60000, 10000)
data = FashionMNIST()
len(data.train[0]), len(data.val[0])
(60000, 10000)
data = FashionMNIST()
len(data.train[0]), len(data.val[0])
(60000, 10000)
data = FashionMNIST()
len(data.train), len(data.val)
(60000, 10000)

Because Fashion-MNIST ships with only two splits, we use the \(10{,}000\)-image test split as our validation set during training (we analyze the statistical effect of repeated test-set evaluation in Section 3.5). Let us also attach text_labels to translate integer class indices \(0, \ldots, 9\) into human-readable garment names:

@d2l.add_to_class(FashionMNIST)
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]

3.2.2 Reading Minibatches

In deep learning frameworks, each image in a minibatch of size \(n\) with \(c\) channels (\(c = 1\) for grayscale, \(c = 3\) for RGB color), height \(h\), and width \(w\) is stored either in channel-first layout \((n, c, h, w)\) or channel-last layout \((n, h, w, c)\), depending on the framework.

PyTorch stores images in channel-first layout \((n, c, h, w)\).

TensorFlow stores images in channel-last layout \((n, h, w, c)\).

JAX stores images in channel-last layout \((n, h, w, c)\). We wrap tf.data.Dataset in a lightweight TensorFlowDataLoader helper that exposes .as_numpy_iterator() and __len__ so each epoch yields NumPy minibatches directly:

MXNet stores images in channel-first layout \((n, c, h, w)\).

class TensorFlowDataLoader:
    """Expose a tf.data.Dataset as re-iterable NumPy batches."""
    def __init__(self, dataset):
        self.dataset = dataset

    def __iter__(self):
        return self.dataset.as_numpy_iterator()

    def __len__(self):
        return len(self.dataset)

Now we attach get_dataloader(self, train) to FashionMNIST, wrapping the framework’s native data loader so it reshuffles the training split on every epoch and retains the final partial minibatch (\(60{,}000 = 937 \times 64 + 32\)) so every image is visited once per epoch:

A batchify helper scales each minibatch to float32 in \([0, 1]\) and resizes it as the loader reads it. One operation on a whole minibatch is much cheaper than a separate operation for each image, which is why the loader does not go through the per-image transform.

A batchify helper resizes each minibatch as the loader reads it.

@d2l.add_to_class(FashionMNIST)
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)

@d2l.add_to_class(FashionMNIST)
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
@d2l.add_to_class(FashionMNIST)
def get_dataloader(self, train):
    X, y = self.train if train else self.val
    X = tf.expand_dims(X, axis=3) / 255  # Channel axis last; values in [0, 1]
    resize = lambda X, y: (tf.image.resize(X, self.resize), y)
    return tf.data.Dataset.from_tensor_slices(
        (X, tf.cast(y, tf.int32))).shuffle(len(y) if train else 1).batch(
            self.batch_size).map(resize)
@d2l.add_to_class(FashionMNIST)
def get_dataloader(self, train):
    X, y = self.train if train else self.val
    X = tf.expand_dims(X, axis=3) / 255  # Channel axis last; values in [0, 1]
    resize = lambda X, y: (tf.image.resize(X, self.resize), y)
    return TensorFlowDataLoader(tf.data.Dataset.from_tensor_slices(
        (X, tf.cast(y, tf.int32))).shuffle(len(y) if train else 1).batch(
            self.batch_size).map(resize))
@d2l.add_to_class(FashionMNIST)
def get_dataloader(self, train):
    data = self.train if train else self.val
    return gluon.data.DataLoader(data, self.batch_size, shuffle=train,
                                 batchify_fn=self.batchify)

@d2l.add_to_class(FashionMNIST)
def batchify(self, examples):
    """Stack examples into a minibatch and resize it if asked to."""
    X, y = gluon.data.batchify.Stack()(examples)
    if X.shape[2:] != tuple(self.resize):  # Resizing wants channels last
        X = npx.image.resize(X.transpose(0, 2, 3, 1), self.resize[::-1])
        X = X.transpose(0, 3, 1, 2)
    return X, y

Let us fetch one minibatch (X, y) from train_dataloader() and inspect both the single-image layout and the full minibatch tensor shapes and dtypes:

X, y = next(iter(data.train_dataloader()))
X[0].shape  # Channel-first: (channels, height, width)
torch.Size([1, 28, 28])
X, y = next(iter(data.train_dataloader()))
X[0].shape  # Channel-last: (height, width, channels)
TensorShape([28, 28, 1])
X, y = next(iter(data.train_dataloader()))
X[0].shape  # Channel-last: (height, width, channels)
(28, 28, 1)
X, y = next(iter(data.train_dataloader()))
X[0].shape  # Channel-first: (channels, height, width)
(1, 28, 28)

Stacking examples into a minibatch prepends a leading batch axis to the images, while the labels arrive as a one-dimensional vector with one entry per image.

print(X.shape, X.dtype, y.shape, y.dtype)
torch.Size([64, 1, 28, 28]) torch.float32 torch.Size([64]) torch.int64
(64, 28, 28, 1) <dtype: 'float32'> (64,) <dtype: 'int32'>
(64, 28, 28, 1) float32 (64,) int32
(64, 1, 28, 28) float32 (64,) int32

At \(64 \times 28 \times 28 \times 4 \approx 200\textrm{ KB}\) per minibatch (and \(\sim 190\textrm{ MB}\) for all \(60{,}000\) float32 training images), the entire dataset fits comfortably in RAM. Still, benchmarking the data loader by itself—timing one complete pass over train_dataloader() with no model attached—is a vital habit, because no training epoch can run faster than its data pipeline.

tic = time.time()
for X, y in data.train_dataloader():
    continue
f'{time.time() - tic:.2f} sec'
'0.42 sec'
'0.57 sec'
'0.55 sec'
'0.53 sec'

3.2.3 Inspecting the Images

Always inspect a sample of labeled images by eye before training any model: misaligned labels, inverted intensities, or a scrambled reshape will ruin training without raising a runtime error. We attach a visualize method to FashionMNIST that drops the singleton channel axis and plots a grid of grayscale images titled with their text labels:

@d2l.add_to_class(FashionMNIST)
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')

Let us display the first three validation images of every class, one column per category, taking advantage of the fact that the validation loader always returns images in deterministic order:

X, y = next(iter(data.val_dataloader()))
labels = d2l.numpy(y)
idx = [int(np.flatnonzero(labels == c)[r]) for r in range(3) for c in range(10)]
titles = data.text_labels(range(10)) + [''] * 20
data.visualize([d2l.stack([X[i] for i in idx]), None], nrows=3, ncols=10,
               labels=titles)

Even a quick visual scan previews what our linear classifier is up against: trousers and bags have unmistakable silhouettes, sandals/sneakers/ankle boots form a distinct footwear cluster, and the four upper-body garments (T-shirt, pullover, coat, and shirt) share almost the same boxy torso outline, differing only in subtle collar, sleeve, and button details that \(28 \times 28\) resolution barely resolves.

3.2.4 Summary

Fashion-MNIST provides \(60{,}000\) training and \(10{,}000\) test grayscale \(28 \times 28\) images across \(10\) balanced clothing categories, making it rich enough to separate linear models (\(\sim 83\%\)) from convolutional networks (\(>90\%\)) while small enough to train in seconds. Our FashionMNIST(d2l.DataModule) pipeline rescales raw uint8 pixels to float32 in \([0, 1]\), supports optional spatial resizing, and delivers reshuffled minibatches alongside integer labels in each framework’s native channel layout. Benchmarking the standalone loader sets a lower bound on epoch time, and inspecting a labeled gallery catches silent shape or label mismatches before training starts.

3.2.5 Exercises

  1. [code] Class means. Compute the mean image of each class over the training set, and show the ten means as a grid of images.
    1. Compute the Euclidean distance between every pair of class means and present the distances as a \(10 \times 10\) table. Which pairs are closest, and which class is farthest from all others?
    2. Predict from the table which classes a linear classifier will confuse most often and which it will almost never confuse. Keep your prediction; Section 3.3 computes the answer.
    3. Name a pair of classes that a person tells apart easily although their means are close, and say which pixels carry the difference.
  2. [code] Loader throughput. The time of one pass over the training set depends on the minibatch size and on the size of the images that the loader delivers.
    1. Time one full pass of train_dataloader for FashionMNIST constructed with batch_size of 1, 16, 64, 256, and 1024, and plot the throughput in images per second against batch_size. Explain the shape of the curve in terms of per-batch overhead and per-image work.
    2. batchify resizes each minibatch as the loader reads it. Time one pass of train_dataloader for FashionMNIST(resize=(s, s)) with \(s\) = 28, 56, 112, and 224, and plot the time against the number of pixels per image. Which part of the time grows with the number of pixels, and which does not?
  3. [code] Upsampling and linear models. ● Treat the resizing from \(28 \times 28\) to \(32 \times 32\) as a linear map \(\mathbf{x}' = \mathbf{A}\mathbf{x}\) from the 784 original pixels to the 1024 resized ones, where the columns of \(\mathbf{A} \in \mathbb{R}^{1024 \times 784}\) are linearly independent.
    1. Show that softmax regression on \(\mathbf{x}'\) can represent exactly the classifiers that softmax regression on \(\mathbf{x}\) can.
    2. After Section 3.3, train SoftmaxRegressionScratch on data from FashionMNIST() and from FashionMNIST(resize=(32, 32)), with num_inputs set to the number of pixels per image. Compare the validation accuracies and explain any difference in light of the previous part.
  1. [code] Class means. Compute the mean image of each class over the training set, and show the ten means as a grid of images.
    1. Compute the Euclidean distance between every pair of class means and present the distances as a \(10 \times 10\) table. Which pairs are closest, and which class is farthest from all others?
    2. Predict from the table which classes a linear classifier will confuse most often and which it will almost never confuse. Keep your prediction; Section 3.3 computes the answer.
    3. Name a pair of classes that a person tells apart easily although their means are close, and say which pixels carry the difference.
  2. [code] Loader throughput. The time of one pass over the training set depends on the minibatch size and on how much of the pipeline runs in parallel.
    1. Time one full pass of train_dataloader for FashionMNIST constructed with batch_size of 1, 16, 64, 256, and 1024, and plot the throughput in images per second against batch_size. Explain the shape of the curve in terms of per-batch overhead and per-image work.
    2. The tf.data pipeline in get_dataloader does not use the num_workers attribute of DataModule; its parallelism is set per stage. Time one pass as written, then with num_parallel_calls=tf.data.AUTOTUNE in the map call and a trailing .prefetch(tf.data.AUTOTUNE). State under what conditions more parallelism stops helping.
  3. [code] Upsampling and linear models. ● Treat the resizing from \(28 \times 28\) to \(32 \times 32\) as a linear map \(\mathbf{x}' = \mathbf{A}\mathbf{x}\) from the 784 original pixels to the 1024 resized ones, where the columns of \(\mathbf{A} \in \mathbb{R}^{1024 \times 784}\) are linearly independent.
    1. Show that softmax regression on \(\mathbf{x}'\) can represent exactly the classifiers that softmax regression on \(\mathbf{x}\) can.
    2. After Section 3.3, train SoftmaxRegressionScratch on data from FashionMNIST() and from FashionMNIST(resize=(32, 32)), with num_inputs set to the number of pixels per image. Compare the validation accuracies and explain any difference in light of the previous part.
  1. [code] Class means. Compute the mean image of each class over the training set, and show the ten means as a grid of images.
    1. Compute the Euclidean distance between every pair of class means and present the distances as a \(10 \times 10\) table. Which pairs are closest, and which class is farthest from all others?
    2. Predict from the table which classes a linear classifier will confuse most often and which it will almost never confuse. Keep your prediction; Section 3.3 computes the answer.
    3. Name a pair of classes that a person tells apart easily although their means are close, and say which pixels carry the difference.
  2. [code] Loader throughput. The time of one pass over the training set depends on the minibatch size and on how much of the pipeline runs in parallel.
    1. Time one full pass of train_dataloader for FashionMNIST constructed with batch_size of 1, 16, 64, 256, and 1024, and plot the throughput in images per second against batch_size. Explain the shape of the curve in terms of per-batch overhead and per-image work.
    2. The tf.data pipeline in get_dataloader does not use the num_workers attribute of DataModule; its parallelism is set per stage. Time one pass as written, then with num_parallel_calls=tf.data.AUTOTUNE in the map call and a trailing .prefetch(tf.data.AUTOTUNE). State under what conditions more parallelism stops helping.
  3. [code] Upsampling and linear models. ● Treat the resizing from \(28 \times 28\) to \(32 \times 32\) as a linear map \(\mathbf{x}' = \mathbf{A}\mathbf{x}\) from the 784 original pixels to the 1024 resized ones, where the columns of \(\mathbf{A} \in \mathbb{R}^{1024 \times 784}\) are linearly independent.
    1. Show that softmax regression on \(\mathbf{x}'\) can represent exactly the classifiers that softmax regression on \(\mathbf{x}\) can.
    2. After Section 3.3, train SoftmaxRegressionScratch on data from FashionMNIST() and from FashionMNIST(resize=(32, 32)), with num_inputs set to the number of pixels per image. Compare the validation accuracies and explain any difference in light of the previous part.
  1. [code] Class means. Compute the mean image of each class over the training set, and show the ten means as a grid of images.
    1. Compute the Euclidean distance between every pair of class means and present the distances as a \(10 \times 10\) table. Which pairs are closest, and which class is farthest from all others?
    2. Predict from the table which classes a linear classifier will confuse most often and which it will almost never confuse. Keep your prediction; Section 3.3 computes the answer.
    3. Name a pair of classes that a person tells apart easily although their means are close, and say which pixels carry the difference.
  2. [code] Loader throughput. The time of one pass over the training set depends on the minibatch size and on the size of the images that the loader delivers.
    1. Time one full pass of train_dataloader for FashionMNIST constructed with batch_size of 1, 16, 64, 256, and 1024, and plot the throughput in images per second against batch_size. Explain the shape of the curve in terms of per-batch overhead and per-image work.
    2. batchify resizes each minibatch as the loader reads it. Time one pass of train_dataloader for FashionMNIST(resize=(s, s)) with \(s\) = 28, 56, 112, and 224, and plot the time against the number of pixels per image. Which part of the time grows with the number of pixels, and which does not?
  3. [code] Upsampling and linear models. ● Treat the resizing from \(28 \times 28\) to \(32 \times 32\) as a linear map \(\mathbf{x}' = \mathbf{A}\mathbf{x}\) from the 784 original pixels to the 1024 resized ones, where the columns of \(\mathbf{A} \in \mathbb{R}^{1024 \times 784}\) are linearly independent.
    1. Show that softmax regression on \(\mathbf{x}'\) can represent exactly the classifiers that softmax regression on \(\mathbf{x}\) can.
    2. After Section 3.3, train SoftmaxRegressionScratch on data from FashionMNIST() and from FashionMNIST(resize=(32, 32)), with num_inputs set to the number of pixels per image. Compare the validation accuracies and explain any difference in light of the previous part.