This interactive web application built with TensorFlow.js allows you to train and experiment with neural networks on the MNIST handwritten digit dataset:
- π― Interactive Training - Train a CNN model directly in your browser
- π Real-time Visualization - Monitor training metrics with live charts
- βοΈ Draw & Predict - Draw digits and get instant predictions
- π Comprehensive Metrics - View batch and epoch-level performance
- π Confusion Matrix - Analyze model performance across all digit classes
- πΌοΈ Dataset Preview - Visualize random samples from the MNIST dataset
- β‘ WebGPU Acceleration - Leverage GPU for faster training
- π§ WebGL Backend - Fallback option for wider browser compatibility
- π± Responsive Design - Works seamlessly on desktop and mobile devices
The application provides comprehensive training capabilities:
| Feature | Description | Use Case |
|---|---|---|
| π§ Configurable Parameters | Adjust training data size, batch size, epochs | ποΈ Experiment with different training setups |
| π Live Metrics | Real-time loss and accuracy tracking | π Monitor training progress |
| π¨ Interactive Canvas | Draw digits for instant prediction | βοΈ Test model performance |
| π Performance Charts | Batch and epoch-level visualizations | π Analyze training dynamics |
| π Auto Prediction | Automatic inference after drawing | β‘ Seamless user experience |
The CNN model uses modern deep learning practices with Batch Normalization for improved training stability:
Input (28Γ28Γ1)
β
[Conv2D(32, 3Γ3) β BatchNorm β ReLU β MaxPool(2Γ2)]
β
[Conv2D(64, 3Γ3) β BatchNorm β ReLU β MaxPool(2Γ2)]
β
Flatten β Dropout(0.5)
β
[Dense(128) β BatchNorm β ReLU β Dropout(0.5)]
β
Dense(10) β Softmax
| Layer Type | Configuration | Output Shape | Parameters |
|---|---|---|---|
| Input | 28Γ28 grayscale | (28, 28, 1) | 0 |
| Conv2D | 32 filters, 3Γ3 kernel, HeNormal init | (26, 26, 32) | 320 |
| BatchNorm | - | (26, 26, 32) | 128 |
| ReLU | - | (26, 26, 32) | 0 |
| MaxPool2D | 2Γ2 pool, stride 2 | (13, 13, 32) | 0 |
| Conv2D | 64 filters, 3Γ3 kernel, HeNormal init | (11, 11, 64) | 18,496 |
| BatchNorm | - | (11, 11, 64) | 256 |
| ReLU | - | (11, 11, 64) | 0 |
| MaxPool2D | 2Γ2 pool, stride 2 | (5, 5, 64) | 0 |
| Flatten | - | (1600) | 0 |
| Dropout | rate=0.5 | (1600) | 0 |
| Dense | 128 units, HeNormal init | (128) | 204,928 |
| BatchNorm | - | (128) | 512 |
| ReLU | - | (128) | 0 |
| Dropout | rate=0.5 | (128) | 0 |
| Dense | 10 units (output) | (10) | 1,290 |
| Softmax | - | (10) | 0 |
Total Parameters: ~225,930
- π― Batch Normalization: Applied after convolutions and dense layers for faster convergence
- π§ He Normal Initialization: Optimal weight initialization for ReLU activations
- π‘οΈ Dropout Regularization: 50% dropout rate to prevent overfitting
- β‘ Adam Optimizer: Adaptive learning rate optimization
- π Categorical Crossentropy: Standard loss for multi-class classification
{
optimizer: 'adam',
learningRate: 0.001, // Configurable in UI
loss: 'categoricalCrossentropy',
metrics: ['accuracy']
}-
Batch Normalization
- Stabilizes training by normalizing layer inputs
- Allows higher learning rates
- Acts as regularization
-
He Normal Initialization
- Specifically designed for ReLU activations
- Prevents vanishing/exploding gradients
-
Progressive Feature Extraction
- 32 filters β 64 filters: Gradually increases feature complexity
- MaxPooling: Reduces spatial dimensions while preserving features
-
Dropout for Robustness
- Applied after flatten and dense layers
- Reduces overfitting on training data
With default settings (5,500 training samples, 10 epochs):
- Training Accuracy: ~98-99%
- Validation Accuracy: ~97-98%
- Training Time: ~2-5 minutes (depending on hardware)
- Clone this repository
git clone https://github.com/yourusername/mnist-playground-tfjs.git- Navigate to the project directory
cd mnist-playground-tfjs- Install dependencies
npm installStart development server
npm run devBuild the project
npm run buildPreview production build
npm run preview| Parameter | Range | Default | Description |
|---|---|---|---|
| Train Data | 1,000 - 60,000 | 5,500 | Number of training samples |
| Test Data | 1,000 - 10,000 | 1,000 | Number of validation samples |
| Batch Size | 1 - 512 | 128 | Number of samples per training batch |
| Epochs | 1 - 200 | 10 | Number of complete training iterations |
| Learning Rate | 0.0001 - 1 | 0.001 | Optimizer learning rate |
| Backend | WebGPU/WebGL | WebGPU | Computational backend for training |
-
Batch-Level Metrics
- Loss and accuracy per batch
- Average batch processing time
- Progress tracking
-
Epoch-Level Metrics
- Training and validation loss
- Training and validation accuracy
- Average epoch processing time
-
Confusion Matrix
- Overall accuracy
- Per-class precision, recall, F1-score
- Visual heatmap of predictions
-
Draw Digits
- Use mouse or touch to draw on the 280x280 canvas
- Automatic prediction after 0.5 seconds of inactivity
- Manual prediction button available
-
Prediction Display
- Predicted digit with confidence score
- Probability distribution across all 10 digits
- Color-coded confidence levels:
- π’ Green (>80%): High confidence
- π‘ Yellow (50-80%): Medium confidence
- π΄ Red (<50%): Low confidence
-
Canvas Controls
- Clear Canvas: Reset the drawing area
- Predict Now: Trigger immediate prediction
β οΈ Note: Drawing is disabled during training and requires a trained model
- Measures how far predictions are from actual values
- Lower is better
- Should decrease during training
- Percentage of correct predictions
- Higher is better
- Should increase during training
- Shows which digits are commonly confused
- Diagonal elements represent correct predictions
- Off-diagonal elements show misclassifications
- Precision: Of all predicted X, how many were actually X?
- Recall: Of all actual X, how many were correctly identified?
- F1-Score: Harmonic mean of precision and recall
- Start Small: Begin with smaller datasets (5,000-10,000 samples) for faster experimentation
- Adjust Batch Size: Larger batches (128-256) for stability, smaller for better generalization
- Monitor Overfitting: Watch for diverging training and validation accuracy
- Experiment: Try different learning rates and epochs to find optimal settings
You can modify the model architecture in src/utils/model.js:
export function createModel(lr = 0.001) {
const model = sequential();
// layer_1 - 32 filters, 3x3 kernel
model.add(
layers.conv2d({
inputShape: [28, 28, 1],
kernelSize: 3,
filters: 32,
activation: "linear",
kernelInitializer: "heNormal",
})
);
// ... more layers
return model;
}To use a custom dataset:
- Prepare your data in the MNIST format (28x28 grayscale images)
- Update
src/utils/data.jsto load your dataset - Adjust the number of classes if needed
| Browser | WebGPU | WebGL | Status |
|---|---|---|---|
| Chrome (113+) | β | β | β |
| Edge (113+) | β | β | β |
| Firefox | π§ | β | β |
| Safari | π§ | β | β |
β‘ WebGPU Support: WebGPU is currently supported in Chrome and Edge. Other browsers will automatically fall back to WebGL.
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.
- TensorFlow.js - Machine learning library
- Chart.js - Data visualization
- Bootstrap - UI framework
- Bootstrap Icons - Icon library
- MNIST Dataloader - Dataset source
For questions or feedback, please open an issue on GitHub.

