Chapter 27: Example 1 Model
What is the “Example 1 Model”?
Example 1 Model = a single-layer, single-neuron dense model (basically a linear regressor implemented as a tiny neural network) that learns to predict:
y ≈ 2 × x (from a small noisy dataset)
In code, it looks like this (the heart of every beginner TensorFlow.js tutorial):
|
0 1 2 3 4 5 6 7 8 9 10 |
const model = tf.sequential(); model.add(tf.layers.dense({ units: 1, // ← only 1 neuron / output inputShape: [1] // ← takes 1 number as input })); |
That’s it — just 2 lines to define the entire model architecture!
Why This Model is Called “Example 1 Model”
- It is literally the first model shown in:
- Official TensorFlow.js “Get Started” guide
- Almost every YouTube beginner tutorial
- Udemy, Coursera, freeCodeCamp tf.js courses
- It proves the core promise: real training (gradient descent) happens 100% in the browser
- It teaches the exact same concepts as a perceptron or linear regression, but using modern neural network syntax
What Does This Model Actually Contain?
After these two lines, the model has:
| Part | What it is | How many parameters? | What it learns |
|---|---|---|---|
| Input | 1 number (x) | 0 | — |
| Dense Layer | 1 neuron | 2 | 1 weight (slope) + 1 bias |
| Total parameters | — | 2 | Slope ≈ 2, bias ≈ 0 (after training) |
Yes — only 2 trainable numbers! That’s why it’s perfect for beginners — you can almost predict what the weights will be after training.
Full Code Again (With Extra Comments & Printouts)
|
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 |
<!DOCTYPE html> <html> <head> <title>Example 1 Model – TensorFlow.js</title> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"></script> </head> <body> <h1>Example 1 Model: Single Neuron Linear Regression</h1> <button onclick="trainModel()">Train the Model</button> <pre id="log"></pre> <script> function log(msg) { document.getElementById('log').innerHTML += msg + '\n'; console.log(msg); } async function trainModel() { log("=== Starting Example 1 Model ==="); // 1. Tiny dataset const xs = tf.tensor2d([[1],[2],[3],[4],[5],[6],[7],[8],[9],[10]], [10,1]); 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]); // 2. Create the Example 1 Model – the star of the show! const model = tf.sequential(); model.add(tf.layers.dense({ units: 1, // ← only ONE neuron inputShape: [1], // ← expects ONE number per example name: 'output_layer' })); log("Model created:"); log("→ Layers: 1 (dense)"); log("→ Parameters: 2 (1 weight + 1 bias)"); model.summary(); // prints model structure in console // 3. Compile – how should it learn? model.compile({ optimizer: 'sgd', loss: 'meanSquaredError' }); log("\nTraining started..."); // 4. Train await model.fit(xs, ys, { epochs: 300, callbacks: { onEpochEnd: (epoch, logs) => { if (epoch % 50 === 0 || epoch === 299) { log(`Epoch ${epoch}: loss = ${logs.loss.toFixed(6)}`); } } } }); log("\nTraining finished!"); // 5. Look inside: what did it learn? const weights = model.layers[0].getWeights(); const w = (await weights[0].data())[0][0]; // slope const b = (await weights[1].data())[0]; // bias log(`Learned weight (slope) = ${w.toFixed(4)} ← should be ≈ 2`); log(`Learned bias = ${b.toFixed(4)} ← should be ≈ 0`); // 6. Predict new value const testX = tf.tensor2d([[15]], [1,1]); const pred = model.predict(testX); const predValue = (await pred.data())[0]; log(`\nPrediction for x = 15: ${predValue.toFixed(4)}`); log("Expected ≈ 30"); // Cleanup xs.dispose(); ys.dispose(); testX.dispose(); pred.dispose(); } </script> </body> </html> |
What You Should See After Clicking “Train the Model”
In the <pre> area and console:
|
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 |
=== Starting Example 1 Model === Model created: → Layers: 1 (dense) → Parameters: 2 (1 weight + 1 bias) _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= output_layer (Dense) (None, 1) 2 ================================================================= Total params: 2 Trainable params: 2 Non-trainable params: 0 _________________________________________________________________ Training started... Epoch 0: loss = 142.345678 Epoch 50: loss = 0.987654 Epoch 100: loss = 0.123456 ... Epoch 299: loss = 0.004321 Training finished! Learned weight (slope) = 1.9987 ← should be ≈ 2 Learned bias = 0.0214 ← should be ≈ 0 Prediction for x = 15: 29.9919 Expected ≈ 30 |
Why This Tiny Model Teaches You So Much
- You see only 2 parameters → easy to understand what “learning” means
- You watch loss drop dramatically → feel the power of gradient descent
- You can manually calculate what the model learned → weight ≈ 2, bias ≈ 0
- You predict on new data → see generalization in action
In 2026, this Example 1 Model is still the perfect starting point because:
- It proves tf.js can train models in browser
- It uses the exact same sequential → add → compile → fit → predict pattern as every bigger model
- It builds intuition for weights, bias, loss, epochs, optimizer
Got it completely now? 🌟
Want next?
- Add tfjs-vis live loss graph to this exact model?
- Change it to multiple inputs (e.g., flat size + bedrooms → price)?
- Show how to save/load this tiny model?
Just tell me — next class is ready! 🚀
