Back
Groundwork / Machine Learning from First Principles
An interactive chapter · Machine Learning from first principles

A machine learns the way you find the bottom of a hill: one small step downhill at a time.

No math background needed. Using one tiny example — predicting a house's price from its size — you'll watch a straight line teach itself to fit data. Every equation is explained in plain words, and everything that can move, moves. Each section drops the error a little lower, until the line settles right through the data.

Start walking ↓
Section 01

What is Machine Learning, really?

Traditional programming means a human writes explicit rules: "if this, then that." Machine Learning flips that around. Instead of writing the rules ourselves, we show the computer many examples of inputs and correct outputs, and let it discover the rule — a mathematical function — that connects them. Once learned, that function can predict answers for brand-new inputs it has never seen.

A spam filter isn't told "the phrase 'free money' means spam" (spammers adapt in a week). It's shown thousands of labeled emails and learns which patterns correlate with spam. Handwriting readers aren't given a rule for every possible "7" — they see thousands of examples. In every case the common thread is the same: we don't know the rule ourselves, but we have examples of it in action — so we let the data reveal the rule.

This chapter is about supervised learning: we have both inputs and correct answers. (Two siblings exist — unsupervised learning finds structure without answers, and reinforcement learning learns from rewards — but they wait for another chapter.)

The idea in symbols f(x) ≈ y

We're hunting for a function f that turns an input into (approximately) the right output. The wavy "≈" matters: we rarely find a rule that's perfectly right — we find one that's close enough on average.

x the input — a fact we know (house size) y the true answer (the actual sale price) f the rule the machine must discover "approximately equals" — close, not perfect
See it move · finding f is drawing a line

Many candidate rules, one best fit

Here are our three houses (sizes 1, 2, 3 — in hundreds of square feet — selling for 3, 5, 7 — in $10,000s). Each gray line is a different candidate rule. The machine's whole job is to find the one line that fits the dots best — automatically, instead of a human guessing by eye.

Trying candidate rules…
Section 02

The model: a line with two knobs

Our simplest possible rule assumes price grows in a straight line with size: a bigger house costs proportionally more, on top of some fixed base cost. A straight line has exactly two knobs you can turn: how steep it is, and where it starts. Learning, at its core, is nothing more than tuning these two knobs until the line fits the data well.

The model equation ŷ = w·x + b
ŷ "y-hat" — the model's predicted answer (the hat means "our guess", not the true value) x the input (house size) w the weight — knob #1, the slope: how much price rises per unit of size b the bias — knob #2, the starting height: the base price when size is zero

If w is large, price climbs steeply with size. If it's near zero, size barely matters. And b slides the whole line up or down without changing its tilt. Just two numbers completely determine the line — so training a model is nothing more than searching for the best pair of numbers.

Interactive · turn the two knobs yourself

Steer the line over the houses

ŷ = 1.0·x + 0.5
Real-life analogy · what a "weight" really means

Two colleges, same students, opposite verdicts

"Weight" isn't jargon — it means what it means in everyday life: how much a factor counts toward an outcome. Imagine a college admissions score built from three inputs every applicant has — GPA, a test score, and extracurriculars (each out of 10):

Score = w₁·GPA + w₂·Test + w₃·Extracurricular + b

Student A has GPA 9.5, Test 9.0, Extracurricular 3.0. Student B has GPA 7.0, Test 7.0, Extracurricular 9.5. The students never change. Only the weights do — watch the ranking flip:

Student A
Student B

That's the entire point of a weight: how much influence one input has on the final answer, relative to the others. A college committee picks its weights by intuition. An ML model lets gradient descent search for the weights that make predictions match reality — judged by the loss function we meet next. (Real houses use the same trick with many features — size, bedrooms, location — each with its own weight: ŷ = w₁x₁ + w₂x₂ + … + wₙxₙ + b.)

Section 03

How do we know a model is good? The loss function

