Chapter 25: TensorFlow Example 1
What is “TensorFlow.js Example 1”?
In the official TensorFlow.js documentation, most beginner YouTube videos, Udemy courses, and blog posts, Example 1 is always the same:
Training a single-neuron linear regression model in the browser to learn the relationship y ≈ 2x (with a little noise)
Why this specific example?
- It shows the complete end-to-end ML cycle in ~30 lines of code
- Proves that real gradient descent / backpropagation happens 100% in the browser (no Python, no server)
- Uses the simplest possible model: one input → one output (basically a perceptron without activation)
- Lets you watch the loss drop live in console → you feel the learning happening
- After this, everything else (CNNs, LSTMs, transfer learning, image classification) builds on the same pattern
So let’s do it properly — full working code + explanation.
Full Working Code for TensorFlow.js Example 1
Create a file called tfjs-example1.html and paste this entire code:
|
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 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <title>TensorFlow.js Example 1 – Hello World (y ≈ 2x)</title> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest/dist/tf.min.js"></script> <style> body { font-family: Arial, sans-serif; text-align: center; padding: 50px 20px; background: #f0f4f8; color: #333; } h1 { color: #4285f4; margin-bottom: 10px; } p.intro { max-width: 700px; margin: 20px auto; font-size: 1.1em; line-height: 1.5; } button { padding: 14px 32px; font-size: 1.3em; background: #4285f4; color: white; border: none; border-radius: 8px; cursor: pointer; margin: 30px 0; } button:hover { background: #3367d6; } #status { font-size: 1.5em; margin: 30px 0; min-height: 60px; color: #555; } #console-log { background: #1e1e1e; color: #d4d4d4; padding: 20px; border-radius: 10px; max-width: 800px; margin: 20px auto; text-align: left; font-family: 'Courier New', monospace; white-space: pre-wrap; max-height: 400px; overflow-y: auto; } </style> </head> <body> <h1>TensorFlow.js – Example 1: Learn y ≈ 2x</h1> <p class="intro"> This is the classic first example in TensorFlow.js.<br> We train a tiny model to discover that <strong>y is approximately 2 times x</strong>.<br> Click the button → watch the console (F12) for loss decreasing → see the final prediction. </p> <button onclick="runExample1()">Run Example 1 – Start Training!</button> <div id="status">Waiting for you to click the button...</div> <div id="console-log">Console output will appear here...</div> <script> // Helper function to show messages in both console and UI function log(message) { console.log(message); const logDiv = document.getElementById('console-log'); logDiv.innerHTML += message + '\n'; logDiv.scrollTop = logDiv.scrollHeight; // auto-scroll to bottom } async function runExample1() { const status = document.getElementById('status'); status.innerHTML = 'Preparing tiny dataset...'; // ───────────────────────────────────────────────────────────── // 1. Create training data (very small on purpose) // x = inputs (1 to 10) // y ≈ 2*x + small random noise // ───────────────────────────────────────────────────────────── const xs = tf.tensor2d( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [10, 1] // shape: 10 examples, 1 feature each ); const ys = tf.tensor2d( [2.1, 4.3, 5.9, 8.2, 10.1, 12.4, 14.0, 16.3, 18.2, 20.1], [10, 1] ); status.innerHTML = 'Creating single-neuron model...'; // ───────────────────────────────────────────────────────────── // 2. Build the simplest model possible // One dense layer with 1 unit → learns 1 weight + 1 bias // ───────────────────────────────────────────────────────────── const model = tf.sequential(); model.add(tf.layers.dense({ units: 1, // one output neuron inputShape: [1] // one input feature })); log('Model architecture created: 1 input → 1 neuron → 1 output'); // ───────────────────────────────────────────────────────────── // 3. Compile: choose how to learn // ───────────────────────────────────────────────────────────── model.compile({ optimizer: 'sgd', // stochastic gradient descent loss: 'meanSquaredError' // measure average squared error }); status.innerHTML = 'Training... (watch console for loss dropping)'; // ───────────────────────────────────────────────────────────── // 4. Train the model (this is where the magic happens!) // ───────────────────────────────────────────────────────────── await model.fit(xs, ys, { epochs: 300, // number of full passes over data callbacks: { onEpochEnd: (epoch, logs) => { // Show progress every 30 epochs to avoid console spam if (epoch % 30 === 0 || epoch === 299) { log(`Epoch ${epoch}: loss = ${logs.loss.toFixed(6)}`); } } } }); status.innerHTML = 'Training complete! 🎉 Model learned y ≈ 2x'; // ───────────────────────────────────────────────────────────── // 5. Test the model on a new value it never saw // ───────────────────────────────────────────────────────────── const testInput = tf.tensor2d([[15]], [1, 1]); // x = 15 const predictionTensor = model.predict(testInput); const predictedValue = (await predictionTensor.data())[0]; log(`\nPrediction for x = 15: ${predictedValue.toFixed(4)}`); log('Expected ≈ 30 (because 2 × 15 = 30)'); // Clean up memory (very important in browser!) xs.dispose(); ys.dispose(); testInput.dispose(); predictionTensor.dispose(); } </script> </body> </html> |
How to Run It Right Now (30 Seconds)
- Copy the entire code above
- Paste into a new file → save as tfjs-example1.html
- Double-click the file (opens in Chrome/Edge/Firefox)
- Press F12 → go to Console tab
- Click the big blue button
- Watch:
- Loss starts high (maybe 50–200)
- Every 30 epochs it prints lower loss
- Final prediction for x=15 should be very close to 30 (usually 29.8–30.2 after 300 epochs)
Line-by-Line Breakdown (Teacher Mode)
- xs & ys: Our tiny training dataset (10 examples). Real data would be much larger.
- tf.sequential(): Creates a linear stack of layers (like a simple pipeline).
- tf.layers.dense({units: 1, inputShape: [1]}): One neuron that takes 1 number and outputs 1 number. Learns slope (weight) and intercept (bias).
- model.compile(…): Tells TensorFlow: “Use SGD optimizer to minimize mean squared error”.
- model.fit(xs, ys, {epochs: 300, callbacks: …}): The training loop. Each epoch = full pass over 10 examples.
- onEpochEnd callback: Prints loss so we see progress (without flooding console).
- model.predict(testInput): After training, use the learned weights to guess for new x=15.
- dispose(): Frees GPU/browser memory (very important — tf.js tensors don’t auto-free like Python).
What You Should See (Typical Console Output)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Model architecture created: 1 input → 1 neuron → 1 output Epoch 0: loss = 142.345678 Epoch 30: loss = 4.567890 Epoch 60: loss = 0.789012 ... Epoch 270: loss = 0.004567 Epoch 299: loss = 0.003214 Prediction for x = 15: 29.9923 Expected ≈ 30 (because 2 × 15 = 30) |
If loss doesn’t drop much → common mistake: too few epochs, wrong optimizer, or data not scaled.
Why This Example is Called “Example 1” Everywhere
- It is literally Example 1 in the official TensorFlow.js “Get Started” guide
- It appears first in almost every tutorial video/blog/course
- It teaches the core cycle: data → model → compile → fit → predict
- It proves TensorFlow.js can do real training (not just inference) in browser
In 2026 this tiny example is still the #1 starting point — because once you understand this, adding layers, CNNs, transfer learning, or tfjs-vis graphs becomes easy.
Got it completely now? 🔥
Want next?
- Add live loss graph with tfjs-vis to this example?
- Version with multiple features (e.g. flat price predictor)?
- How to save/load this model in browser?
Just tell me — next class is ready! 🚀
