2.2.4 · D3Linear & Logistic Regression

Worked examples — Cost function (MSE) and gradient descent fitting

2,954 words13 min readBack to topic

This page is a case atlas. The parent note built the two machines: the cost (how wrong we are) and the update rule (how we fix it). Here we run those machines by hand across every situation they can meet — good learning rates, bad ones, flat data, single points, and a real word problem.

Recall the two tools we reuse everywhere (from the parent). First the cost — our single number for "how wrong is this line?":

And the update lines — how we push the line downhill:

The word residual just means — the leftover gap between what we said and what happened. Positive residual = we guessed too high; negative = too low.


The scenario matrix

Every gradient-descent problem lands in one of these cells. The examples below are labelled with the cell they cover.

Cell What makes it special Covered by
A. Baseline good Small clean dataset, sane step size, cost drops Ex 1
B. too large (divergence) Overshoot; cost grows each step Ex 2
C. too small Cost drops but crawls; many steps needed Ex 3
D. Perfect fit / zero residual Data lies exactly on a line; gradient Ex 4
E. Flat / degenerate data ( all equal) can't be determined; only moves usefully Ex 5
F. Negative slope data Best line goes down; check signs of the gradient Ex 6
G. Single point () Degenerate limit; infinitely many perfect lines Ex 7
H. Real-world word problem Units, interpretation, prediction from fitted line Ex 8
I. Exam twist: start at the optimum Already minimised; verify gradient stays zero Ex 9

Ex 1 — Cell A: baseline, a healthy learning rate

Forecast: The true line is obviously (so should climb toward , stay near ). Guess: after one step jumps up a lot, a little.

  1. Predictions. . Why this step? Both parameters are zero, so the line is flat on the -axis — every prediction is .
  2. Residuals : . Why this step? These signed gaps drive both updates; all negative means we're guessing too low everywhere.
  3. Gradients. Why this step? 's gradient averages the raw residuals; 's weights each residual by its (bigger pulls harder on the slope).
  4. Update. , . Why this step? We subtract the gradient, so a negative gradient pushes the parameter up — exactly toward the true .

Verify: Cost before . New predictions give residuals ; new cost . Cost fell ✓ — healthy descent. Why this step? We recompute with the updated line to confirm the step actually went downhill; a lower cost is the only proof the update helped.

The figure below shows this single step: the grey flat line is the start (), the butter vertical bars are the three residuals pulling the line up, the lavender line is where we land after one update, and the dashed mint line is the true we are heading toward. Notice the lavender line already tilts most of the way to mint — one healthy step covers a lot of ground.

Figure — Cost function (MSE) and gradient descent fitting

Ex 2 — Cell B: learning rate too large (divergence)

Forecast: A giant step. Do we still land near , or fly past it? Guess before reading.

  1. Gradients are identical to Ex 1: and (same data, same start). Why this step? The gradient depends only on the current point on the surface, not on .
  2. Update with . , . Why this step? One times a big gradient is a big leap — we hurl the slope from all the way to .
  3. New cost. Predictions : . Residuals . Cost . Why this step? We overshot so hard the line is now steeper than needed and above every point.

Verify: Cost went — it increased 20-fold. This is divergence: with too big we climbed the far wall of the valley. Fix by shrinking (see 4.2.03-Learning-rate-schedules). Why this step? Recomputing after the step is how we detect divergence — a rising cost is the alarm bell that is too large.

In the figure below, the grey line is again the start, but now the coral line (our one step with ) shoots far above every data point — its slope badly overshoots the true slope (dashed mint). The annotation marks where it "flew over the valley": instead of settling into the bowl, we launched up the opposite wall, which is why the cost grew instead of shrinking.

Figure — Cost function (MSE) and gradient descent fitting

Ex 3 — Cell C: learning rate too small

Forecast: Correct direction, but how far? Guess: barely moves.

  1. Same gradients: , . Why this step? Data and start point are unchanged from Ex 1, and gradients ignore , so they are exactly the same numbers.
  2. Update. , . Why this step? Multiplying by a tiny gives a tiny nudge — right direction, almost no progress.

Verify: New predictions give ; residuals ; new cost . It dropped from but only by — at this rate we'd need hundreds of iterations. Why this step? We plug the updated parameters back into the same MSE formula to confirm the cost did move in the right direction; the tiny drop is the fingerprint of the classic "too small" symptom — correct but painfully slow.


Ex 4 — Cell D: data already perfectly on a line (zero residual)

Forecast: We're already sitting in the valley floor. What should the gradient be?

  1. Predictions. — exact. Why this step? Plugging the true parameters reproduces the data.
  2. Residuals. . Why this step? Perfect predictions leave zero gap.
  3. Gradients. Both sums contain only 's . Why this step? Every term is (residual)something, and residual .
  4. Update. nothing moves. Why this step? A zero gradient times any is zero, so the parameters stay put — this is a fixed point.

Verify: Cost , the global minimum. This is the fixed point of gradient descent: zero gradient no update, regardless of . This is why a convex bowl (see 3.1.02-Convex-optimization) has exactly one resting place. Why this step? Confirming proves we are literally on the valley floor — there is nowhere lower to go, so descent correctly does nothing.


Ex 5 — Cell E: degenerate data, all equal

Forecast: Can we ever pin down a slope when the input never varies? Think first.

  1. Predictions all ; residuals . Why this step? With both parameters zero the line is flat, so each prediction is and the residual is just .
  2. Gradients. . . Why this step? Both gradients are non-zero, so the parameters will move.
  3. Update. . Why this step? Subtract times each gradient; both go up because both gradients are negative.