Once we have a line — any line, even a terrible guess — we need a way to measure how wrong it is. For each house we compare the model's prediction to the actual price; the difference is that house's error. We then want one single number summarizing how wrong the model is across all houses at once. Smaller is better. That number is called the loss.

Why square each error? Two reasons. First, a raw error can be positive or negative — if we just averaged them, a +10 miss and a −10 miss would cancel to zero, falsely claiming a perfect model. Squaring makes every error positive, so mistakes can never hide each other. Second, squaring punishes big misses much more than small ones — being off by 4 costs 16, being off by 1 costs only 1. Being very wrong should count for more than being slightly wrong.

Real-life analogy · why squaring is fair

A dartboard where big misses hurt extra

Imagine scoring darts by the area of a square drawn on your miss distance. Miss by 1 cm — a tiny 1 cm² square, barely a scratch. Miss by 5 cm — a 25 cm² square, a real penalty. Under this scoring, one wild throw costs more than many small wobbles, so the safest strategy is to keep every throw reasonably close. That's exactly the behavior we want from our line: no single house left badly mispriced. In the demo below, each error is drawn as a literal square — watch how the biggest miss dominates the picture.

The loss equation · Mean Squared Error L(w,b) = (1/n) Σ (ŷᵢ − yᵢ)²
L the loss — one number for "how wrong overall" (smaller = better) Σ "sigma" — just means "add these up, one per data point" n how many data points we have (here, 3 houses) ŷᵢ − yᵢ the error on house number i: prediction minus truth 1/n divide by the count — i.e. take the average

In words: "for each house, take (prediction − truth), square it, then average the squares." We write L as a function of w and b because those knobs are the only things we control — the data is fixed.

Interactive · errors as literal squares, loss computed live

The bad line vs. the good line

Same two knobs as before — but now every prediction miss is drawn as a red stick (the error) with its square attached (the penalty). Start on the chapter's bad line (w = 0.5, b = 0, loss 17.5), then press the good line and watch the penalty collapse to zero.

17.50loss L(w, b) — mean of the squared errors
housesize xtrue price ypredicted ŷerror ŷ−ysquared
Section 04

Derivatives: which way is downhill?

