AI Logic

Datasets and Benchmarks

MNIST

Updated:

How MNIST was built and the shape of its data. Left: the flow of mixing NIST SD-3 and SD-1, shrinking digits to fit a 20×20 box, centering them in a 28×28 image, and splitting into 60,000 training and 10,000 test images. Right: a 28×28 grid with pixel values, the label, and the tensor shape

Background and overview

MNIST is a dataset of handwritten digits 0–9 as 28×28-pixel grayscale images. It consists of 60,000 training and 10,000 test images, 70,000 in total, and is used for 10-class classification: looking at an image and predicting which digit is written.

LeCun et al. released it in 1998 as the dataset used in the experiments of the paper that proposed LeNet-5. The name stands for Modified NIST; it is a rework of handwritten digit data collected by the U.S. National Institute of Standards and Technology (NIST).

Because the images are small and the whole dataset is only tens of MB, a model can be trained in a few minutes even on a laptop. It is therefore widely used as the first testbed for new methods and as teaching material for deep learning, and is sometimes called "the Hello World of machine learning". Implementation examples on this site, such as MLP, also use MNIST.

In the paper, LeNet-5's test error rate was 0.95%, dropping to 0.8% when the training images were augmented with distortions. Current methods achieve even lower error rates, so getting over 99% accuracy on MNIST alone does not demonstrate that a method is good.

How the dataset was built

MNIST was built by mixing two NIST databases. The source data are Special Database 3 (SD-3, written by Census Bureau employees) and Special Database 1 (SD-1, written by high school students). NIST designated SD-3 for training and SD-1 for testing, but SD-3 is cleaner and easier to read, so using them as is would make training and testing differ in difficulty. The data were therefore rebuilt as follows.

  1. Split the 58,527 images of SD-1 (from 500 writers) into two by writer.
    • Characters from the first 250 writers go into the training set and those from the remaining 250 writers into the test set. Each gets about 30,000 images.
  2. Add SD-3 images so that the training and test sets each have 60,000 images.
  3. Shrink the black-and-white images to fit in a 20×20-pixel box while preserving the aspect ratio.
    • Interpolation during shrinking creates gray levels at the edges of the characters.
  4. Place each character in a 28×28 image so that its center of mass (of pixel intensity) is at the center.
  5. Of the 60,000 test images, 10,000 (5,000 from SD-1 and 5,000 from SD-3) become the published test set.

In the SD-1 portion, training and test writers do not overlap. Test performance therefore reflects "how well the model reads digits written by people it has never seen".

The remaining 50,000 unused test images were long lost, but in 2019 Yadav and Bottou reconstructed them from the NIST data and released them as QMNIST.

Data format and loading

The contents of MNIST are summarized below.

ItemDetails
Images60,000 training, 10,000 test
Image28×28 pixels, 1-channel grayscale
Pixel valuesIntegers 0–255 (background is 0; larger where the stroke is)
LabelsIntegers 0–9 (10 classes)
FilesFour files in a format called IDX (images and labels for training and test)

In PyTorch, torchvision.datasets.MNIST downloads and loads the data. After ToTensor(), each image becomes a [1, 28, 28] tensor with values in 0–1, and the label is an integer. When feeding a model with only fully connected layers, flatten the image into a 784-dimensional (=28×28= 28 \times 28) vector.

MNIST has no validation set. Looking at test-set performance when choosing hyperparameters fits the model to the test set (a form of overfitting) and overestimates performance. Hold out part of the 60,000 training images (e.g., 5,000) for validation, and use the test set only for the final evaluation.

Limitations and alternative datasets

MNIST is easy to work with, but it has the following limitations.

  • Too easy: many methods exceed 99% accuracy, making differences between methods hard to see.
  • Unlike real images: characters are centered, uniformly sized, and have no background. Methods that work well on MNIST do not necessarily work on natural photos.
  • Label errors: a small number of images have been pointed out as having incorrect labels.

