Skip to main content

AI and machine learning · Intermediate · 25 min

Train a small convolutional network to read handwritten digits

By Padding · Updated 18 Nov 2026
Python 3.15 (python:3.15-slim) · PyTorch 2.15.0 (CPU) · scikit-learn 1.9.1

You will train a two-layer convolutional network in PyTorch on scikit-learn's bundled 8x8 digits, compare it with logistic regression, read its confusion matrix and mistakes, and make it robust to shifted digits with data augmentation.

On this page

A logistic regression on raw pixels treats an image as a list of unrelated numbers. Move a digit one pixel to the left and, to that model, almost every input has changed. A convolutional network (CNN) instead slides small filters across the image, so a stroke or a corner is recognised wherever it sits, and pooling throws away a little of the exact position on purpose. That is the whole idea behind image models, from reading meter photos to checking scanned forms.

In this tutorial you train a small CNN on scikit-learn's handwritten digits dataset: 1,797 greyscale digits of 8x8 pixels that ship inside scikit-learn, so there is nothing to download and every run uses the same data. You build a baseline with logistic regression first, then a two-layer CNN that trains on a laptop CPU in seconds. You read the confusion matrix, look at the digits it gets wrong, and then test both models on digits shifted by one pixel, which is where the CNN, trained with a little data augmentation, earns its keep.

Training uses random numbers, so your accuracy figures may differ from the ones shown in the third decimal place. The checks in each step use ranges, not exact values.

Step 1 · Set up the project

Create a throwaway project folder and a virtual environment:

Bash
mkdir -p ~/digits-cnn-demo
cd ~/digits-cnn-demo
python3 -m venv .venv
source .venv/bin/activate

Install PyTorch from its CPU-only index first, so pip does not fetch the much larger GPU build, then scikit-learn:

Bash
pip install --quiet torch==2.15.0 --index-url https://download.pytorch.org/whl/cpu
pip install --quiet scikit-learn==1.9.1

The PyTorch wheel is a few hundred megabytes. If you are on prepaid mobile data, run this step on Wi-Fi; it is a one-off, and nothing later in the tutorial downloads anything.

Check it worked

Bash
python -c "import torch, sklearn; print(torch.__version__, sklearn.__version__)"

The output is 2.15.0+cpu 1.9.1 on Linux, or 2.15.0 1.9.1 on macOS, where the default wheel is already CPU-only.

Step 2 · Load and look at the digits

Every script in this tutorial needs the same train and test split, so put it in one module. load_split scales the pixel values from 0–16 down to 0–1, which keeps the network's inputs small, and holds back 20% of the images for testing. stratify keeps the same share of each digit in both halves. draw prints an image as text, two characters per pixel, so you can see digits in a terminal over SSH:

Bash
cat > digits_data.py <<'PY'
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

SHADES = " .:-=+*#%@"


def load_split():
    digits = load_digits()
    images = (digits.images / 16.0).astype(np.float32)
    return train_test_split(
        images, digits.target, test_size=0.2, stratify=digits.target, random_state=0
    )


def draw(image):
    rows = []
    for row in image:
        rows.append("".join(SHADES[min(int(v * 9.99), 9)] * 2 for v in row))
    return "\n".join(rows)
PY

Now a short script that prints the shapes, the class balance and one digit:

Bash
cat > explore.py <<'PY'
from collections import Counter

from digits_data import draw, load_split

X_train, X_test, y_train, y_test = load_split()
print("train:", X_train.shape, "test:", X_test.shape)
print("pixel range:", X_train.min(), "to", X_train.max())
print("test digits per class:", dict(sorted(Counter(y_test.tolist()).items())))
print(f"\nlabel {y_train[0]}:")
print(draw(X_train[0]))
PY
python explore.py

Check it worked

The first lines read:

Text
train: (1437, 8, 8) test: (360, 8, 8)
pixel range: 0.0 to 1.0

The class counts are all 35 to 37, and below them is a digit drawn in characters, darkest pixels as @. At 8x8 pixels the digits are coarse, which makes this a quick dataset to learn on, and a harder one than its size suggests: some 1s and 8s are only a few pixels apart.

Bash
python explore.py | grep -q "train: (1437, 8, 8) test: (360, 8, 8)" && echo "shapes OK"

Step 3 · Set a baseline with logistic regression

Before training a network, find out what a plain model manages. Logistic regression needs one flat row per image, so each 8x8 grid becomes 64 numbers:

Bash
cat > baseline.py <<'PY'
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

from digits_data import load_split

X_train, X_test, y_train, y_test = load_split()
flat_train = X_train.reshape(len(X_train), -1)
flat_test = X_test.reshape(len(X_test), -1)

