2.2.3 · D2Linear & Logistic Regression

Visual walkthrough — Ordinary least squares derivation

2,838 words13 min readBack to topic

This is the visual walkthrough child of the OLS derivation. The parent proved the Normal Equation with algebra. Here we draw it — every step is a picture, every symbol earns its place before it appears. If you have never seen a matrix, a transpose, or a gradient, start here. We build all of it.


Step 1 — The data, the guess, and the miss

WHAT. We start with plain dots on a grid. Each dot is one training example: a horizontal position (the input we know) and a vertical position (the answer we want to predict). We then draw a candidate straight line and measure how badly it misses each dot.

WHY. Before any formula, we must be crystal-clear on what "wrong" means. Everything downstream is just "make this wrongness as small as possible."

PICTURE (Step-1 figure): blue data dots, a yellow guess line, and pink vertical sticks marking each miss.

Figure — Ordinary least squares derivation

A straight line is written .

The red vertical stick from a dot up (or down) to the line is the residual:

If the line is above the dot, is positive; below, negative. Look at the red sticks in the figure — some point up, some down.


Step 2 — Why we square the misses

WHAT. We turn each red stick into a square: a little box whose side is the residual. The total "badness" is the sum of the areas of these boxes.

WHY. Two problems with just adding raw residuals: (1) up-misses and down-misses would cancel and pretend the line is perfect; (2) we want big misses to hurt more than small ones. Squaring fixes both — every square is positive, and a miss of makes a box of area while a miss of makes only .

PICTURE (Step-2 figure): each pink miss redrawn as a shaded square whose area is the squared error; total shaded area is the cost.

Figure — Ordinary least squares derivation

The best line is the one that makes the total box area smallest. That is the entire optimisation. (See Linear Regression Fundamentals for the model itself.)


Step 3 — Stacking everything into one matrix picture

WHAT. Writing out for every is tedious. We stack the dots into a table , the answers into a column , and the two knobs into a column . Then all predictions at once are the single product .

WHY. With one clean object we can use calculus once instead of chasing and separately. This is where linear algebra pays for itself.

PICTURE (Step-3 figure): the table , the knob column , and their product shown side by side, with the column of 1s highlighted.

Figure — Ordinary least squares derivation

Before we measure the length of the residual we need one new symbol, the transpose.

Now the cost from Step 2 collapses to a length:

Here is the length of the residual column — Pythagoras in dimensions. Small length = good line.


Step 4 — The geometry: predictions live on a flat sheet

WHAT. Think of as a single arrow in a high-dimensional space (one axis per dot). As we turn the two knobs , the prediction arrow can only reach points on a flat sheet (the column space of ). We cannot reach itself unless it happens to lie on the sheet.

WHY. This is the picture that makes the answer obvious. Minimising means: find the point on the sheet closest to . Geometry gives that instantly — it is the shadow (projection) of onto the sheet.

PICTURE (Step-4 figure): the pink arrow floating above a blue tilted sheet, its yellow shadow on the sheet, and the white residual arrow standing straight up between them.

Figure — Ordinary least squares derivation

The closest point is where the residual arrow is perpendicular to the sheet. Any other spot on the sheet is farther from (slanted stick is longer than the vertical drop). That perpendicularity is the whole secret of the next step.


Step 5 — "Perpendicular" written as an equation

WHAT. Perpendicular means "no shadow along the sheet's directions." The sheet's directions are exactly the columns of . So the residual must be perpendicular to every column of at once.

WHY. A geometric statement ("perpendicular") becomes an algebraic one ("dot product "), which we can actually solve.

PICTURE (Step-5 figure): a blue column-direction arrow and a white residual arrow meeting at a right-angle marker, captioned "dot product = 0."

Figure — Ordinary least squares derivation

Perpendicular arrows have dot product zero. The transpose from Step 3 packages "dot with every column of " into one product :

This is called the Normal Equation because "normal" is the old geometry word for perpendicular (see the upright arrow in Step 4). Rearrange:


Step 6 — Same answer from calculus (the valley floor)

WHAT. We repeat Step 5's result, this time by rolling downhill on the cost surface instead of using geometry. Plot over the two knobs: it is a bowl. The bottom is where the ground is flat — the gradient is zero.

