Project: MNIST with your own library
Last updated
MNIST is the dataset that made handwritten digit recognition famous: 70,000 digits, each 28×28 pixels, twelve times the detail of scikit-learn’s 8×8 ones. In this project you’ll train a network on it with simplenet, the library you wrote, and get above 95% of digits right that it has never seen. It’s the first project you run on your own computer: the data has to be downloaded, and a page can’t do that. Every number below is what the scripts printed when we ran them.
By the end of this lesson you can
- Download MNIST, keep a 10,000-image subset, and split it into training and validation sets
- Train simplenet MLPs on 784 inputs and tune the width and learning rate on the validation set
- Report the test accuracy once, above 95%, and look at the mistakes
Plan it
The question: can the library you wrote in lessons 6.7 and 6.8 learn real handwriting, at full size?
The data: MNIST. 60,000 training digits and 10,000 test digits, written by different people, each a 28×28 greyscale image: 784 pixels.
What you'll make: three scripts, in a folder called 06-mnist inside ml-course, beside a copy of simplenet.py:
load.pydownloads MNIST, keeps a random 10,000 of the training digits (8,000 to train, 2,000 to validate), and saves them, with the test set, to one file;train.pytrains networks of three widths at three learning rates, and prints each one's validation accuracy;final.pychooses how long to train, reports the test accuracy once, and draws 20 mistakes.
Why 10,000 and not all 60,000? simplenet runs on NumPy, on the CPU, and a subset keeps each run to seconds while you tune. More data would do better; that's one of the things to try at the end.
The goal: above 95% on the test set.
You'll run these on your own computer, in the environment from lesson 0.10, which already has NumPy, matplotlib and scikit-learn. All four files, ready to run:
06-mnist/final.py35 lines06-mnist/load.py22 lines06-mnist/simplenet.py338 lines06-mnist/train.py35 lines
Or make them yourself as you go, copying your own simplenet.py from lesson 6.8 or the one in the download. Open a terminal in the 06-mnist folder, with the environment active, to run them.
Load the subset
"""Step 2: download MNIST once, keep 10,000 training images, and split off a validation set.""" import numpy as np from sklearn.datasets import fetch_openml # The first call downloads MNIST from openml.org; later calls read the copy saved on disk. # parser="liac-arff": with scikit-learn 1.9 and pandas 3, the default parser fails on this file. X, y = fetch_openml("mnist_784", version=1, as_frame=False, return_X_y=True, parser="liac-arff") X = X.astype(np.float32) / 255 # pixels from 0 to 1 y = y.astype(int) # labels arrive as strings: "5" print("all of MNIST:", X.shape, y.shape) rng = np.random.default_rng(0) pick = rng.choice(60_000, size=10_000, replace=False) # 10,000 of the 60,000 training images X_train, y_train = X[pick[:8_000]], y[pick[:8_000]] X_val, y_val = X[pick[8_000:]], y[pick[8_000:]] X_test, y_test = X[60_000:], y[60_000:] # MNIST's own test set: 10,000 other images print("train", X_train.shape, " validation", X_val.shape, " test", X_test.shape) print("images of each digit in train:", np.bincount(y_train)) np.savez_compressed("mnist-subset.npz", X_train=X_train, y_train=y_train, X_val=X_val, y_val=y_val, X_test=X_test, y_test=y_test) print("saved mnist-subset.npz")
(.venv) $ python load.py all of MNIST: (70000, 784) (70000,) train (8000, 784) validation (2000, 784) test (10000, 784) images of each digit in train: [798 909 792 823 770 737 806 820 756 789] saved mnist-subset.npz
The first run downloads about 15 MB from OpenML and keeps it in a scikit_learn_data folder in your home folder, so later runs start in seconds.
Things to notice:
- The pixels arrive as numbers from 0 to 255; dividing by 255 scales them to 0–1, as the 8×8 digits were scaled in lesson 6.9.
- The labels arrive as strings,
"5", soastype(int)makes them numbers forcross_entropy. - The subset is a random sample, so every digit appears about 800 times: no digit is left out.
- The test set is MNIST's own: 10,000 images by different writers from the training images, so it's a fair test of new handwriting.
parser="liac-arff"is there because we checked: with scikit-learn 1.9 and pandas 3, the default parser stops with aTypeErroron this file. A slower parser that works beats a fast one that doesn't.
np.savez_compressed saves all six arrays to one file. Loading it takes a moment, so the next two scripts don't repeat the download or the sampling, and they all use exactly the same split.
Model and training loop
The training loop is lesson 6.9's, with batches of 64. The network is MLP([784, width, 10]): 784 pixels in, one hidden ReLU layer, 10 logits out. The first half of train.py defines it as a function, train(width, lr, epochs), so the next step can call it with different settings and final.py can import it:
"""Steps 3 and 4: train simplenet MLPs on the subset, and tune the width and the learning rate.""" import numpy as np from simplenet import MLP, SGD, Tensor, cross_entropy data = np.load("mnist-subset.npz") # made by load.py X_train, y_train = data["X_train"], data["y_train"] X_val, y_val = data["X_val"], data["y_val"] def accuracy(model, X, y): return (model(Tensor(X)).data.argmax(axis=1) == y).mean() def train(width, lr, epochs, seed=0): rng = np.random.default_rng(seed) model = MLP([784, width, 10], rng) optimizer = SGD(model.parameters(), lr=lr) for epoch in range(epochs): order = rng.permutation(len(X_train)) for start in range(0, len(order), 64): batch = order[start:start + 64] loss = cross_entropy(model(Tensor(X_train[batch])), y_train[batch]) optimizer.zero_grad() loss.backward() optimizer.step() return model if __name__ == "__main__": print("width lr validation accuracy after 10 epochs") for width in (32, 128, 256): for lr in (0.1, 0.3, 0.5): model = train(width, lr, epochs=10) print(f"{width:5} {lr:6} {accuracy(model, X_val, y_val):.3f}")
if __name__ == "__main__": runs the grid only when you run train.py itself, not when final.py imports train from it (Simple Python, lesson 2.7).
Tune the width and the learning rate
Run it. Nine networks, 10 epochs each, scored on the validation set:
(.venv) $ python train.py width lr validation accuracy after 10 epochs 32 0.1 0.918 32 0.3 0.940 32 0.5 0.937 128 0.1 0.927 128 0.3 0.949 128 0.5 0.955 256 0.1 0.928 256 0.3 0.948 256 0.5 0.953
It takes under a minute on an ordinary laptop. Read the table by rows and columns:
- Learning rate matters most. At 0.1, every width is far behind (91.8% to 92.8%): steps that small haven't got far in 10 epochs. At 0.3 and 0.5 they've gone much further.
- 32 units is too narrow. Its best, 94.0%, is below every wider network at the same learning rate.
- 128 and 256 are about the same, 95.5% and 95.3% at 0.5. Twice the width costs twice the time and buys nothing here.
So: 128 units, learning rate 0.5. Every choice was made on the validation set; the test set hasn't been touched.
Report the test accuracy, once
One choice is left: how many epochs. final.py trains for 10, 20 and 30, keeps the run with the best validation score, and only then measures it on the test set:
"""Steps 5 and 6: train the chosen network for longer, test it once, and look at its mistakes.""" import matplotlib.pyplot as plt import numpy as np from simplenet import Tensor from train import X_val, accuracy, data, train, y_val X_test, y_test = data["X_test"], data["y_test"] best = None for epochs in (10, 20, 30): model = train(width=128, lr=0.5, epochs=epochs) score = accuracy(model, X_val, y_val) print(f"{epochs} epochs: validation accuracy {score:.3f}") if best is None or score > best[0]: # a tie keeps the shorter run best = (score, epochs, model) score, epochs, model = best print(f"chosen: {epochs} epochs") # Every choice is made, so now, once: the test set. print(f"test accuracy: {accuracy(model, X_test, y_test):.3f}") pred = model(Tensor(X_test)).data.argmax(axis=1) wrong = np.flatnonzero(pred != y_test) print(f"{len(wrong)} mistakes in {len(y_test)} test images") print("first 20, as true -> said:", ", ".join(f"{y_test[i]}->{pred[i]}" for i in wrong[:20])) fig, axes = plt.subplots(2, 10, figsize=(12, 3)) for ax, i in zip(axes.flat, wrong[:20]): ax.imshow(X_test[i].reshape(28, 28), cmap="gray_r") ax.set_title(f"{y_test[i]}, said {pred[i]}") ax.axis("off") fig.tight_layout() fig.savefig("mistakes.png") print("saved mistakes.png")
(.venv) $ python final.py 10 epochs: validation accuracy 0.955 20 epochs: validation accuracy 0.955 30 epochs: validation accuracy 0.954 chosen: 10 epochs test accuracy: 0.957 434 mistakes in 10000 test images first 20, as true -> said: 5->6, 9->4, 9->4, 2->9, 4->2, 6->0, 3->5, 9->7, 2->7, 5->3, 9->4, 3->7, 9->7, 0->5, 6->0, 9->8, 3->5, 9->7, 8->2, 5->7 saved mistakes.png
Training longer didn't help: 95.5%, 95.5%, then 95.4%. On a tie the script keeps the shorter run, so 10 epochs. Then, once, the test set: 95.7%, above the goal, on 10,000 digits the network has never seen, with a library you wrote yourself.
The test score is close to the validation score, which is what a fair validation set should give. If you now went back and changed the width because of the test score, the test set would become one more validation set, and 95.7% would stop being an honest estimate (lesson 2.9).
Show 20 mistakes
434 of the 10,000 test digits were wrong. final.py saves the first 20 to mistakes.png:
mistakes.png, from the run above: the true digit, then what the network said.Look at them as a person would. Some are hard for anyone: the 2 that's mostly loop, the 0 that's a thin oval. Others look easy to you: the 3 read as 5, the 6 read as 0. Those are what a better model would fix. Notice too that 9 is in 7 of the 20, taken for a 4 three times and a 7 three times. A dense layer sees each pixel separately, so it can't tell that a 9 shifted sideways is still a 9. Stage 8's convolutional networks are built to see exactly that.
Finished
You've trained a network on real handwriting with your own library. Your three scripts
- download MNIST once, and save a fixed training, validation and test split,
- train simplenet MLPs on 784 inputs with shuffled mini-batches,
- tune the width and the learning rate on the validation set only,
- report the test accuracy once: 95.7%, and
- save 20 mistakes to look at.
Before you call it finished, delete mnist-subset.npz and run all three scripts again, in order. Your numbers should match these to the last digit or two (lesson 7.1 says why they might differ slightly).
Try next:
- Use all 60,000 training images instead of 8,000 (keep 10,000 for validation). How much does the test accuracy go up? How much longer does an epoch take?
- Add a second hidden layer,
MLP([784, 128, 64, 10]). Does depth help more than width did? - Print the confusion matrix for the test set (lesson 6.9). Which pair of digits is confused most?
Stage 7 moves to PyTorch: the same ideas, with a GPU when you have one, and the tricks that make much deeper networks train.
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- LeCun, Bottou, Bengio and Haffner, Gradient-based learning applied to document recognition, 1998: the paper that introduced MNIST
- scikit-learn: fetch_openml: downloading a dataset from OpenML, and its parser options
- NumPy: numpy.savez_compressed: several arrays in one compressed .npz file
- Nielsen, Neural Networks and Deep Learning, chapter 1: an MLP trained on MNIST by mini-batch SGD, from scratch