Chapter 29: Example 2

What is “Example 2” in TensorFlow.js?

Example 2 = training a convolutional neural network (CNN) on the MNIST handwritten digit dataset to classify images of digits 0–9.

  • Dataset: 60,000 training + 10,000 test images (28×28 grayscale)
  • Goal: look at a new 28×28 image → say “this is a 7” (or 3, 8, etc.)
  • Model: simple CNN → Conv2D + MaxPooling + Dense layers
  • Output: 10 probabilities (one for each digit 0–9) → pick the highest

This is the first real deep learning example — the same pattern powers Google Photos tagging, face recognition, medical scans, Ola object detection, etc.

Full Working Code for Example 2 (Browser-ready)

This version uses the official small subset loading method + live training progress. Save as tfjs-example2.html and open in browser.

HTML

What Happens When You Run This

  1. Click “Train Model” → data loads, model builds
  2. Training starts → tfjs-vis Visor opens automatically
  3. You see live graphs:
    • Loss dropping (from ~2.3 → ~0.05–0.1)
    • Accuracy climbing (from ~10% → 97–99%)
    • Validation curves (shows generalization)
  4. After 5 epochs (~1–3 min on decent laptop) → accuracy usually 97–99%
  5. Draw a digit (mouse on canvas) → click “Predict My Drawing” → model tells you what it sees

Line-by-Line – Why This is Example 2

  • Data loading: tf.data.mnist() → official helper, gives batched tensors
  • Model: 2 convolutional layers + pooling → learns edges → shapes → digits
  • Compile: categoricalCrossentropy + adam → standard for multi-class
  • fitDataset: trains on streaming data (memory efficient for large datasets)
  • tfvis.show.fitCallbacks: plots loss/accuracy live — magic for understanding

Why Example 2 is the Game-Changer

  • Example 1 → linear regression (1 neuron, 2 params)
  • Example 2 → real deep learning (CNN, many layers, thousands of params)
  • You see image input → classification output
  • You get 97–99% accuracy in browser — proves tf.js is powerful

In Hyderabad 2026, this exact Example 2 pattern is still the second thing every student/developer runs — because once you see handwritten digits recognized in your browser, you believe you can build real AI apps.

Understood now? 🌟

Want next?

  • Improve accuracy to 99%+ with more epochs / better model?
  • Add confusion matrix in Visor after training?
  • Save/load this model & use it in another project?

Just say — next class ready! 🚀

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *