Linear models · lesson 12 of 12
Parts in this lesson
Aforward, cross_entropy, gradients3.11: the model, its loss and its gradient
Brng.permutation(len(X_train))3.6: shuffled mini-batches
CLogisticRegression(max_iter=1000)3.9: the answer to check against
Dax.imshow(W[:, digit].reshape(8, 8))a column of weights as a picture

Project: a digit reader from scratch

Last updated

Everything in this stage, in one program. You’ll build a handwritten-digit reader in NumPy: softmax regression, trained by mini-batch gradient descent on cross-entropy, with nothing from scikit-learn but the data. Then you’ll check it against scikit-learn’s LogisticRegression, find which digits it confuses, and look at what it learned, drawn as ten 8 × 8 pictures.

By the end of this lesson you can

  • Write softmax regression’s forward pass, loss and gradient as separate functions
  • Train it with shuffled mini-batches, and read its loss as it goes
  • Match scikit-learn’s LogisticRegression, and read the confusion matrix
  • Draw the learned weights as images, and say what they show

Plan it

The question: can a model with nothing inside but one weight per pixel per digit read handwritten digits? And can you build it yourself, well enough to match a library?

The data: scikit-learn's 1,797 handwritten digits, 8 × 8 pixels each, from lesson 3.11.

What you'll make: one notebook that, run from the top,

  1. loads the digits, scales the pixels to 0 to 1, and splits off a stratified test set,
  2. turns the labels into one-hot rows,
  3. defines forward, cross_entropy and gradients as functions,
  4. trains with shuffled mini-batches of 32 for 30 epochs, printing the loss,
  5. scores the test set, and compares with LogisticRegression,
  6. finds the commonest mistake, and draws the ten digits' weights as images.

On your own computer, make it in the ml-course folder as 03-digits.ipynb. Here, the notebooks below run in the page. The model, from lesson 3.11:

Softmax regression on one digit64 pixels in, 10 probabilities out
8 × 8 imagepixels 0 to 1⋮x: 64x W + bW: 64 × 100−1.210.321.134.64−0.851.96−270.682.291.410 scoressoftmax0010.0120.0230.794050.056070.0180.0790.0310 probabilities, adding to 1

The model's answer is the digit with the biggest probability: 3, at 0.79. Training changes W and b so that the right digit's probability goes up for every training image.

Load and split

03-digits.ipynb

1,347 digits to train on and 450 to test, with about 135 of each digit in training: stratify=y kept the ten classes balanced (lesson 2.5). Dividing by 16 puts every pixel between 0 and 1, so all 64 features are already on the same scale (lesson 3.7).

One-hot labels

03-digits.ipynb

Row i of np.eye(10) is all 0s with a 1 in column i, so np.eye(10)[y_train] picks one such row per label: the first training digit is a 7, and its row has its 1 in column 7. Y_train has the same shape as the model's probabilities, 1347×10, which is what makes the gradient 1nX⊤(P−Y) work (lesson 3.11).

Forward, loss, gradient, step

Write the model as three small functions, so each can be tested on its own:

  • forward(X, W, b): the probabilities, softmax⁡(XW+b), one row per image, with the subtract-the-maximum fix (lesson 3.11).
  • cross_entropy(P, y): the mean of −log⁡ of each image's probability for its true digit. P[np.arange(len(y)), y] picks, from each row, the column of the true label. The 1e-12 keeps a probability of exactly 0 from giving -inf (lesson 3.10).
  • gradients(X, P, Y): 1nX⊤(P−Y) for the weights, the mean of P−Y for the biases.

The step is then two lines: W = W - lr * dW and b = b - lr * db. Together they're lesson 3.3's loop, with a different model inside:

[yes][no]Start the weightsat 0Predictŷ = wx + bMeasure the errorsŷ − y, and the lossWork out thegradientStep against itw ← w − η ∂L/∂wStepsleft?

Press Walk through it to follow the work round the chart, one stop at a time.

  1. Start: set every weight and the bias to 0.
  2. Predict every example with the current weights.
  3. Measure the errors and the loss.
  4. Work out the gradient of the loss.
  5. Step each weight against its gradient, scaled by the learning rate.
  6. If there are steps left, go back to 2; otherwise stop.
