Part I ยท Ch. 3 โ€” Fitting a Line

Part I ยท Chapter 3 of 13

Fitting a Line

Linear regression: the 'hello world' of machine learning


Which line is best?

Here are three measurements that almost line up: the points $(1, 1)$, $(2, 4)$, and $(3, 4)$. Your eye wants to draw a straight line through them, sloping up. But there are infinitely many lines you could draw, and no single one hits all three. Which is best โ€” and could a machine find it without you ever telling it the answer? That question, answered honestly, is your first real piece of machine learning.

What we are about to do has a name: linear regression, the "hello world" of the whole field โ€” the smallest example that still contains every moving part of how machines learn. Get it for real and you have the skeleton of everything from here to the largest models alive.

The plan in one sentence: first a model with a dial, then a way to measure its wrongness as a single number you can see, then the discovery that all those numbers form a smooth bowl, and finally the downhill walk from the toolkit chapter that finds the bottom of that bowl on its own. Let us make the question vivid before any math.

A quadrant plot with input x across and output y up. Three blue data dots sit at (1, 1), (2, 4) and (3, 4). Two mint lines rise from the origin: a shallower dashed line labeled 'w = 1?' and a steeper solid line labeled 'w = 1.5?'. Neither line passes through all three dots.
Three points that almost line up, and two of the infinitely many lines through the origin. Your eye prefers the steeper one โ€” but "prefers" is not a number. To let a machine choose, we first have to measure exactly how wrong each line is.

A model with a dial

Start with the simplest function that can fit rising data: a line through the origin, where the prediction is just the slope times the input. Writing the model's guess as $\hat{y}$ โ€” read "y-hat, the model's guess" โ€” the model is

$$\hat{y} = w \cdot x$$

In words: to guess, multiply the input by the dial $w$. That single number $w$ is the slope, and it is the one thing we get to adjust โ€” a weight.

Turning the dial changes the whole line's steepness at once. Watch what three settings do to our three inputs $x = 1, 2, 3$:

Worked example โ€” three settings of the dial

dial $w$guess at $x=1$guess at $x=2$guess at $x=3$
$w = 1$123
$w = 1.5$1.534.5
$w = 2$246

Same machine, three attitudes โ€” and none of them matches the real values $1, 4, 4$ exactly.

So here is the whole game in one sentence: learning this model means finding the one value of the dial $w$ that makes the predictions closest to the real values. To do that, we first have to say what "closest" means with a number.

One honest aside, planted for later: a line through the origin is a deliberate simplification โ€” it always passes through $(0, 0)$. Real lines also have a height, an intercept. We add that second dial near the end; for now, one dial keeps every number checkable by hand.

Wrongness you can see

Before we make the error a number, let us make it visible. For a given line, each data point sits some vertical distance above or below the line โ€” that gap is the residual, the model's miss on that point. We draw residuals as red segments, because on this site red always means error.

The mint line y = 1.5x through three blue dots at (1, 1), (2, 4) and (3, 4). A red vertical segment joins each dot to the line: length 0.5 at x = 1, length 1 at x = 2, length 0.5 at x = 3. Beside each segment sits a faint red square whose side equals the residual, labeled with its area 0.25, 1 and 0.25. A note reads 'square each miss, then average, L = (0.25 + 1 + 0.25) / 3 = 0.5'.
The loss, made of literal squares. Each red segment is a residual โ€” how far the line missed that point โ€” and each red square has that miss as its side, so its area is the squared error. Average the three areas and you get the mean squared error, $L = 0.5$. Squaring is why the big miss in the middle dominates the score.

Now turn those misses into one number, confronting the design choices out loud. We cannot just add the residuals up: overshoots (positive) and undershoots (negative) would cancel, and a wildly wrong line could score zero. The fix is to square each residual first. Squaring makes every miss positive and punishes big misses far more than small ones โ€” a miss of 2 costs 4, while a miss of 1 costs only 1. Then average over the points to get one score. That score is the mean squared error, our loss $L$.

One piece of notation first, because it turns up in nearly every equation from here on. That tall symbol $\sum$ is a capital Greek sigma, and it means nothing more alarming than "add these up." Written $\sum_{i=1}^{N}$, it says: let $i$ count through the examples โ€” 1, then 2, and on up to $N$ โ€” work out whatever follows it once per example, and add the results. It is a for-loop wearing a robe. The little subscripts do the same counting job: $x_i$ and $y_i$ mean "the input and the real value of example number $i$." For our three points, $\sum_{i=1}^{3}$ is just example 1's answer plus example 2's plus example 3's.