clf = LogisticRegression(max_iter=2000)
clf.fit(flat_train, y_train)
acc = accuracy_score(y_test, clf.predict(flat_test))
print(f"inputs per image: {flat_train.shape[1]}")
print(f"logistic regression test accuracy: {acc:.3f}")
PY
python baseline.py

Check it worked

The script prints inputs per image: 64 and a test accuracy of about 0.967 (348 of 360 test digits). That is a strong baseline: these digits are centred and size-normalised, so pixel positions alone carry most of the signal. Keep the number; the CNN has to beat it to be worth its extra code.

Bash
python baseline.py | python -c "import sys; acc = float(sys.stdin.read().split()[-1]); assert 0.93 < acc < 1.0, acc; print('baseline OK', acc)"

Step 4 · Build the network

The network has two blocks of convolution, ReLU and max pooling, then one linear layer that turns what is left into ten scores, one per digit:

  • Conv2d(1, 16, kernel_size=3, padding=1) learns 16 filters of 3x3 pixels. padding=1 adds a blank border so the output stays 8x8.
  • MaxPool2d(2) keeps the largest value in each 2x2 patch, halving the height and width. This is where the network starts to stop caring about the exact pixel.
  • The second block does the same with 32 filters, so the image ends as 32 channels of 2x2, or 128 numbers.
  • Linear(128, 10) gives the ten raw scores (logits). There is no softmax at the end, because the loss function in the next step applies it.
Bash
cat > model.py <<'PY'
import torch
from torch import nn


class DigitCNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv2d(1, 16, kernel_size=3, padding=1),  # 1x8x8 -> 16x8x8
            nn.ReLU(),
            nn.MaxPool2d(2),  # -> 16x4x4
            nn.Conv2d(16, 32, kernel_size=3, padding=1),  # -> 32x4x4
            nn.ReLU(),
            nn.MaxPool2d(2),  # -> 32x2x2
        )
        self.classify = nn.Sequential(nn.Flatten(), nn.Linear(32 * 2 * 2, 10))

    def forward(self, x):
        return self.classify(self.features(x))


if __name__ == "__main__":
    model = DigitCNN()
    batch = torch.zeros(5, 1, 8, 8)
    print("output shape:", tuple(model(batch).shape))
    print("parameters:", sum(p.numel() for p in model.parameters()))
PY
python model.py

PyTorch's convolution layers expect four dimensions: batch, channels, height and width. A greyscale image has one channel, which is why the test batch is (5, 1, 8, 8).

Check it worked

The output is:

Text
output shape: (5, 10)
parameters: 6090

Five images in, ten scores each out. The parameter count is 160 for the first convolution (16 filters of 3x3, plus a bias each), 4,640 for the second, and 1,290 for the linear layer. The logistic regression had 650 (64 weights and a bias for each of the ten digits), so the CNN is bigger but still tiny.

Bash
python model.py | grep -q "output shape: (5, 10)" && python model.py | grep -q "parameters: 6090" && echo "model OK"

Step 5 · Train the network

train.py turns the arrays into tensors, adds the channel axis with unsqueeze(1), and trains with the Adam optimiser on shuffled batches of 64 for 30 epochs. It prints the loss and test accuracy every five epochs, then saves the weights (the state_dict) and a small JSON file with the final accuracy. The --augment flag and the shift function are for the last step; leave them alone for now:

Bash
cat > train.py <<'PY'
import argparse
import json
import time

import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader, TensorDataset

from digits_data import load_split
from model import DigitCNN

parser = argparse.ArgumentParser()
parser.add_argument("--epochs", type=int, default=30)
parser.add_argument("--augment", action="store_true")
parser.add_argument("--out", default="cnn.pt")
args = parser.parse_args()

torch.manual_seed(0)
X_train, X_test, y_train, y_test = load_split()
# Conv2d wants (batch, channels, height, width): add a channel axis of size 1.
train_x = torch.from_numpy(X_train).unsqueeze(1)
test_x = torch.from_numpy(X_test).unsqueeze(1)
train_y = torch.from_numpy(y_train)
test_y = torch.from_numpy(y_test)

loader = DataLoader(TensorDataset(train_x, train_y), batch_size=64, shuffle=True)


def shift(batch):
    # Pad one blank pixel on every side, then cut a random 8x8 window back out:
    # each image moves up to one pixel in any direction.
    padded = F.pad(batch, (1, 1, 1, 1))
    out = torch.empty_like(batch)
    for i in range(len(batch)):
        dy, dx = torch.randint(0, 3, (2,)).tolist()
        out[i] = padded[i, :, dy : dy + 8, dx : dx + 8]
    return out


def accuracy(model, x, y):
    model.eval()
    with torch.no_grad():
        return (model(x).argmax(dim=1) == y).float().mean().item()