WHY. Two independent routes landing on the same equation is the strongest evidence it is right. Calculus also generalises when we later add regularisation (see Ridge Regression).

PICTURE (Step-6 figure): the bowl-shaped cost surface over the two knobs, with a pink dot marking the flat bottom where the gradient vanishes.

Figure — Ordinary least squares derivation

Differentiating term by term:

Set the gradient to zero — the from Step 2 exactly cancels the from the square's derivative (that was its whole purpose) — and we recover

Same equation as Step 5. Geometry and calculus agree. (Rolling downhill iteratively instead of jumping to the bottom is Gradient Descent.)


Step 7 — Solve, and the bowl-vs-trough edge case

WHAT. If can be undone (inverted), multiply both sides by its inverse to isolate . If it cannot be inverted, the bowl is not a bowl — it is a flat-bottomed trough, and infinitely many lines tie for best.

WHY. A formula is only useful if we know when it breaks. The trough case is the difference between "one answer" and "no unique answer."

PICTURE (Step-7 figure): left, a genuine bowl with one lowest point (unique best line); right, a flat-bottomed trough whose whole valley floor ties for best (singular case).

Figure — Ordinary least squares derivation

Let be the number of dots and let be the number of feature columns in (so has columns once the 1s column is added). The formula works exactly when the columns of are linearly independent (nothing is a copy or blend of the others) — call this full column rank.

Left panel (good): columns of point in genuinely different directions → true bowl → one lowest point → one best line.

Right panel (degenerate): the columns are not independent (multicollinearity) — for example one feature is a scaled copy of another. Then the two sheet-directions collapse onto the same line, the bowl flattens along a valley, , and does not exist.


Step 8 — A tiny numeric run you can check by hand

WHAT. Use three dots and crank the formula once, end to end.

WHY. Numbers make the abstract machine concrete, and confirm the boxes really do get smallest.

Check at : , close to the true . The line threads the dots — exactly the "smallest boxes" line from Step 2.


The one-picture summary

PICTURE (summary figure): on the left the fitted line with its pink residual sticks; on the right the same story as geometry — 's shadow on the sheet with the perpendicular residual — jointly giving .

Figure — Ordinary least squares derivation

Left: dots + best line + the red residual sticks. Right: the same story as geometry — 's shadow lands on the sheet, and the residual stands perpendicular, giving , i.e. .

Recall Feynman retelling (say it to a 12-year-old)

We scatter dots and want the fairest straight line. "Fair" = the total area of little squares built on each vertical miss should be as small as possible. Squares (not raw gaps) because we do not want ups and downs to cancel, and we want big misses punished hard. We pack the dots into a table , the answers into a column , and our two dials (height and tilt) into ; then all predictions are just . Picture floating in the air and all reachable predictions living on a flat sheet — the closest we can get is 's shadow, and the leftover gap points straight up off the sheet. "Straight up" means the gap has no overlap with the sheet's directions, which are the columns of ; written down (using the transpose to dot with every column at once), that is . Solving gives . Rolling downhill on a bowl-shaped cost gives the exact same equation, so we trust it. The one catch: if two dials secretly do the same thing (a copied feature) or we have more dials than dots, the bowl flattens into a trough and there is no single best line — then we drop the copy or add a gentle tilt (Ridge) to scoop the trough back into a bowl.

Recall Quick self-test

Why is it called the Normal equation? ::: "Normal" is geometry-speak for perpendicular: at the best line the residual is perpendicular to the column space of , giving . What does (transpose) let us do in one multiplication? ::: Lay a column on its side so a row-times-column product adds up the squares, = length squared. What role does the column of 1s in play? ::: It carries the intercept ; without it the line is forced through the origin. When does fail to exist? ::: When 's columns are not independent (duplicate/scaled features, or ) — the bowl becomes a flat trough with infinitely many best . In the trough case, does a closest point still exist? ::: Yes — the perpendicular projection always exists; it is the labelling that becomes non-unique. Where did the in the cost go? ::: It cancels the factor of 2 from differentiating the square, so the gradient stays clean.

Connections: Gradient Descent (the iterative cousin), Ridge Regression (fixing the trough), Maximum Likelihood Estimation (why squared error under Gaussian noise), QR Decomposition & Pseudoinverse (solving without forming ), Feature Scaling, Bias-Variance Tradeoff.