Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

stough 202-

Preview: Look into the MNIST dataset with PyTorch.

The MNIST database is one of the first large machine learning datasets, originally designed for the computer vision task of recognizing digits on bank checks. It consists of some {60000 training, 10000 test} 28x28 grayscale images of handwritten digits, along with each image’s associated decimal digit represented.

PyTorch is open source machine learning library principally developed by Facebook. It enables us to perform very advanced GPU-based machine learning through a convenient Python interface.

We will here explore the MNIST dataset through PyTorch.

Download the training and test Datasets

Torch allows us to interface with our data through DataLoader and Dataset objects. torchvision knows how to fetch MNIST, and with download=True it downloads the data into your data folder (see data_paths) the first time, then reuses it.

Indexing a Dataset gives one example: a tuple of the image (here a PIL image, which the notebook displays directly) and its label, an integer from 0 to 9. Before torch can compute with the images, they need to be tensors. ToTensor converts a PIL image to a float tensor scaled to [0,1][0, 1], with shape (1,28,28)(1, 28, 28): channels first, then rows and columns.

Expected output (what the cell above should show, if you can’t run it)
expected output

make_grid tiles a batch of images into one big image, and the permute reorders it from torch’s (channels, height, width) to the (height, width, channels) that matplotlib expects (see the note below). Run the cell a few times to see different random samples. Notice the variety in handwriting: thick and thin strokes, slants, open and closed loops.

Let’s look at all training sevens.

We do the permute because torch is channels-first, meaning each image is actually (1,28,28). If our images were color, the default orientation would be (3,h,w). This orientation is incompatible with matplotlib’s imshow.

Expected output (what the cell above should show, if you can’t run it)
expected output

Summing every seven in the training set gives a kind of “average seven”: brightest where most sevens have ink, the crossbar at the top and the stroke down the middle, and fading out where only some sevens reach. The blur shows how much the sevens vary in slant and position. Even so, they are roughly centered and scaled the same way. The MNIST creators normalized every digit to fit a 20×2020 \times 20 box centered in the 28×2828 \times 28 image, which makes the recognition task much easier.

Next, can we recognize digits automatically? Try a first approach yourself in the template-matching activity, then see what a learned linear classifier does.