Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Applied Neural Networks: Handwritten Digit Recognition

Open in Colab Open in Kaggle

Applied Neural Networks: Handwritten Digit Recognition

From benchmark accuracy to deployment evidence

We classify 8×88\times8 grayscale images from scikit-learn’s built-in Digits dataset. Because the data ships with scikit-learn, the entire case study is reproducible offline.

Learning Objectives

  1. Build a leakage-safe image-classification split

  2. Compare a linear baseline with a multilayer perceptron

  3. Interpret a confusion matrix and inspect high-confidence errors

  4. Stress-test robustness under increasing pixel noise

  5. Build a confidence-based abstention policy

  6. Quantify parameter count and inference latency

1. Load and Inspect the Dataset

Each example is an 8×88\times8 image with integer pixel intensity from 0 to 16. The label is one of ten digits. Flattened inputs have shape (B,64)(B,64); the MLP output has shape (B,10)(B,10).

Images: (1797, 8, 8); flattened features: (1797, 64); classes: [0 1 2 3 4 5 6 7 8 9]
Pixel range after scaling: [0.0, 1.0]
<Figure size 1200x340 with 16 Axes>

2. Split Before Modeling

We create train, validation, and test sets with stratification. The test set remains untouched until final evaluation. Pixel scaling uses the known physical range [0,16][0,16], so no statistics are learned from held-out examples.

Train: (1149, 64); validation: (288, 64); test: (360, 64)
Class counts in train: [113 117 114 117 116 116 116 114 111 115]

3. Establish a Linear Baseline

Multinomial logistic regression gives a strong, interpretable baseline. It can only create linear class boundaries in the 64-dimensional pixel space.

Baseline validation accuracy: 0.979
Baseline validation log-loss: 0.123

4. Train a Multilayer Perceptron

Architecture: 64→128→64→1064\rightarrow128\rightarrow64\rightarrow10 with ReLU hidden activations. Adam performs mini-batch updates, L2L_2 regularization controls weight magnitude, and internal early stopping restores the best validation state found during training.

MLP stopped after 81 epochs
MLP validation accuracy: 0.976
MLP validation log-loss: 0.072
<Figure size 1100x400 with 2 Axes>

5. Final Test Evaluation

Model selection used the validation set. We now evaluate the chosen models once on the held-out test set.

Linear baseline accuracy=0.964, log-loss=0.139
MLP             accuracy=0.967, log-loss=0.090

MLP classification report:

              precision    recall  f1-score   support

           0      1.000     0.944     0.971        36
           1      0.868     0.917     0.892        36
           2      0.971     0.971     0.971        35
           3      1.000     1.000     1.000        37
           4      0.973     1.000     0.986        36
           5      1.000     1.000     1.000        37
           6      1.000     0.972     0.986        36
           7      0.973     1.000     0.986        36
           8      0.886     0.886     0.886        35
           9      1.000     0.972     0.986        36

    accuracy                          0.967       360
   macro avg      0.967     0.966     0.966       360
weighted avg      0.968     0.967     0.967       360

<Figure size 800x700 with 1 Axes>

6. Inspect the Mistakes

Aggregate metrics do not show how a model fails. We sort incorrect predictions by confidence to find the errors the model is most certain about—often the most important cases to audit.

<Figure size 1200x450 with 12 Axes>
Incorrect test examples: 12 of 360

7. Robustness Stress Test: Pixel Noise

Clean test accuracy is not a robustness guarantee. We add Gaussian noise of increasing standard deviation to the scaled pixels and clip back to [0,1][0,1]. This is not a complete deployment test, but it reveals sensitivity to a plausible input corruption.

<Figure size 800x450 with 1 Axes>
Linear baseline: clean=0.964, σ=0.3 → 0.867, σ=0.6 → 0.556
MLP            : clean=0.967, σ=0.3 → 0.817, σ=0.6 → 0.486

8. Confidence-Based Abstention

In a safety-sensitive system, the classifier can defer uncertain examples to a human or a slower specialist model. Raising the confidence threshold typically increases accuracy on accepted examples while reducing coverage.

<Figure size 700x500 with 1 Axes>
threshold=0.50: coverage=0.989, accepted accuracy=0.975
threshold=0.80: coverage=0.950, accepted accuracy=0.988
threshold=0.95: coverage=0.894, accepted accuracy=0.997

Confidence is not automatically calibrated. A production abstention threshold should be selected on a validation set using domain costs, then monitored after deployment.

9. Model Size and Inference Latency

Accuracy is only one deployment constraint. Parameter count approximates memory needs; batch inference timing provides a rough local latency comparison. These timings are machine-specific, so interpret the ratio more than the absolute numbers.

Linear baseline:     650 parameters, median 128-image latency=0.047 ms
MLP            :  17,226 parameters, median 128-image latency=0.091 ms

10. Deployment Card

QuestionEvidence from this notebookRemaining gap
Does it classify clean held-out digits?accuracy, log-loss, per-class reportexternal dataset
Which mistakes occur?confusion matrix, confident-error gallerydomain expert review
Does corruption hurt?controlled Gaussian-noise curvereal sensor artifacts
Can it defer uncertain cases?accuracy–coverage curvecalibration and cost study
Can it run cheaply?parameters and local batch latencytarget-hardware benchmark

The evidence supports a classroom prototype—not an unrestricted production claim.

Summary

  • The MLP improves on a linear baseline by learning nonlinear pixel interactions.

  • Test accuracy must be paired with log-loss, per-class results, and concrete error inspection.

  • Robustness degrades as input noise rises; clean performance does not certify shifted inputs.

  • Confidence-based abstention exposes an explicit accuracy–coverage trade-off.

  • Architecture choice affects both capacity and deployment cost.

Exercises

  1. Tune hidden width and L2L_2 strength using only the validation set, then evaluate once on test.

  2. Replace Gaussian noise with random pixel dropout or small translations.

  3. Compute an expected cost curve for automatic prediction versus human review.

  4. Calibrate probabilities with a validation set and compare the accuracy–coverage curve.

  5. Implement the same MLP in PyTorch and verify that the tensor shapes match the lecture notation.

References