Plot the loss against every possible pair of knob settings and you get a bowl-shaped surface (you'll see it in Section 9). The best model lives at the bottom of the bowl. So the whole problem becomes: how do you find the bottom of a bowl you can't see all at once?

A derivative answers exactly one question: at the spot where you're standing, how steeply is the ground tilting, and in which direction? Slope pointing up to the right? Then downhill is to the left. Slope of zero? You're standing on flat ground — possibly the very bottom.

The chapter's analogy · the blindfolded hiker

Feeling for the slope with your feet

Imagine standing somewhere on that bowl, blindfolded, asked to walk to the bottom. You can't see the shape — but you can feel which way the ground slopes under your feet. Take a small step downhill, feel again, step again. Repeat, and you'll reach the bottom. A derivative is that feeling-with-your-feet, turned into a number. Try it below: read the slope, then step downhill.

The definition, and the only two rules we need f′(x) = lim (h→0) [f(x+h) − f(x)] / h
f′(x) "f prime" — the slope of f at the exact point x h a tiny nudge to the input, shrinking toward zero lim "in the limit" — what the value settles to as h vanishes

In words: "nudge the input a hair, see how much the output moves, divide — that ratio, for an infinitely small nudge, is the slope at that exact spot." Happily, we only ever need two ready-made rules:

1 · The power rule. For f(x) = xⁿ, the slope is f′(x) = n·xⁿ⁻¹. So for f(x) = x² — the hill above — the slope is f′(x) = 2x. That's why the readout above always shows exactly twice the hiker's position.

2 · The chain rule. When one function sits inside another, f(x) = g(h(x)), the slope is f′(x) = g′(h(x)) · h′(x) — differentiate the outer function first, then multiply by the derivative of the inner one. Like peeling an onion: outside layer, then inside layer, multiply.

Our loss is exactly this shape: a square (outer) wrapped around the line (inner).

We'll use the chain rule in the very next section — because our loss (ŷ − y)² is a square (outer function) wrapped around the line ŷ = wx + b (inner function, which contains the knob w we care about).

Section 05

The gradient: a slope for each knob

We have two knobs, so we ask the slope question twice: if I nudge w a hair, does the loss go up or down, and how fast? And the same for b. The two answers together are called the gradient — a pair of numbers pointing in the direction where loss climbs fastest. Since we want loss to fall, we'll move exactly the opposite way.

Deriving both slopes with the chain rule

Take the loss for one house, (ŷ − y)² where ŷ = wx + b. Chain rule: outer square first (power rule gives 2(ŷ−y)), then multiply by the inner function's slope with respect to w — which is just x, since in wx + b − y only the wx part moves when w moves:

∂/∂w (ŷ−y)² = 2(ŷ−y)·x

Averaging over all n houses, and doing the same for b (whose inner slope is just 1):

∂L/∂w = (2/n) Σ(ŷᵢ−yᵢ)·xᵢ ∂L/∂b = (2/n) Σ(ŷᵢ−yᵢ)
"partial" — a derivative taken for one knob while the other holds still ∂L/∂w how fast loss changes when only w is nudged ∂L/∂b how fast loss changes when only b is nudged (ŷᵢ−yᵢ) the error on point i — both formulas are built from it

Reading them in plain words: the w-slope is the average error scaled by the input x — larger inputs demand larger weight adjustments, because a change in w matters more when x is big. The b-slope is simply the average error itself — no scaling, because b shifts every prediction equally regardless of x.

Interactive · feel the gradient at any knob setting

Two slopes, two suggested nudges

Set the knobs anywhere. The gradient reports the two slopes; each arrow shows the direction the update will push that knob (opposite the slope) and how urgently. Notice: near the best line, both arrows shrink toward nothing — flat ground.

∂L/∂w = −18.00
→ push w up
∂L/∂b = −8.00
→ push b up
current loss at this (w, b)
Real-life consequence · why the size of x matters

Square feet vs. bedrooms: an unfair tug-of-war

Because the w-slope is error × x, the raw size of x sneaks into the gradient. Give a house two features — size = 2,000 sq ft and bedrooms = 3 — and suppose the model is off by 5. The same formula, 2 × error × x, gives each feature's gradient:

Size (x=2000)
20,000
Bedrooms (x=3)
30

The size weight's gradient is over 600× larger — not because size truly matters 600× more, but purely because its numbers happen to be thousands of times bigger. One knob would take enormous steps while the other barely learns. (The bar above is drawn on a compressed scale just so the bedroom bar is visible at all.) This is why, in practice, features are scaled to similar ranges before training — it returns as a pitfall in Section 11.

Section 06

Gradient descent: the update rule

We now know which direction makes the loss worse. So we take a small step in the opposite direction, re-measure the slope from our new position, and repeat. Each step nudges w and b a little closer to the values that minimize error. This "step downhill, feel again, step again" ritual is gradient descent — the core learning mechanism behind almost all of modern ML, including deep neural networks.

The update rule w := w − α·∂L/∂w b := b − α·∂L/∂b
:= "update to" — replace the old value with the new one α "alpha", the learning rate — a small positive number setting the step size the minus sign is the whole trick: go against the uphill direction

Everything hangs on choosing α well. Too small → thousands of timid steps, training crawls. Too large → each step flies past the bottom, bouncing back and forth or even diverging (loss gets worse). Just right → steady, efficient descent. It's one of the most important practical judgment calls in ML — found by experimentation, and often shrunk gradually during training ("learning-rate decay").

Interactive · three hikers, three step sizes

Too timid, just right, too bold

Three identical hills, three hikers who differ only in step size α. Press run and compare their fates.

Too small α = 0.02

ready

Just right α = 0.35

ready

Too large α = 1.15

ready
Section 07

The training loop: four steps on repeat

That's every ingredient. Training a model is simply repeating four steps, over and over: guess, measure the mistake, ask which direction reduces it, adjust. Nothing more mysterious than that.

Real-life analogy · seasoning a soup

Taste, judge, adjust, taste again

A cook doesn't compute the perfect amount of salt in advance. They taste the soup (predict), notice it's too bland (measure the error), decide salt — not sugar — is what's missing and roughly how much (the gradient: which knob, which direction), add a pinch rather than the whole box (a small step, the learning rate) — and taste again. Round and round until it's right.

1 · Predicttaste the soup — ŷ = wx + b 2 · Measuretoo bland? — the loss L 3 · Gradientwhat's missing? ∂L/∂w, ∂L/∂b 4 · Updatea pinch more — α step
The algorithm, spelled out

1. Initialize w and b (often to zero, or small random values).
2. Repeat, for a fixed number of iterations or until the loss stops improving:
    a. Predict for every data point: ŷᵢ = w·xᵢ + b
    b. Measure: L = (1/n) Σ(ŷᵢ−yᵢ)²
    c. Compute both gradients: ∂L/∂w, ∂L/∂b
    d. Update both knobs: w := w − α·∂L/∂w, b := b − α·∂L/∂b
3. Return the final w and b — that pair is the trained model.

How do we know when to stop? Common choices: a fixed number of iterations ("epochs"), the loss improving by less than a tiny threshold between iterations (convergence), or error on held-out data starting to rise — an early warning of overfitting, covered in later chapters.

The player below runs this exact loop on our three houses — Section 8 walks through what its first iterations mean, number by number.

Section 08

The worked example, running live

Let's make everything concrete. Our dataset: three houses, size x = [1, 2, 3], price y = [3, 5, 7]. (Secretly the true relationship is y = 2x + 1 — but the model doesn't know that. It must discover it.) Setup, exactly as in the chapter: start at w = 0, b = 0, learning rate α = 0.1.

