Case study 06
MNIST CNN
A PyTorch CNN that reads your handwriting live, running in the browser through ONNX.
- 00.0%
- 10.0%
- 20.0%
- 30.0%
- 40.0%
- 50.0%
- 60.0%
- 70.0%
- 80.0%
- 90.0%
PyTorch CNN exported to ONNX, running in your browser.
Overview
A convolutional neural network trained from scratch in PyTorch on the MNIST handwritten digit dataset, then exported to ONNX so it can run anywhere without PyTorch.
Draw a digit on the pad and the model classifies it as you draw, showing its confidence for every class from 0 to 9. I trained it alongside a plain MLP baseline to compare how much convolution helps on image data.
What it does
Two-block CNN
Two convolution blocks (32 then 64 filters) with ReLU and max pooling, then a 128-unit dense head.
Trained from scratch
PyTorch training loop with Adam and cross-entropy over 10 epochs on 60,000 digits.
MLP baseline
A 784-128-64-10 fully connected network trained the same way, as a point of comparison.
Exported to ONNX
About 420K parameters in a 1.7 MB file, served as a static asset.
Live inference
Classifies while you draw, with at most one inference in flight at a time.
Matching preprocessing
Crop, scale to 20x20 and centre on 28x28, exactly as during training.
How it works
- 01Train the CNN in PyTorch on MNIST with inputs normalised to [-1, 1].
- 02Export the trained weights to ONNX.
- 03In the browser, crop the drawing to its bounding box and scale it into 20x20.
- 04Centre it on a 28x28 canvas and normalise it the same way as in training.
- 05Run the model with ONNX Runtime Web and softmax the logits into confidences.
Stack
- Python
- PyTorch
- CNN
- ONNX
- ONNX Runtime Web
- WebAssembly
- TypeScript