Skip to content

Capstone 2: an MNIST classifier from scratch

ready≈ 8.5 hoursNeeds: 2.3, 2.4, 2.5, Capstone 1

Part 2 ends with a real classifier on real data: every pixel of 70,000 handwritten digits, ten classes, and nothing but NumPy and your own derivatives.

The model is multiclass logistic regression, also called softmax regression. Each 28×28 image is flattened to x∈R784\mathbf{x}\in\mathbb{R}^{784}, the logits are z=W⊤x+b\mathbf{z} = \mathbf{W}^\top\mathbf{x} + \mathbf{b} with one column of W\mathbf{W} per digit, and the loss is the softmax cross-entropy from 2.4 plus an L2 penalty λ2∥W∥2\frac\lambda2\lVert\mathbf{W}\rVert^2 from 2.5. The parameters are a dictionary {"W", "b"}, the format your Capstone 1 check_gradients takes.

Check before you train. Write forward_backward, then run your Capstone 1 gradient checker on a batch of five images before training anything. A wrong gradient can still lower the loss for a while and give a mediocre model, and you would never know why. The tests use the same check.

Train with mini-batches. Each epoch shuffles the training set and steps through batches of 128. Every step is noisy but cheap, and one pass over 50,000 images gives 390 updates instead of one. 10,000 training images are held out as a validation set to watch for overfitting. The test set is touched exactly once, at the end (module 2.1).

Capstone 2 stubs/cap2_mnist_logreg.py

Loading starter file…

Prefer your own editor? Edit exercises/stubs/cap2_mnist_logreg.py and run mlc check cap2. The tests are identical; import the results on the progress page.

Hints · forward_backward 0/3 revealed
Hints · train 0/3 revealed

Then train on MNIST (locally; downloads about 11 MB once):

Terminal window
cd exercises && python projects/mnist_logreg.py

It trains for 10 epochs (a few seconds on a laptop), prints the training loss and validation accuracy per epoch, and reports test accuracy. The reference solution reaches about 92%. Linear models top out near there. Part 3’s hidden layers take this same data past 97%, and the Part 3 capstone has you do it with your own autograd library.

  • not yet: All tests pass (0/?)
Finish the items above first.
Learner log: time spent and points of confusion

Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.