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:

HTML

How to Run It (30 Seconds)

  1. Save the code above as example1.html
  2. Double-click the file → opens in your browser (Chrome/Edge/Firefox)
  3. Press F12 to open Developer Tools → go to Console tab
  4. Click the button “Run Example 1 – Train Now!”
  5. 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)

text

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! 🚀

You may also like...

Leave a Reply

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