model = DigitCNN()
optimiser = torch.optim.Adam(model.parameters(), lr=0.003)
start = time.perf_counter()
for epoch in range(1, args.epochs + 1):
    model.train()
    total = 0.0
    for xb, yb in loader:
        if args.augment:
            xb = shift(xb)
        loss = F.cross_entropy(model(xb), yb)
        optimiser.zero_grad()
        loss.backward()
        optimiser.step()
        total += loss.item() * len(xb)
    if epoch == 1 or epoch % 5 == 0:
        print(f"epoch {epoch:2d}  loss {total / len(train_x):.4f}  "
              f"test accuracy {accuracy(model, test_x, test_y):.3f}")

seconds = time.perf_counter() - start
acc = accuracy(model, test_x, test_y)
torch.save(model.state_dict(), args.out)
print(f"trained in {seconds:.1f} s, test accuracy {acc:.3f}, saved {args.out}")
with open(args.out.replace(".pt", ".json"), "w") as f:
    json.dump({"accuracy": acc, "seconds": seconds}, f)
PY
python train.py

Three details matter here. F.cross_entropy takes the raw scores and applies softmax itself, which is why the model has none. In accuracy, eval() switches layers such as dropout and batch norm to their inference behaviour (this model has none, but the habit matters), and no_grad() skips building the gradient graph, which saves memory and time. Only optimiser.step() changes the weights. And the test accuracy printed during training is only for watching progress; if you used it to pick the number of epochs, you would need a separate validation set to report an honest final figure, as the training loop tutorial shows.

Check it worked

The loss falls quickly, from about 2.2 after the first epoch to around 0.01 by the end, and the final line reads something like:

Text
trained in 3.5 s, test accuracy 0.981, saved cnn.pt

Training takes a few seconds on a recent laptop and well under a minute on a small cloud server. The CNN usually lands a little above the logistic regression on this clean test set; the gap is small because the baseline is already good. cnn.pt and cnn.json are now in the folder:

Bash
python -c "import json; acc = json.load(open('cnn.json'))['accuracy']; assert acc > 0.95, acc; print('cnn OK', round(acc, 3))"
ls -l cnn.pt

Step 6 · Read the confusion matrix and the mistakes

An accuracy figure hides which digits get mixed up. mistakes.py loads the saved weights into a fresh model, predicts the test set, prints the confusion matrix, then draws the first three digits it got wrong. Rows are the true digit and columns the prediction, so everything off the diagonal is an error. weights_only=True tells torch.load to read only tensors, not arbitrary Python objects; only load weight files you trust all the same.

Bash
cat > mistakes.py <<'PY'
import sys

import torch
from sklearn.metrics import confusion_matrix

from digits_data import draw, load_split
from model import DigitCNN

path = sys.argv[1] if len(sys.argv) > 1 else "cnn.pt"
X_train, X_test, y_train, y_test = load_split()
model = DigitCNN()
model.load_state_dict(torch.load(path, weights_only=True))
model.eval()
with torch.no_grad():
    predicted = model(torch.from_numpy(X_test).unsqueeze(1)).argmax(dim=1).numpy()

print("rows: true digit, columns: predicted digit")
print("    " + " ".join(f"{d:3d}" for d in range(10)))
for digit, row in enumerate(confusion_matrix(y_test, predicted)):
    print(f"{digit:3d} " + " ".join(f"{n:3d}" for n in row))

wrong = [i for i in range(len(y_test)) if predicted[i] != y_test[i]]
print(f"\n{len(wrong)} of {len(y_test)} test digits wrong")
for i in wrong[:3]:
    print(f"\ntrue {y_test[i]}, predicted {predicted[i]}:")
    print(draw(X_test[i]))
PY
python mistakes.py

Check it worked

You see a 10x10 grid with large numbers (32 to 37) on the diagonal and mostly zeros elsewhere, then a line such as 7 of 360 test digits wrong, then up to three drawn digits with their true and predicted labels. In the run behind this tutorial, most errors involved 8: two 8s were read as 1, and a 3 and a 1 were read as 8. Thin strokes at 8x8 pixels make an 8 and a heavy 1 look alike. Some of the mistakes are digits a person would hesitate over too; others are clear to you and point at what the model has not learned. Before you trust a model like this for real forms, look at its mistakes this way, not only at its accuracy.

Bash
python mistakes.py | grep -E "^[0-9]+ of 360 test digits wrong"

Step 7 · Make the network robust to shifted digits

Real handwriting is not always centred. To see what happens when it is not, shifted_test.py moves every test digit by one pixel up, down, left and right (four shifted copies, 1,440 images) and scores the logistic regression and any saved CNNs on them:

