---
title: "Reading Handwritten Digits"
code-links:
  - text: Quarto source
    href: handwritten-digits.qmd
    icon: file-code
---

In the 1990s, banks still read the amount on every check by hand. @lecun1998gradient describe a neural network system that did it instead: it was in commercial use in NCR's check recognition systems and read millions of checks in banks across the United States. To train their networks, they built a database of 70,000 handwritten digits from two collections of the National Institute of Standards and Technology (NIST), one written by Census Bureau employees and one by high school students. They called it the Modified NIST database, or MNIST, and it has been the first data set of nearly every course on neural networks since.

This notebook trains two models to read those digits: a linear classifier, the analog of a linear regression, and a network with one hidden layer. The network makes about a third as many mistakes. Looking at the weights of both shows why.

## Packages

PyTorch is the library we use to build and train networks.

```{python}
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import requests
import torch
import torch.nn as nn

# Small networks train faster on a few threads than on all cores
torch.set_num_threads(4)
```

## The digits

A copy of MNIST is kept as a single file of 11 MB. We download it once and save it.

```{python}
DATA = Path("../_data") if Path("../_data").exists() else Path("data")
file = DATA / "mnist.npz"
if not file.exists():
    url = "https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz"
    DATA.mkdir(exist_ok=True)
    file.write_bytes(requests.get(url, timeout=60).content)

with np.load(file) as f:
    images_train, labels_train = f["x_train"], f["y_train"]
    images_test, labels_test = f["x_test"], f["y_test"]
print(images_train.shape, images_test.shape)
```

There are 60,000 training digits and 10,000 test digits, written by different people. Each is an image of $28 \times 28$ pixels, and each pixel is a number from 0 (white) to 255 (black). The label says which digit it is.

```{python}
#| fig-alt: "Twenty-four handwritten digits from the MNIST training set in a grid of three rows, each with its label above it. The digits vary in slant, thickness and shape."
fig, axes = plt.subplots(3, 8, figsize=(8, 3.4))
for ax, image, label in zip(axes.flat, images_train, labels_train):
    ax.imshow(image, cmap="gray_r")
    ax.set_title(label, fontsize=9)
    ax.axis("off")
plt.show()
```

For a model, an image is a list of $28 \times 28 = 784$ numbers. We flatten each image into a row of 784 inputs and divide by 255, so that every input lies between 0 and 1.

```{python}
X_train = torch.tensor(images_train.reshape(-1, 784) / 255, dtype=torch.float32)
X_test = torch.tensor(images_test.reshape(-1, 784) / 255, dtype=torch.float32)
y_train = torch.tensor(labels_train, dtype=torch.long)
y_test = torch.tensor(labels_test, dtype=torch.long)
```

## From regression to classification

A regression predicts one number. Here the answer is one of ten digits, so the model produces ten numbers, one *score* per digit, and its answer is the digit with the highest score. The *softmax* function turns the scores $s_0, \ldots, s_9$ into probabilities that are positive and add up to one,
$$
p_k = \frac{e^{s_k}}{e^{s_0} + e^{s_1} + \cdots + e^{s_9}}.
$$
Training needs a loss to minimize, as the squared error was for regression. The usual one is the *cross-entropy*: for a digit whose label is $y$, the loss is $-\ln p_y$, which is zero when the model gives the right digit probability one and grows without bound as that probability falls to zero. PyTorch's `cross_entropy` computes the softmax and the loss together from the scores.

With 60,000 images, computing the gradient on all of them for every step would be slow. Instead, each step uses a *minibatch* of 128 images drawn at random, which gives a noisy but cheap estimate of the gradient. One pass through all the training images in minibatches is an *epoch*. The function `train` does this for any model and reports the share of digits it reads correctly, its *accuracy*, after each epoch.

```{python}
def accuracy(net, X, y):
    with torch.no_grad():
        return (net(X).argmax(dim=1) == y).float().mean().item()


def train(net, epochs=5, batch_size=128):
    torch.manual_seed(0)
    opt = torch.optim.Adam(net.parameters(), lr=0.001)
    for epoch in range(epochs):
        order = torch.randperm(len(X_train))
        for start in range(0, len(X_train), batch_size):
            rows = order[start:start + batch_size]
            opt.zero_grad()
            loss = nn.functional.cross_entropy(net(X_train[rows]), y_train[rows])
            loss.backward()
            opt.step()
        print(f"Epoch {epoch + 1}: accuracy {accuracy(net, X_train, y_train):.3f} on the training digits, "
              f"{accuracy(net, X_test, y_test):.3f} on the test digits")
```

## A linear classifier

The simplest model computes each digit's score as a weighted sum of the 784 pixels plus an intercept, ten linear regressions side by side. In PyTorch it is a single linear layer with 784 inputs and 10 outputs.

```{python}
torch.manual_seed(0)
linear = nn.Linear(784, 10)
train(linear)
```

The linear classifier reads about 92% of the test digits correctly. Its weights can be drawn as images: for each digit, the 784 weights of its score, in the positions of the pixels they multiply. Ink on a red pixel raises the digit's score and ink on a blue one lowers it.

