A Convolutional Neural Network (CNN) trained on the MNIST dataset that achieves ~99.4% test accuracy on handwritten digit recognition (0–9).
Includes an interactive Gradio web demo where you can draw a digit and get an instant prediction.
| Draw on canvas | Upload an image |
|---|---|
| Draw any digit with your mouse or touchscreen | Upload a 28×28 (or any size) grayscale image |
handwritten-digit-recognizer/
├── train.py # Train the CNN on MNIST and save model.h5
├── predict.py # CLI tool to run inference on any image
├── app.py # Interactive Gradio web demo
├── requirements.txt # Python dependencies
└── README.md
pip install -r requirements.txtpython train.pyThis will:
- Automatically download the MNIST dataset (~11 MB)
- Train the CNN for up to 30 epochs with early stopping
- Save the best model to
model.h5 - Generate
training_curves.png
Expected output:
Test Accuracy : 99.40%
✅ Model saved to model.h5
python app.pyOpens a Gradio interface in your browser at http://localhost:7860.
python predict.py --image my_digit.png
python predict.py --image my_digit.png --show # also display a visualisationInput (28×28×1)
│
├─ Conv2D(32, 3×3) + BatchNorm → Conv2D(32, 3×3) + BatchNorm
├─ MaxPool(2×2) → Dropout(0.25)
│
├─ Conv2D(64, 3×3) + BatchNorm → Conv2D(64, 3×3) + BatchNorm
├─ MaxPool(2×2) → Dropout(0.25)
│
├─ Flatten → Dense(256) + BatchNorm → Dropout(0.5)
└─ Dense(10, softmax)
Training details:
| Parameter | Value |
|---|---|
| Optimizer | Adam (lr = 1e-3) |
| Loss | Categorical cross-entropy |
| Batch size | 128 |
| Max epochs | 30 (early stopping) |
| Data augmentation | Random rotation ±10°, zoom ±10%, translation ±10% |
| Test accuracy | ~99.4% |
| Metric | Value |
|---|---|
| Training accuracy | ~99.8% |
| Validation accuracy | ~99.5% |
| Test accuracy | ~99.4% |
| Parameters | ~430,000 |
- Python 3.9+
- TensorFlow / Keras 2.12+
- NumPy
- Pillow
- Matplotlib
- Gradio 4+
MIT License — see LICENSE.