The training loop as a UML activity diagram. In UML’s notation: the filled dot is where it starts and the ringed dot where it ends; rounded boxes are actions; a diamond with a question is a decision, with the condition for each way out in [brackets], and an empty diamond is a merge, where a way back joins the flow; Pink arrows go back to an earlier action.

Mini-batches

Every epoch, shuffle the training digits and walk through them 32 at a time (lesson 3.6): 43 steps an epoch, 1,290 in all.

03-digits.ipynb

The training loss falls from 0.26 after 5 epochs to 0.11 after 30. It doesn't fall every time: after 25 epochs it's a little higher than after 20. That's mini-batch noise (lesson 3.6), and nothing to worry about while the trend is down. 96.4% of the 450 test digits are read correctly.

Compare with scikit-learn

The same split, trained again, and LogisticRegression beside it:

03-digits.ipynb

Yours: 0.964. scikit-learn's: 0.969. And the two models give the same answer on 99.6% of test digits, so they've learned nearly the same thing. The small difference is mostly scikit-learn's default ridge penalty (lesson 3.8) and its optimiser running to convergence.

Which digits does it get wrong? The second cell blanks out the diagonal of the confusion matrix (lesson 2.8) and finds the biggest box left:

03-digits.ipynb

16 mistakes in all, and 5 of them are the same one: an 8 read as a 1. Here's the whole confusion matrix, truth down the side:

Your digit reader’s confusion matrix450 test digits; · is 0
predictedtruth0011223344556677889945··········45······1··143··········45···1······43···2··1···45·····2····43··········45···5···1·136······1···44

434 of 450 on the diagonal (outlined) are right; every box off it is a kind of mistake, and its row and column say which digit was read as which.

The 8 row is the weakest: 36 of 45 right, with five read as 1s. The 1 column collects mistakes from 2, 5, 6 and 8 as well. A thin, upright stroke down the middle is what a 1 is, and some badly written 8s are little more than that.

Show the learned weights as 8 × 8 images

Each digit's 64 weights, one per pixel, can be put back into an 8 × 8 grid and drawn:

03-digits.ipynb

All ten share one colour scale, with white at 0. Red pixels have positive weights: ink there is evidence for that digit. Blue pixels have negative weights: ink there is evidence against it. Look at 0: a red ring with a blue centre, since a 0 has ink round the edge and none in the middle. 2 is red along the bottom row, where a 2 has its flat base. 6 is blue at the top right, where a 6 has no ink but a 5 or a 9 would. Each column of W is a template, and the score for a digit is how well the image matches it, a dot product (lesson 1.3).

Most of the others are harder to read, speckled with red and blue. With about 135 examples of each digit and 64 weights each, the model has picked up some quirks of these particular writers along with the shapes. That's lesson 3.8's overfitting, mildly, and the ridge penalty in "Try next" smooths it.

That's also this model's limit. One template per digit can't say "a 7, written with or without a bar across". Stage 6 adds a hidden layer, which can learn many smaller templates and combine them.

Finished

You've built a classifier from nothing but NumPy and matched a library. Your notebook

  • loads, scales and splits the data, with a stratified test set,
  • writes the model, its loss and its gradient as small functions,
  • trains with shuffled mini-batches, and shows the loss falling,
  • scores 96.4% on the test digits, against scikit-learn's 96.9%,
  • finds the commonest mistake, and shows what each digit's weights learned.

Before you call it finished, restart the kernel and run every cell from the top. If the numbers are the same, it's done.

Try next:

  • Train for 100 epochs instead of 30. Does the test score go up, or does the gap between training and test grow (lesson 2.6)?
  • Add a ridge penalty: add lam * W to dW, and try lam from 0.0001 to 0.1, choosing it with a validation set (lessons 2.9 and 3.8). Do the weight pictures get smoother?
  • Try a learning rate of 5. What does the loss do, and why (lesson 3.3)?

Stage 4 meets the other classic models, from naive Bayes to random forests, and some of them will beat this one on these digits without any gradient descent at all.

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.

All sources for Simple Machine Learning