```{python}
#| fig-alt: "Ten 28 by 28 weight images, one for each digit from 0 to 9, colored red for positive and blue for negative weights. Some show a blurry outline of their digit, such as a ring around a blue center for 0 and a slanted red stroke for 1; others are harder to recognize."
weights = linear.weight.detach().numpy()
limit = np.abs(weights).max()
fig, axes = plt.subplots(1, 10, figsize=(10, 1.6))
for digit, ax in enumerate(axes):
    ax.imshow(weights[digit].reshape(28, 28), cmap="RdBu_r", vmin=-limit, vmax=limit)
    ax.set_title(digit, fontsize=9)
    ax.axis("off")
plt.show()
```

Each digit's weights act as a template, and some of them look like a blurred version of the digit: a ring with a blue hole for the 0, a slanted stroke for the 1. Others are harder to read, because each template is also shaped to lower the scores of the digits it could be confused with. A linear classifier can only ask how much of the ink falls where that template expects it. A 4 written with a closed top, or a 7 with a crossbar, matches the template of another digit better than its own, and nothing in the model can combine features, such as "a loop at the top *and* a stroke on the right," into a decision.

## A network with one hidden layer

The network puts a hidden layer of 128 units with the ReLU activation between the pixels and the scores. Each hidden unit computes its own weighted sum of the pixels, and the scores are weighted sums of the hidden units.

```{python}
torch.manual_seed(0)
net = nn.Sequential(
    nn.Linear(784, 128),
    nn.ReLU(),
    nn.Linear(128, 10),
)
train(net)
```

The network reads about 97% of the test digits correctly. Its error rate is about a third of the linear classifier's: 2.8% against 7.8%. @lecun1998gradient report the same ranking, with test errors of 12.0% for a linear classifier and 4.7% for a network with one hidden layer of 300 units; the training methods available today do better with both.

The first-layer weights of a hidden unit can be drawn in the same way. They are not templates of whole digits. Each unit responds to a pattern of strokes, a curve in one place or a gap in another, and the second layer combines the units into scores. Because a unit is zero until its weighted sum turns positive, the network can respond to combinations of patterns, which the linear classifier cannot.

```{python}
#| fig-alt: "Sixteen 28 by 28 weight images of hidden units in two rows, colored red for positive and blue for negative weights. They show scattered patches and stroke-like patterns rather than whole digits."
hidden = net[0].weight.detach().numpy()
fig, axes = plt.subplots(2, 8, figsize=(8, 2.4))
for unit, ax in enumerate(axes.flat):
    limit = np.abs(hidden[unit]).max()
    ax.imshow(hidden[unit].reshape(28, 28), cmap="RdBu_r", vmin=-limit, vmax=limit)
    ax.axis("off")
plt.show()
```

## The mistakes

Which digits does the network still get wrong? Here are some of them, with the label and the network's answer.

```{python}
#| fig-alt: "Sixteen test digits the network misread, each titled with its true label and the network's answer. Some are ambiguous even to a person, such as a 6 with an open loop read as 0 or a thin 8 read as 2; others, such as a clear 0 read as 9, are plain mistakes."
with torch.no_grad():
    predicted = net(X_test).argmax(dim=1).numpy()
wrong = np.flatnonzero(predicted != labels_test)
print(f"{len(wrong)} of {len(labels_test)} test digits misread")

fig, axes = plt.subplots(2, 8, figsize=(8, 2.8))
for ax, i in zip(axes.flat, wrong):
    ax.imshow(images_test[i], cmap="gray_r")
    ax.set_title(f"{labels_test[i]} read as {predicted[i]}", fontsize=8)
    ax.axis("off")
plt.show()
```

Some of the mistakes are digits a person would hesitate over too; others, such as the clear 0 read as 9, are plain errors that a better model avoids. The most common confusions:

```{python}
mistakes = pd.DataFrame({"label": labels_test[wrong], "read as": predicted[wrong]})
mistakes.value_counts().head(6).rename("count").reset_index()
```

## What we learned

- A classifier produces one score per class. Softmax turns the scores into probabilities, and training minimizes the cross-entropy, the negative log probability of the right answer.
- With large data sets, gradient descent works on minibatches: many cheap, noisy steps instead of a few exact ones.
- A linear classifier can only match each image against one template per digit. A hidden layer of ReLU units responds to combinations of features, and on these digits it cuts the error rate by about two thirds.
- The training and test accuracies are close, so the network has learned how digits are written rather than memorizing these particular images. This is the opposite of the problem we will meet with financial data, where a little signal hides in a lot of noise.

## Try it

1. Train networks with 16 and with 512 hidden units. How does the test accuracy change, and how long does training take?
2. Add a second hidden layer of 64 units. Does the test accuracy improve?
3. Train the network on the first 1,000 training digits only, for 50 epochs. Compare the training and test accuracy with those above. What happened?
4. Write a digit on paper, photograph it, and turn it into a $28 \times 28$ image of numbers between 0 and 1 with white as 0, centered like the MNIST digits. What does the network read? Ask Claude to help with the image processing, and look at your image before trusting the answer.
