Chapter 24: Example 1
What “Example 1” Actually Does
We create fake data where the relationship is roughly:
y ≈ 2 × x + a little noise
We ask the model to learn this relationship automatically by adjusting one weight (slope ≈ 2) and one bias.
After training → give it a new x (e.g. 10) → it should predict ≈ 20.
This is supervised regression using a single-neuron model (basically a perceptron without activation).
Full Working Code – Example 1 (Copy-Paste & Run)
Create a file called index.html and paste this:
|
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 |
<!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 Linear Regression</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: 40px; background: #f8f9fa; } h1 { color: #4285f4; } button { padding: 14px 28px; font-size: 1.2em; margin: 20px; background: #4285f4; color: white; border: none; border-radius: 6px; cursor: pointer; } button:hover { background: #3367d6; } #status { font-size: 1.4em; margin: 30px; color: #333; min-height: 80px; } #console-output { background: #272822; color: #f8f8f2; padding: 20px; border-radius: 8px; max-width: 700px; margin: 20px auto; text-align: left; white-space: pre-wrap; font-family: 'Courier New', monospace; } </style> </head> <body> <h1>TensorFlow.js – Example 1: Learn y ≈ 2x</h1> <p style="font-size:1.1em; max-width:700px; margin:20px auto;"> Click the button below. Watch the browser console (F12) and the status message.<br> The model learns that y is roughly 2 times x. </p> <button onclick="runExample1()">Run Example 1 – Train Now!</button> <div id="status">Waiting for you to click...</div> <div id="console-output"></div> <script> // Helper to show messages both in UI and console function log(msg) { console.log(msg); const div = document.getElementById('console-output'); div.innerHTML += msg + '\n'; div.scrollTop = div.scrollHeight; } async function runExample1() { const status = document.getElementById('status'); status.innerHTML = 'Preparing data...'; // ──────────────────────────────────────────────── // Step 1: Create fake training data // x values: 1 to 10 // y values: roughly 2*x + small noise // ──────────────────────────────────────────────── const xs = tf.tensor2d( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [10, 1] ); const ys = tf.tensor2d( [2.2, 4.1, 6.3, 8.0, 10.2, 12.4, 14.1, 16.3, 18.0, 20.2], [10, 1] ); // ──────────────────────────────────────────────── // Step 2: Create the simplest possible model // One dense layer with 1 unit (one weight + one bias) // ──────────────────────────────────────────────── const model = tf.sequential(); model.add(tf.layers.dense({ units: 1, // one output inputShape: [1] // one input feature })); log('Model created: single neuron (weight + bias)'); // ──────────────────────────────────────────────── // Step 3: Compile – tell how to learn // ──────────────────────────────────────────────── model.compile({ optimizer: 'sgd', // stochastic gradient descent loss: 'meanSquaredError' // how wrong are we? }); status.innerHTML = 'Training... (watch console for loss)'; // ──────────────────────────────────────────────── // Step 4: Train! (this is where learning happens) // ──────────────────────────────────────────────── await model.fit(xs, ys, { epochs: 200, // how many full passes callbacks: { onEpochEnd: async (epoch, logs) => { if (epoch % 20 === 0 || epoch === 199) { log(`Epoch ${epoch}: loss = ${logs.loss.toFixed(6)}`); } } } }); status.innerHTML = 'Training finished! 🎉'; // ──────────────────────────────────────────────── // Step 5: Use the model to predict // ──────────────────────────────────────────────── const testX = tf.tensor2d([[15]], [1, 1]); // new value never seen const prediction = model.predict(testX); const predValue = (await prediction.data())[0]; log(`\nPredicted value for x = 15: ${predValue.toFixed(4)}`); log('(should be close to 30 – because 2 × 15 = 30)'); // Clean up memory (good habit in tf.js) xs.dispose(); ys.dispose(); testX.dispose(); prediction.dispose(); } </script> </body> </html> |
How to Run It (30 Seconds)
- Save the code above as example1.html
- Double-click the file → opens in your browser (Chrome/Edge/Firefox)
- Press F12 to open Developer Tools → go to Console tab
- Click the button “Run Example 1 – Train Now!”
- Watch:
- Loss starts high (maybe 100–200)
- Every 20 epochs it prints lower & lower loss
- Final prediction for x=15 should be very close to 30
What You Should See in Console (Typical Output)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Model created: single neuron (weight + bias) Epoch 0: loss = 123.456789 Epoch 20: loss = 8.234567 Epoch 40: loss = 1.567890 ... Epoch 180: loss = 0.012345 Epoch 199: loss = 0.008901 Predicted value for x = 15: 29.9876 (should be close to 30 – because 2 × 15 = 30) |
Why This Example is Called “Example 1” Everywhere
- It is the very first code example in most TensorFlow.js tutorials (official docs, YouTube, Medium, Udemy courses)
- It proves the core promise: real gradient descent happens in the browser
- It uses only 1 input feature, 1 neuron → easy to understand weights & bias
- After this → next examples add more layers, CNNs, transfer learning, etc.
Final Teacher Words
Example 1 in TensorFlow.js = the Hello World of browser-based deep learning — training a tiny linear model to learn y ≈ 2x.
- Shows data → model → compile → fit → predict cycle
- Runs 100% client-side
- Loss goes down live → you see learning happen
In 2026 this example is still the #1 starting point — because if you can run this, you can build almost anything in tf.js.
Understood? 🌟
Want next?
- Add tfjs-vis live graphs to this example?
- Version with multiple features (flat price prediction)?
- Convert this model to TensorFlow Lite?
Just tell me — next class is ready! 🚀