It is therefore common to use MNIST for sanity checks and getting started, and to also use harder datasets when demonstrating a method's performance. Alternatives by purpose are as follows.

DatasetContentsBest suited for
MNISTHandwritten digits, 28×28 grayscale, 10 classesSanity checks, getting started
Fashion-MNISTPhotos of clothes, shoes, etc., 28×28 grayscale, 10 classesTrying a slightly harder task with the same code as MNIST
EMNISTHandwritten digits and letters (built from NIST SD-19)Handwritten character recognition with more character types
CIFAR-10/100Photos of objects, 32×32 color, 10 or 100 classesClassification of small natural images
ImageNetPhotos of objects, various sizes, 1,000 classesSerious comparison of image recognition performance

Fashion-MNIST uses the same image size, file format, and split sizes as MNIST, so code that loads MNIST can be used almost unchanged.

PyTorch example

Show code
python
import torch
from torchvision import datasets, transforms
from torch.utils.data import DataLoader, random_split

'''
Load MNIST with torchvision and split into training, validation, and test sets
'''

# Convert images to [0, 1] tensors, then normalize by mean and standard deviation
# (0.1307 and 0.3081 are commonly used values for the pixel mean and std of the MNIST training set)
transform = transforms.Compose([
  transforms.ToTensor(),                      # 0-255 image -> [1, 28, 28] tensor in 0-1
  transforms.Normalize((0.1307,), (0.3081,))
])

# Downloads to ./data/MNIST/raw/ on first run
train_full = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
print(len(train_full), len(test_dataset))  # 60000 10000

# MNIST has no validation set, so hold out 5,000 images from the training set
generator = torch.Generator().manual_seed(0)
train_dataset, val_dataset = random_split(train_full, [55000, 5000], generator=generator)

# Each example is a pair (image tensor, integer label)
image, label = train_full[0]
print(image.shape, type(label))  # torch.Size([1, 28, 28]) <class 'int'>

train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=256)
test_loader = DataLoader(test_dataset, batch_size=256)

images, labels = next(iter(train_loader))
print(images.shape, labels.shape)  # torch.Size([64, 1, 28, 28]) torch.Size([64])

# Flatten to 784 dimensions when feeding fully connected layers (MLP)
flat = images.flatten(start_dim=1)
print(flat.shape)  # torch.Size([64, 784])

FAQ

Q. Are MNIST images in color?
A.

No. They are 1-channel grayscale. Pixels take values 0–255, with a background of 0. Interpolation when the original black-and-white images were shrunk leaves gray levels at the edges of the characters.

Q. How should I create a validation set?
A.

MNIST has no validation set, so hold out part of the 60,000 training images. In PyTorch, use random_split to split them into, for example, 55,000 and 5,000 images. Use the 10,000 test images only for the final evaluation.

Q. Does high accuracy on MNIST mean a model is good?
A.

No. MNIST is easy, and many methods exceed 99%. It is suited to sanity checks, but when comparing performance, also verify on harder datasets such as Fashion-MNIST or CIFAR-10.

References

  1. LeCun, Y., Bottou, L., Bengio, Y., & Haffner, P. (1998). Gradient-based learning applied to document recognition. Proceedings of the IEEE, 86(11), 2278–2324.
  2. LeCun, Y., Cortes, C., & Burges, C. J. C. The MNIST database of handwritten digits (official page).
  3. Yadav, C., & Bottou, L. (2019). Cold Case: The Lost MNIST Digits. NeurIPS 2019.
  4. Xiao, H., Rasul, K., & Vollgraf, R. (2017). Fashion-MNIST: a Novel Image Dataset for Benchmarking Machine Learning Algorithms.
  5. Cohen, G., Afshar, S., Tapson, J., & van Schaik, A. (2017). EMNIST: an extension of MNIST to handwritten letters.
  6. torchvision.datasets.MNIST (PyTorch documentation).