Written for our $N$ examples โ€” here $N = 3$ โ€” the loss is the average over the points of (prediction minus truth) squared:

$$L(w) = \frac{1}{N} \sum_{i=1}^{N} \left( \hat{y}_i - y_i \right)^2 = \frac{1}{N} \sum_{i=1}^{N} \left( w \cdot x_i - y_i \right)^2$$

In words: for each point, take how far off the guess was, square it, and average those squared misses. Notice the loss depends on the dial โ€” a different $w$ gives a different wrongness โ€” which is why we write it $L(w)$.

Worked example โ€” the loss at $w = 1.5$

At $w = 1.5$ the predictions are $1.5, 3, 4.5$ against the real values $1, 4, 4$. The residuals (prediction minus truth) are $-0.5$, $+1$, $-0.5$; their squares are $0.25$, $1$, $0.25$:

$$L(1.5) = \frac{(-0.5)^2 + (1)^2 + (-0.5)^2}{3} = \frac{0.25 + 1 + 0.25}{3} = \frac{1.5}{3} = 0.5$$

Two more, by the same recipe: at $w = 1$ the squared misses are $0, 4, 1$, so $L(1) = 5/3 \approx 1.67$; at $w = 2$ they are $1, 0, 4$, so $L(2) = 5/3 \approx 1.67$.

In words: square each of the three misses, add them, divide by three โ€” and the dial at $w = 1.5$ scores $0.5$, well under the $1.67$ that $w = 1$ and $w = 2$ each score.

Look at the pattern, because it gives away the whole ending. The dial at $w = 1$ and the dial at $w = 2$ are equally wrong โ€” both score $1.67$ โ€” while $w = 1.5$ sits between them and is less wrong, at $0.5$. The wrongness dips in the middle. The next section reveals the shape that dip belongs to.

The loss is a bowl

