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) ( grayscale images across 10 digit classes) was a landmark benchmark in the 1990s, but today even trivial models clear accuracy and convolutional networks exceed , leaving almost no headroom to see architectural improvements work. At the opposite extreme, ImageNet (Deng et al., 2009) ( million color photos across categories) requires hours of GPU compute per run.
Fashion-MNIST (Xiao et al., 2017) hits the sweet spot: it keeps MNIST's footprint ( training and test grayscale images of size across 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 accuracy while convolutional networks climb past . 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 transformsd2l.use_svg_display()
3.2.1 Loading the Dataset#
Fashion-MNIST contains training images and test images for each of its garment categories ( and in total), stored as 8-bit unsigned integers in ( = 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 ):
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 . It applies whenever we index the dataset directly, as in data.train[i], or pass data.train to a loader of our own.
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)Let us instantiate the dataset and verify the size of each split.
data = FashionMNIST()
len(data.train), len(data.val)(60000, 10000)
Because Fashion-MNIST ships with only two splits, we use the -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 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 with channels ( for grayscale, for RGB color), height , and width is stored either in channel-first layout or channel-last layout , depending on the framework.
PyTorch stores images in channel-first layout .
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 () so every image is visited once per epoch:
A batchify helper scales each minibatch to float32 in 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.
@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, yLet 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])
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
At per minibatch (and for all 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'
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 resolution barely resolves.
3.2.4 Summary#
Fashion-MNIST provides training and test grayscale images across balanced clothing categories, making it rich enough to separate linear models () from convolutional networks () while small enough to train in seconds. Our FashionMNIST(d2l.DataModule) pipeline rescales raw uint8 pixels to float32 in , 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#
- [code] Class means. Compute the mean image of each class over the
training set, and show the ten means as a grid of images.
- Compute the Euclidean distance between every pair of class means and present the distances as a table. Which pairs are closest, and which class is farthest from all others?
- 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.
- Name a pair of classes that a person tells apart easily although their means are close, and say which pixels carry the difference.
- [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.
- Time one full pass of
train_dataloaderforFashionMNISTconstructed withbatch_sizeof 1, 16, 64, 256, and 1024, and plot the throughput in images per second againstbatch_size. Explain the shape of the curve in terms of per-batch overhead and per-image work. batchifyresizes each minibatch as the loader reads it. Time one pass oftrain_dataloaderforFashionMNIST(resize=(s, s))with = 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?
- Time one full pass of
- [code] Upsampling and linear models. ● Treat the resizing from
to as a linear map
from the 784 original pixels to the
1024 resized ones, where the columns of
are linearly independent.
- Show that softmax regression on can represent exactly the classifiers that softmax regression on can.
- After Section 3.3, train
SoftmaxRegressionScratchon data fromFashionMNIST()and fromFashionMNIST(resize=(32, 32)), withnum_inputsset to the number of pixels per image. Compare the validation accuracies and explain any difference in light of the previous part.