Lessons › Projects
A neural network that reads handwriting
A multilayer neural network that reads handwritten digits, plus an image of the digits it got wrong.
No setup needed. Run every step in your browser on Gradient Lab, or download it.
Open the notebookLevel: Intermediate · Time: 35 min · You’ll practise: images as numbers, hidden layers, ReLU and Adam, error analysis
Steps
1. Images are just numbers: each digit is an 8x8 grid of brightness values
Load 1,797 tiny 8 × 8 images of handwritten digits and print one as a grid of numbers.
digits = load_digits()
print("Images:", digits.images.shape, " -> flattened:", digits.data.shape)
print("The first image, as numbers:\n", digits.images[0].astype(int))2. Split and scale
Split into training and test sets and scale the pixel values.
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.25, random_state=0, stratify=digits.target) scaler = StandardScaler().fit(X_train) X_train, X_test = scaler.transform(X_train), scaler.transform(X_test)
3. A network with two hidden layers (64 and 32 neurons), ReLU, Adam
Train a network with two hidden layers (64 and 32 neurons), ReLU activations and the Adam optimizer.
net = MLPClassifier(hidden_layer_sizes=(64, 32), activation="relu", solver="adam", max_iter=400, random_state=0)
net.fit(X_train, y_train)
print(f"Training finished after {net.n_iter_} epochs, final loss {net.loss_:.3f}")
print(f"Test accuracy: {net.score(X_test, y_test):.1%}")4. Which digits get confused?
Find which pair of digits it confuses most often.
cm = confusion_matrix(y_test, net.predict(X_test))
np.fill_diagonal(cm, 0)
i, j = np.unravel_index(cm.argmax(), cm.shape)
print(f"Most common mistake: a {i} read as a {j} ({cm[i, j]} times)")5. Look at some mistakes
Save the misread images so you can see why some are genuinely hard.
wrong = np.where(net.predict(X_test) != y_test)[0][:8]
fig, axes = plt.subplots(1, len(wrong), figsize=(2 * len(wrong), 2.4))
for ax, k in zip(np.atleast_1d(axes), wrong):
ax.imshow(scaler.inverse_transform(X_test[k:k + 1]).reshape(8, 8), cmap="gray_r")
ax.set_title(f"true {y_test[k]}\nread {net.predict(X_test[k:k + 1])[0]}"); ax.axis("off")
plt.tight_layout(); plt.savefig("mistakes.png"); print("Saved mistakes.png")Expected output
$ python digit_reader.py Images: (1797, 8, 8) -> flattened: (1797, 64) The first image, as numbers: [[ 0 0 5 13 9 1 0 0] [ 0 0 13 15 10 15 5 0] [ 0 3 15 2 0 11 8 0] [ 0 4 12 0 0 8 8 0] [ 0 5 8 0 0 9 8 0] [ 0 4 11 0 1 12 7 0] [ 0 2 14 5 10 12 0 0] [ 0 0 6 13 10 0 0 0]] Training finished after 113 epochs, final loss 0.003 Test accuracy: 96.4% Most common mistake: a 6 read as a 1 (2 times) Saved mistakes.png
Stretch goals
- Change the hidden layer sizes and plot accuracy against size.
- Add
alpha=0.01(L2 regularization) and compare. - Rebuild it as a small CNN in PyTorch on the full MNIST dataset.