Bash
cat > shifted_test.py <<'PY'
import sys

import numpy as np
import torch
from sklearn.linear_model import LogisticRegression

from digits_data import load_split
from model import DigitCNN

X_train, X_test, y_train, y_test = load_split()


def move(images, dy, dx):
    # Shift every image by (dy, dx) pixels, filling the gap with blank pixels.
    out = np.zeros_like(images)
    h, w = images.shape[1:]
    out[:, max(dy, 0) : h + min(dy, 0), max(dx, 0) : w + min(dx, 0)] = images[
        :, max(-dy, 0) : h + min(-dy, 0), max(-dx, 0) : w + min(-dx, 0)
    ]
    return out


shifted = np.concatenate([move(X_test, dy, dx) for dy, dx in [(1, 0), (-1, 0), (0, 1), (0, -1)]])
shifted_y = np.tile(y_test, 4)

clf = LogisticRegression(max_iter=2000).fit(X_train.reshape(len(X_train), -1), y_train)
lr_acc = (clf.predict(shifted.reshape(len(shifted), -1)) == shifted_y).mean()
print(f"{'logistic regression':<20} {lr_acc:.3f}")

for path in sys.argv[1:]:
    model = DigitCNN()
    model.load_state_dict(torch.load(path, weights_only=True))
    model.eval()
    with torch.no_grad():
        pred = model(torch.from_numpy(shifted).unsqueeze(1)).argmax(dim=1).numpy()
    print(f"{path:<20} {(pred == shifted_y).mean():.3f}")
PY
python shifted_test.py cnn.pt

Both models drop: about 0.42 for the logistic regression and about 0.66 for the CNN. The CNN holds up better because of its filters and pooling, but it has only ever seen centred digits.

Data augmentation fixes that by showing the network varied copies of the training images. The shift function in train.py pads each image with a one-pixel border and cuts a random 8x8 window back out, so every batch moves each digit by up to one pixel in a random direction. The labels stay the same, and the test set is untouched. Augmented data is harder to fit, so train for longer:

Bash
python train.py --augment --epochs 60 --out cnn_aug.pt
python shifted_test.py cnn.pt cnn_aug.pt

Choose augmentations that keep the label true. Shifting by a pixel is safe for digits; flipping left to right is not, because it changes what some digits are, and a 6 rotated half a turn is a 9.

Check it worked

The training log ends with a clean-test accuracy close to the first CNN's, and the second table shows cnn_aug.pt well ahead of both other models on the shifted digits, at about 0.97:

Text
logistic regression  0.422
cnn.pt               0.660
cnn_aug.pt           0.973
Bash
python shifted_test.py cnn.pt cnn_aug.pt > shifted.txt
cat shifted.txt
python - <<'PY'
scores = {line.rsplit(None, 1)[0]: float(line.rsplit(None, 1)[1]) for line in open("shifted.txt")}
assert scores["cnn_aug.pt"] > scores["cnn.pt"], scores
assert scores["cnn_aug.pt"] > scores["logistic regression"], scores
print("augmentation helps on shifted digits")
PY

Taking the same code to MNIST

MNIST, the classic digits benchmark, has 60,000 training and 10,000 test images of 28x28 pixels. The model and the training loop carry over; the data loading and the shift function need rewriting for 28x28 images. In full:

  • Install torchvision, which provides the dataset, from the same CPU index as PyTorch:
Bash
pip install torchvision==0.29.2 --index-url https://download.pytorch.org/whl/cpu
  • Load the data with torchvision.datasets.MNIST(root="data", train=True, download=True, transform=transforms.ToTensor()), and the same with train=False for the test set. It is about 12 MB to download and around 55 MB once extracted, so plan for it on metered data. The images arrive through a Dataset, not load_split(), and their pixels are 0 to 255; transforms.ToTensor() scales them to 0 to 1 and adds the channel axis, so every unsqueeze(1) call goes. Pass the datasets straight to DataLoader, and measure test accuracy batch by batch rather than on one tensor of 10,000 images.
  • Rewrite shift(): it hard-codes the 8x8 window (dy : dy + 8, dx : dx + 8), so it breaks on 28x28 images. Take the window size from the batch (batch.shape[-2:]) and pad by two or three pixels instead of one, drawing dy and dx from 0 to twice the pad.
  • Change the final layer's input from 32 * 2 * 2 to 32 * 7 * 7, because two 2x2 poolings take 28 pixels down to 7.
  • Expect each epoch to take tens of seconds on a CPU instead of a fraction of one, so a few epochs are enough to start.

When you have finished, remove the project:

Bash
deactivate
cd ~
rm -rf ~/digits-cnn-demo
ls ~/digits-cnn-demo 2>/dev/null || echo "removed"

The last command prints removed.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.