Iteration 1 by hand. With both knobs at zero, every prediction is 0, so the errors are [−3, −5, −7] and the loss is (1/3)(9 + 25 + 49) = 27.67. The gradients: ∂L/∂w = (2/3)(−3·1 − 5·2 − 7·3) = −22.67 and ∂L/∂b = (2/3)(−15) = −10. Both slopes are steeply negative — the bowl tilts hard toward larger w and b — so the updates push both knobs up: w becomes 0 − 0.1(−22.67) = 2.267 and b becomes 0 − 0.1(−10) = 1.0. One step, and the loss collapses from 27.67 to about 0.33.

Iteration 2 refines the slight overshoot: the new predictions [3.267, 5.533, 7.8] are all a touch high, the gradients turn small and positive, and the knobs ease back to w ≈ 2.018, b ≈ 0.893. From there the loss keeps shrinking as w → 2 and b → 1 — exactly the true rule y = 2x + 1. Gradient descent, working precisely as intended. Watch it happen:

Interactive · the training-loop player

Predict → measure → gradient → update, on repeat

iteration
0
weight w
0.000
bias b
0.000
loss L
27.67
The arithmetic of the current step (matches the chapter's hand computation)
Press Step or Play to begin.
iterationwbloss

The chapter shows the same pattern holds on completely different data — predicting ice-cream sales from temperature — where the identical four-step loop drives the loss down just as fast (with a smaller α, because those x values are larger — feature scaling again). Different units, same machinery: predict, measure, gradient, update works on any linear dataset.

Section 09

Visual intuition: the bowl

Now the picture that ties it all together. Plot the loss L for every possible combination of w and b and you get a bowl-shaped surface: high walls where the line fits badly, a single lowest point at w = 2, b = 1 where it fits perfectly. Training never sees this whole bowl — it only ever feels the local slope — yet the path it traces bends steadily inward toward the bottom, loss shrinking with every step. That path below is the actual descent on our house data, starting from w = 0, b = 0.

Interactive · the loss landscape and the descent path

Watching the walk from above — and from the side

Dark valley = low loss, pale ridges = high loss. The green dot marks the bottom of the bowl (w = 2, b = 1). The orange trail is gradient descent feeling its way down — big confident strides where the slope is steep, tiny careful steps as the ground flattens near the bottom.

Section 10

From simple to general

Here's the payoff. Everything in this chapter — a model with weights and biases, a loss measuring error, gradients from calculus, an update rule stepping downhill — is exactly the same machinery used in logistic regression and in deep neural networks. Only two things ever change in fancier models: the shape of the function f(x), and the specific loss used. The core loop — predict, measure, gradient, update — stays identical. That's why gradient descent is called the workhorse of modern machine learning.

Direction 1 · classification with logistic regression

Same knobs, squeezed into an S

To predict a probability ("is this email spam?") instead of a number, we take our familiar wx + b and squeeze it through an S-shaped curve called the sigmoid — its output always lands between 0 and 1, perfect for probabilities. Drag w and watch: the knob still controls steepness, exactly as it did for the line.

ŷ = 1 / (1 + e^−(wx+b))
e a fixed math constant (≈ 2.718) that makes the S-shape smooth ŷ now a probability between 0 and 1, instead of a price

The weights are learned by the very same gradient-descent updates — only the loss changes, to one better suited for probabilities (called cross-entropy loss).

Direction 2 · neural networks

Stacks of weighted sums

A neural network is just many of our little equations stacked in layers, each feeding the next: layer₁ = wx + b, layer₂ = w′·(layer₁) + b′, and so on — with a non-linear bend (like ReLU) between layers so the network can learn curves, not just straight lines. In the sketch below, every glowing connection is another w, and every circle adds another b:

inputs x output ŷ

Training is identical in spirit to what we derived by hand: predict, compute the loss, compute the gradient of every weight via the chain rule, update. The chain rule simply gets applied more times — once per layer — and that repeated application has a famous name: backpropagation.

Section 11

Summary and key takeaways

The five formulas that ran this whole chapter
The modelŷ = w·x + b
The loss (MSE)L = (1/n) Σ(ŷᵢ−yᵢ)²
Gradient for w∂L/∂w = (2/n) Σ(ŷᵢ−yᵢ)·xᵢ
Gradient for b∂L/∂b = (2/n) Σ(ŷᵢ−yᵢ)
The update rulew := w − α·∂L/∂w, b := b − α·∂L/∂b
ŷ the model's prediction w weight — the slope knob b bias — the height knob α learning rate — the step size Σ add up, one term per data point slope for one knob, other knobs held still n number of data points L the loss — how wrong, overall
Common pitfalls to watch for

Learning rate too high

The loss oscillates wildly or diverges instead of shrinking — every step overshoots the bottom of the bowl (Section 6's third hiker).

Learning rate too low

Training technically works but takes far too long to converge — thousands of timid steps (the first hiker, still crawling).

Unscaled features

Features with very different ranges (square feet vs. bedroom count) produce wildly imbalanced gradients and unstable training. Normalize or standardize features first (Section 5's tug-of-war).

Local minima

Our loss is a perfect bowl with one bottom — but more complex models have bumpy surfaces where descent can settle into a valley that isn't the lowest one. Advanced optimizers (later chapters) help escape.

The whole chapter in one sentence

Machine Learning, at its core, is adjusting weights and biases in the direction that reduces prediction error, guided step-by-step by derivatives — and gradient descent is simply the disciplined, repeated application of that idea until the predictions are as accurate as possible.

Join the discussion

Comments

Leave a comment on the chapter