Verify: Both change, but note is meaningless here: the model only ever sees , so . Only the combination is determined. Check: after the step , moving toward . Why this step? Tracking the combination (not each parameter alone) is the only meaningful sanity check when the slope is unidentifiable — infinitely many pairs give the same fit. Feature variation is required (this is exactly what 2.2.05-Normal-equation would show as a singular matrix, and why 2.06-Feature-scaling-and-normalization matters).


Ex 6 — Cell F: negative-slope data (sign check)

Forecast: Truth has a negative slope. Should go up or down on step one?

  1. Predictions ; residuals . Why this step? All predictions are below the data, so all residuals negative.
  2. Gradients. . . Why this step? Weighting the negative residuals by still gives a negative sum, so this early gradient does not yet "know" the slope should be negative.
  3. Update. . Why this step? First step both go up — even though the true slope is negative! The gradient reacts to the current error, not the final answer.

Verify: After this step the line over-tilts up, but the next iterations will pull back down past zero toward . Predictions ; residuals ; new cost , down from ✓. Why this step? We plug back into the MSE formula to confirm the cost genuinely fell, proving the "wrong-looking" up-step is still downhill on the surface — direction on the cost surface, not the sign of the final slope, is what governs a single step.

In the figure below, the grey start line () sits below all three coral points. The lavender line (after one step) tilts upward — the annotation flags this: step 1 tilts up even though the true line (dashed mint ) slopes down. This is the whole lesson of Cell F: a single gradient step follows the current residuals, and only over many steps does swing down through zero to the correct negative slope.

Figure — Cost function (MSE) and gradient descent fitting

Ex 7 — Cell G: single point, (degenerate limit)

Forecast: How many lines pass exactly through one point? (Answer: infinitely many.) So what does descent do?

  1. Prediction ; residual . Why this step? With flat start the prediction is , so the gap to is .
  2. Gradients (, no averaging needed): , . Why this step? With one example the is ; the slope gradient is inflated by the large .
  3. Update. . Why this step? Subtract times each gradient; the big slope gradient produces a big jump in .

Verify: New prediction , residual — we overshot ! The true minimum is any line with (a whole line of solutions, cost ). Why this step? Plugging the updated line back through the single point exposes the overshoot (, the residual flipped sign), and it shows the fit is under-determined — with one point and this the effective step is large because inflates the slope gradient. Lesson: has no unique fit; you need at least two distinct values.


Ex 8 — Cell H: real-world word problem

Forecast: Slope "extra coffees per barista" . Guess heads toward .

  1. Predictions ; residuals (coffees). Why this step? Units: residuals are in coffees, the same units as — every quantity that flows out of a residual (both gradients) therefore also carries a coffee-unit, which is exactly why must be chosen small.
  2. Unit ⟷ learning-rate reasoning. Because values are large (), residuals are large, so the gradients are large (). A step is ; with a "normal" the slope would jump by in one step and overshoot wildly. Why this step? The size of the gradient scales with the units and magnitude of your data. Big-valued targets demand a smaller (here ) or, better, feature/target scaling so a single works regardless of units.
  3. Gradients. . . Why this step? 's gradient averages the raw coffee residuals; 's weights each residual by the barista count.
  4. Update. , . Why this step? We subtract times each gradient; the small keeps the slope jump modest () so we creep stably toward the true instead of overshooting.
  5. Post-update predictions (sanity peek). , , — still far below the data, as expected after just one gentle step. Why this step? Checking predictions confirms we moved in the right direction (all predictions rose from ) without any wild overshoot — the small- choice paid off.

Verify (fitted answer): Running to convergence, the least-squares line has slope and intercept . Derivation: ; , then . Prediction for 4 baristas: coffees. Why this step? We solve for the exact optimum (the same line 2.2.05-Normal-equation gives) to state the forecast the problem asked for; the units check — coffees/barista baristas coffees ✓ — confirms the prediction is dimensionally sensible, and sits just above the last data point , matching a rising trend.


Ex 9 — Cell I: exam twist — start already at the optimum

Forecast: At the minimum the gradient should be zero — so even a huge does nothing. True or false?

  1. Predictions. . Why this step? Plug the fitted line into each to get the best-fit predictions.
  2. Residuals. . Why this step? Least squares makes residuals sum to zero and their -weighted sum zero — that's the defining condition.
  3. Gradients. . . Why this step? Both defining conditions of least squares force these sums to zero.
  4. Update. — no change. Why this step? Anything times a zero gradient is zero, so size is irrelevant at the minimum.

Verify: Even with (large), nothing moves because both gradients are . This confirms the least-squares point is the fixed point of gradient descent — the same solution 2.2.05-Normal-equation gives in one shot. Residuals do not vanish here (data isn't perfectly linear), but their weighted sums do, which is what "minimum" means. Why this step? Verifying the gradients are zero (not the residuals) is the exam trap: a big is harmless only because the gradient — not the residual — is what gets multiplied by , and at the optimum that gradient is exactly zero.


Recall Self-check

One step of GD on divergent makes cost go which way? ::: Up — it increases (Ex 2 went ). Why does gradient descent stop at the least-squares line even with big ? ::: The gradient is exactly zero there, so every update subtracts . With all equal, which parameter is unidentifiable? ::: The slope — only the combination is determined. First GD step on negative-slope data pushes which way from ? ::: Up (positive), because early residuals are all negative; it corrects later.

See also: 2.2.03-Hypothesis-representation-in-linear-regression, 2.3.02-Logistic-cost-function, 2.4.01-Gradient-descent-for-neural-networks, 4.2.01-Stochastic-gradient-descent.