Chapter 20: TensorFlow.js Tutorial
TensorFlow.js Tutorial — like your favorite teacher walking you through it step-by-step, with real code you can copy-paste right now, explanations, analogies, and examples that actually run in your browser.
No need for Python, servers, or heavy setup — TensorFlow.js (often called tfjs) lets you do real machine learning directly in JavaScript, in the browser (client-side) or Node.js. It’s perfect for web apps, interactive demos, privacy (data stays on user’s device), and quick experiments.
Step 1: What is TensorFlow.js? (Quick Intro Before We Code)
TensorFlow.js = Google’s JavaScript version of TensorFlow. You can:
- Load pre-trained models (face detection, pose estimation, toxicity detection…)
- Train models from scratch in the browser
- Convert Python TensorFlow/Keras models to JS
- Run on CPU/GPU (via WebGL) or Node.js (with tfjs-node for CUDA)
Official site (still the best in 2026): https://www.tensorflow.org/js Tutorials page: https://www.tensorflow.org/js/tutorials Examples repo: https://github.com/tensorflow/tfjs-examples
Why it’s awesome for beginners:
- Runs in any modern browser (Chrome, Firefox, Edge…)
- No install — just add a <script> tag
- Great for learning: see training progress live in browser
- Privacy + offline possible
Step 2: First Things First — How to Include TensorFlow.js
Two easy ways:
- CDN (easiest for quick demos):
|
0 1 2 3 4 5 6 |
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest/dist/tf.min.js"></script> |
(Always latest = good for 2026 features)
- NPM (for real projects with bundlers like Vite/React/Parcel):
|
0 1 2 3 4 5 6 |
npm install @tensorflow/tfjs |
Then:
|
0 1 2 3 4 5 6 |
import * as tf from '@tensorflow/tfjs'; |
Step 3: Hello World – Linear Regression in Browser (Simplest Training Example)
This is the classic first tutorial: Train a model to predict y = 2x + noise.
Create index.html:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
<!DOCTYPE html> <html> <head> <title>TensorFlow.js Hello World</title> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"></script> <style> body { font-family: Arial; text-align: center; padding: 40px; } #output { font-size: 1.5em; margin: 20px; } </style> </head> <body> <h1>TensorFlow.js: Learn y ≈ 2x</h1> <button onclick="trainAndPredict()">Train & Predict!</button> <div id="output">Click the button...</div> <script> async function trainAndPredict() { const outputDiv = document.getElementById('output'); outputDiv.innerHTML = 'Training...'; // 1. Fake data: y ≈ 2x + noise const xs = tf.tensor2d([[1], [2], [3], [4], [5], [6], [7], [8]], [8, 1]); const ys = tf.tensor2d([[3], [5], [7], [9], [11], [13], [15], [17]], [8, 1]); // roughly 2x +1 noise // 2. Create simple model: one dense layer const model = tf.sequential(); model.add(tf.layers.dense({units: 1, inputShape: [1]})); // 1 input → 1 output // 3. Compile: optimizer + loss model.compile({ optimizer: 'sgd', // stochastic gradient descent loss: 'meanSquaredError' }); // 4. Train! (watch console for progress) await model.fit(xs, ys, { epochs: 200, callbacks: { onEpochEnd: (epoch, logs) => { console.log(`Epoch ${epoch}: loss = ${logs.loss.toFixed(4)}`); } } }); // 5. Predict new value const input = tf.tensor2d([[10]], [1, 1]); // predict for x=10 const prediction = model.predict(input); const predValue = (await prediction.data())[0]; outputDiv.innerHTML = `Predicted y for x=10: <b>${predValue.toFixed(2)}</b><br> (should be around 20–21)`; // Clean up tensors (good practice) xs.dispose(); ys.dispose(); input.dispose(); prediction.dispose(); } </script> </body> </html> |
Open this HTML file in browser → click button → watch it train live (console shows loss dropping) → predicts ≈20 for x=10.
That’s training a neural net in your browser — no server!
Step 4: Level Up – Classic MNIST Handwritten Digits (with tfjs-vis for Visuals)
This is the “real” beginner tutorial everyone does (official one uses this).
MNIST: 28×28 grayscale images of digits 0–9.
We’ll:
- Load data
- Build CNN
- Train
- Visualize with tfjs-vis (confusion matrix, accuracy graph)
First, add tfjs-vis:
|
0 1 2 3 4 5 6 |
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-vis@latest"></script> |
Full code (simplified version):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
<!DOCTYPE html> <html> <head> <title>TensorFlow.js MNIST Tutorial</title> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"></script> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-vis@latest"></script> </head> <body> <h1>MNIST Digit Recognition in Browser</h1> <button onclick="runMNIST()">Train Model</button> <div id="accuracy"></div> <canvas id="canvas" width="280" height="280" style="border:1px solid black;"></canvas> <button onclick="predictDigit()">Predict Drawn Digit</button> <div id="prediction"></div> <script> let model; let trainImages, trainLabels, testImages, testLabels; async function runMNIST() { // 1. Load MNIST (tfjs has helpers or use fetch for small version) // For simplicity, use official small subset or load from CDN const data = await tf.data.mnist({version: '1.0.0', split: 'train'}); // In real: use tfjs-examples or fetch json // Simplified: pretend we have data (in practice use tfjs-data-mnist or examples repo) // Here we build model only model = tf.sequential(); model.add(tf.layers.conv2d({ inputShape: [28, 28, 1], filters: 32, kernelSize: 3, activation: 'relu' })); model.add(tf.layers.maxPooling2d({poolSize: [2, 2]})); model.add(tf.layers.conv2d({filters: 64, kernelSize: 3, activation: 'relu'})); model.add(tf.layers.maxPooling2d({poolSize: [2, 2]})); model.add(tf.layers.flatten()); model.add(tf.layers.dense({units: 128, activation: 'relu'})); model.add(tf.layers.dense({units: 10, activation: 'softmax'})); model.compile({ optimizer: 'adam', loss: 'categoricalCrossentropy', metrics: ['accuracy'] }); // Train loop (pseudo - in real use dataset iterators) // await model.fit(...) document.getElementById('accuracy').innerHTML = 'Model ready (in real: train for epochs)'; } // Draw on canvas to test const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); let isDrawing = false; canvas.addEventListener('mousedown', () => isDrawing = true); canvas.addEventListener('mouseup', () => isDrawing = false); canvas.addEventListener('mousemove', draw); function draw(e) { if (!isDrawing) return; ctx.lineWidth = 20; ctx.lineCap = 'round'; ctx.strokeStyle = 'white'; ctx.lineTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop); ctx.stroke(); ctx.beginPath(); ctx.moveTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop); } async function predictDigit() { // Resize canvas to 28x28, convert to tensor const img = tf.browser.fromPixels(canvas, 1).resizeBilinear([28, 28]).mean(2).expandDims(); const pred = model.predict(img.div(255.0)); const value = (await pred.argMax(1).data())[0]; document.getElementById('prediction').innerHTML = `Predicted: {value}`; img.dispose(); pred.dispose(); } </script> </body> </html> |
(Note: Full MNIST loading needs data files — check official codelab: https://codelabs.developers.google.com/codelabs/tfjs-training-classfication)
Step 5: Official Best Starting Points (2026)
- Official Get Started: https://www.tensorflow.org/js/tutorials/setup (Minimal model training)
- Handwritten Digit CNN: https://www.tensorflow.org/js/tutorials/training/handwritten_digit_cnn (Full MNIST training in browser)
- tfjs-vis for Visuals: Loss/accuracy graphs live.
- Pre-trained Models: PoseNet, MobileNet, Coco-SSD — load with:
|
0 1 2 3 4 5 6 |
const model = await tf.loadLayersModel('https://tfhub.dev/...'); |
Final Teacher Advice
Start with the linear regression hello world above — run it in 30 seconds. Then try official MNIST codelab — it’s the best structured tutorial. Practice: Build a color predictor, sentiment analyzer, or webcam rock-paper-scissors.
Got the tutorial vibe? 🔥
Want:
- Full working MNIST code link?
- How to convert Keras model to tfjs?
- React/Vite integration?
Just ask — next class ready! 🚀