Let us do what that last pattern teased: compute the loss for many settings of the dial and plot $L$ against $w$. The points do not scatter โ€” they fall on a smooth U-shaped curve, a parabola (the very shape from the toolkit's derivative section), with a single lowest point.

A mint parabola plotting loss L against slope w. Amber landmark dots sit at (0, 11), (1, 1.67), (1.5, 0.5), (2, 1.67) and (3, 11). The curve is symmetric about w = 1.5, whose loss of 0.5 is the lowest point, flagged with a mint ring and dashed guide lines to both axes. A note reads 'the best line = the bottom of the bowl'.
Every setting of the dial has a wrongness, and plotted together they form a bowl. It is symmetric about $w = 1.5$, whose loss of $0.5$ is the lowest available: the best line our model can draw. Learning is finding this bottom without being shown it in advance.

Read the landmark heights straight off the bowl, all hand-checkable by the same recipe: $L(0) = 11$ (a flat line stuck at zero, badly wrong), $L(1) = 1.67$, $L(1.5) = 0.5$ (the bottom), $L(2) = 1.67$, and $L(3) = 11$. The floor sits at $L = 0.5$ โ€” not zero, because no straight line through the origin can hit all three points at once. The best available line still misses a little, and that is fine.

This curve has a name that scales to the entire field: it is a loss landscape. Right now it is a one-dimensional bowl because we have one dial. Add more dials and it becomes a landscape in more dimensions โ€” a valley, then a mountain range โ€” but the goal never changes: find the lowest point. Training is landscape-descending.

That is what makes the ending inevitable. The best line is the bottom of the bowl, where the ground is flat โ€” and the toolkit chapter handed us the exact tool for finding flat ground by feel. We do not need to see the whole bowl or solve anything clever; we can walk down it.

Rolling downhill to the answer

Bring back the toolkit's downhill rule and aim it at the loss. To step downhill on the bowl, we need the slope of $L$ at our current dial โ€” the derivative $\frac{dL}{dw}$ โ€” and then we step against it. Re-naming the Greek letter as the house rules ask, $\eta$ is eta, the learning rate, which sets how big each step is:

$$w_{\text{new}} = w - \eta \, \frac{dL}{dw}$$

In words: to get the next dial setting, take the slope where you stand, shrink it by the learning rate, and subtract โ€” the minus sign is what sends you downhill instead of up.

We can build that slope from the residuals โ€” no calculus machinery, just the pattern. The slope of $L$ at a given $w$ is

$$\frac{dL}{dw} = \frac{2}{N} \sum_{i=1}^{N} x_i \left( w \cdot x_i - y_i \right)$$

In words: for each point multiply its input $x_i$ by its signed error (prediction minus truth), add those up, and scale by $2/N$. Points we are far off on, especially at large $x$, pull the slope the most.

One careful note, so nobody trips: this uses the signed error, prediction minus truth โ€” the opposite orientation to the residual we defined earlier as truth minus prediction. Squaring hid that sign, but the slope needs it, so we keep it explicit here.

Where did that formula come from? Two honest pieces, both already in your hands. The $2$ out front is the toolkit's $x^2 \to 2x$ pattern: the loss squares each miss, and the slope of a square is twice the thing being squared, so every miss contributes twice its own size. And each error is weighted by its own input $x_i$ because the dial reaches every prediction through that point's input โ€” nudge $w$ a little and the prediction at $x = 3$ moves three times as far as the prediction at $x = 1$, so the far-out point gets three times the say in which way we step.

And you can check the whole thing against the bowl we already drew. At the bottom, $w = 1.5$, the slope had better read zero. The signed errors there are $-0.5$, $+1$, $-0.5$; weight each by its input and add them: $1(-0.5) + 2(1) + 3(-0.5) = -0.5 + 2 - 1.5 = 0$. Flat, exactly where the bowl bottoms out. The formula and the picture agree.

Worked example โ€” the first downhill step, from $w = 0$

Start deliberately from a useless dial, $w = 0$: every prediction is $0$, so the signed errors (prediction minus truth) are $-1$, $-4$, $-4$. Weight each by its input:

$$\sum_i x_i(w x_i - y_i) = 1(-1) + 2(-4) + 3(-4) = -1 - 8 - 12 = -21$$

In words: multiply each signed error by the input that produced it, add the three products, and the weighted total of the misses is $-21$.

Scale that total by $\tfrac{2}{3}$ โ€” twice the average โ€” and you have the slope of the bowl at $w = 0$:

$$\frac{dL}{dw} = \frac{2}{3}(-21) = -14 \quad \text{at } w = 0$$

The slope is negative, so downhill is to the right. We will use $\eta = 0.1$ โ€” small enough that a slope as steep as $14$ does not fling us past the bottom, big enough that we actually get somewhere. The step is

$$w_{\text{new}} = 0 - 0.1 \times (-14) = +1.4$$

In words: the ground at $w = 0$ falls away to the right at $-14$, so a step of one tenth of that slope moves the dial from $0$ to $1.4$. One step took us from a flat, useless line to a slope of $1.4$.

The rest of the walk we summarize, since the full arithmetic is shown once above. From $w = 1.4$ the slope is about $-0.93$, nudging the dial to $1.49$; from $1.49$ the slope is about $-0.06$, nudging it to $1.50$. The steps shrink on their own as the ground flattens, and $w$ glides into $1.5$ โ€” the bottom of the bowl, the best line โ€” while the loss falls from $11$ to $0.5$. Nobody told the machine that $1.5$ was the answer; it found it by rolling downhill.

Sit with that for a second: this is machine learning. A model with a dial, a number for its wrongness, and a downhill walk that tunes the dial until the wrongness bottoms out. The exact same three parts โ€” model, loss, gradient descent โ€” train a network with a trillion dials. What you just did by hand is what a data center does at scale.

From one dial to two โ€” and to a trillion

Time to pay the debt from earlier: real lines have a height as well as a slope. We add a second dial, the intercept $b$, so the model becomes

$$\hat{y} = w \cdot x + b$$

In words: multiply the input by the slope dial, then add the height dial $b$. Now the machine can slide the whole line up and down as well as tilt it.

The tools stretch to fit without changing shape. With two dials, the slope of the loss is now two numbers โ€” how $L$ changes as we nudge $w$, and how it changes as we nudge $b$ โ€” stacked into a little vector, the gradient $\left[\frac{dL}{dw}, \frac{dL}{db}\right]$. The update rule is unchanged in spirit: step both dials against their own slopes at once. This is exactly the gradient from the toolkit, now earning its keep.

Reassure yourself with our own numbers: for this data the best intercept turns out to be $b = 0$ โ€” the ideal line already passes through the origin, because the data's centroid, the average point (the inputs average to $2$, the real values average to $3$), sits at $(2, 3)$, which lies exactly on $y = 1.5x$. That is the tell that no vertical shift of the line would help. Adding the second dial does not change our answer here; it just proves the method generalizes. That $b = 0$ is a feature of these three points, not a general rule โ€” for most data the best $b$ is nonzero, and the machine finds it by the same walk. (The widget below lets you switch on the intercept and watch this.)

Now scale the picture up: a neural network is this same story with millions or billions of dials instead of two โ€” a model that makes a guess, a loss that scores it, and a gradient (now a very long vector) that says which way every dial should move. The bowl becomes a mountain range nobody can see, but the walk is identical. You have met the engine of the entire field.

See it move

The video runs the whole story in one motion: the red residuals shrink as the line tilts, every line's wrongness collapses into a single dot that traces out the bowl, and then the ball rolls down that bowl from $w = 0$ while the line snaps to the best fit โ€” the same numbers as this chapter, with the loss falling $11 \to 0.5$ and the slope landing on $1.5$.

Watch (1:15): a machine learns for the first time โ€” a line with a dial, a visible loss that forms a bowl, and gradient descent rolling to the bottom to find the best slope, $1.5$, with no one supplying the answer.

Now you hold the dials. Drag the line over the three points and feel the loss respond; then press "Let it learn" and watch gradient descent do to the dials exactly what your hand was doing โ€” only guided by the slope instead of by your eye.

Where you'll meet this

Name the three parts you just built, because you will meet them in every remaining chapter of this site. A model (a function with dials), a loss (one number scoring its wrongness), and gradient descent (walking the dials downhill). Every method ahead is a choice of model and loss, trained by this same walk.

The next step is close by. Next chapter, Drawing Boundaries, keeps the model's score $\hat{y} = w \cdot x + b$ almost unchanged, but instead of reporting a number it squashes that score into a probability and asks "which class?" โ€” turning this chapter's regression into classification. The line you just fit becomes the boundary between two categories.

The leap into Part II is the same idea again: an artificial neuron is literally this chapter's weighted sum followed by one of the next chapter's squashes; a deep network is many such neurons stacked, trained by exactly the gradient descent you ran by hand โ€” just with backpropagation to compute the giant gradient efficiently. There is no new learning principle coming; there is only more of this one.

So "the machine learns" stopped being a metaphor in this chapter. You watched a dial find its own best value by feeling for downhill. Everything ahead is that same sentence, scaled up and dressed up โ€” and now you know what is underneath the dress.

What you now know

  • Linear regression models data with a line whose slope $w$ is an adjustable dial, $\hat{y} = w \cdot x$, and later a second dial, the intercept $b$.
  • Wrongness is the mean squared error: for each point take the residual (prediction minus truth), square it so misses cannot cancel and big misses count more, then average โ€” for our data at $w = 1.5$, $L = (0.25 + 1 + 0.25)/3 = 0.5$.
  • Plotting the loss against the dial reveals a bowl-shaped loss landscape whose bottom (here $w = 1.5$, $L = 0.5$) is the best line the model can draw.
  • Gradient descent finds that bottom by feel: it reads the loss's slope from the residuals, $\frac{dL}{dw} = \frac{2}{N} \sum_i x_i(w x_i - y_i)$, and steps against it โ€” from $w = 0$ the first step lands at $w = 1.4$ and the walk glides on to $1.5$.
  • The exact same three parts โ€” a model with dials, a loss that scores it, and gradient descent that tunes the dials downhill โ€” train everything in this site, from this two-dial line to networks with billions of dials.

Where we're headed. We just taught a machine to answer "how much?" โ€” predict a number. But a huge share of real problems ask a different question: "which one?" Spam or not spam. Cat or dog. Benign or malignant. The output is no longer a quantity but a category, and a straight line's job changes from threading through the points to slicing between them, becoming a boundary. Next chapter we keep almost everything from this one, add a single S-shaped function that turns a score into a probability, and draw our first decision boundary. It is where regression becomes classification.