2.2.4 · D4Linear & Logistic Regression

Exercises — Cost function (MSE) and gradient descent fitting

3,073 words14 min readBack to topic

These problems build up from "can you read the formula" all the way to "can you invent your own reasoning about it." Each has a full solution hidden inside a collapsible callout — try first, then reveal. Every level ends with a trap callout: the wrong path that feels right, and how to escape it.

Parent: Cost function (MSE) and gradient descent fitting. If any symbol below is unfamiliar, that parent note builds it from zero.


Level 1 — Recognition

Can you read the machine's parts and name them?

Exercise 1.1

In the update rule , name each of the three pieces and say in plain words what each contributes to one step.

Recall Solution
  • — the parameter we are tuning (a number like a slope or intercept). This is what moves.
  • — the learning rate, a small positive number. It answers "how far do we step".
  • — the partial derivative (slope of the cost surface along the direction). It answers "which way is downhill, and how steep".

One step = look at the slope (derivative) → decide how far to move () → move in the downhill direction (the minus sign flips uphill-slope into a downhill-move).

Exercise 1.2

The cost is . What does the factor do, and does removing it change where the minimum sits?

Recall Solution

The exists only to cancel the that the power rule drops when we differentiate . It makes the gradient tidy: instead of .

It does not move the minimum. Scaling a whole function by a positive constant stretches its height but never shifts the horizontal location of the lowest point: if minimises , it also minimises . So is pure convenience.

Exercise 1.3

For , what is and ?

Recall Solution

appears alone (coefficient ), so . multiplies , so . This is exactly why the two update rules differ: the update sums plain errors, the update sums errors weighted by .


Level 2 — Application

Turn the crank: plug numbers into the machinery.

Exercise 2.1

Dataset . With , compute the cost .

Recall Solution

Predictions: , . Errors : , .

Exercise 2.2

Same dataset , same . Compute both gradients and .

Recall Solution

First, why do the s cancel here? We differentiate the inner squared term . The power rule pulls down the exponent : . That freshly-produced meets the sitting in front of , and — so the factor vanishes, leaving the clean . That is the whole reason the was placed there.

Now plug in. Recall (bias feature) and . Errors from 2.1: . Here . Both negative → both parameters should increase (subtracting a negative).

Exercise 2.3

Continue: with , do one full simultaneous update. Report new .

Recall Solution

Use the old values for both updates (that's what "simultaneous" means). New parameters: .

Exercise 2.4

Verify the step helped: compute at the new and confirm it dropped below .

Recall Solution

✓ — the cost fell, so the step went downhill.


Level 3 — Analysis

Reason about the behaviour, not just the number.

Exercise 3.1

The parent's Example 1 got , larger in magnitude than . Why is the gradient consistently bigger here, and what problem does that cause? Study the figure below.

Figure — Cost function (MSE) and gradient descent fitting
Recall Solution

Guide to the figure: the black rings are level curves of the cost — each ring is a set of pairs with the same cost, like altitude lines on a map. The red ring is one such contour highlighted so you can see the shape clearly: it is an ellipse squashed thin along the horizontal axis and tall along the vertical axis. The black dot is the minimum. The red arrow marks the steep direction.

Why the shape: the gradient weights each error by (values ), while the gradient weights by . Larger values inflate the slope, so the surface is steep along and shallow along — exactly the squashed ellipse you see.

Problem: one shared must serve both directions. Set it safe for the steep axis → progress along the shallow axis is painfully slow; the path zig-zags across the valley. This is precisely what feature scaling fixes — rescaling makes the ellipse round.

Exercise 3.2

A student uses on the parent's dataset and finds grows each iteration. Explain geometrically why, and what range keeps it shrinking. Study the figure below.

Figure — Cost function (MSE) and gradient descent fitting
Recall Solution

Guide to the figure: the black curve is the cost bowl over a single parameter. The red zig-zag path starts near the left wall and, because each step is too long, lands higher on the opposite wall — then higher again. Each red arrow is one gradient-descent step; watch them climb outward instead of settling into the black dot (the true minimum). That outward climb is divergence.

Why: the negative gradient points downhill, but decides how far you commit to that direction. If is too large you leap past the valley bottom and land higher on the opposite wall. Next step you overshoot back even further → cost diverges.

How large is "too large"? First, some vocabulary. The curvature of the bowl is how fast its slope changes as you move — a steep, tightly-curved valley has high curvature, a shallow flat one has low curvature. For a bowl in several parameters, the curvature is different along different directions; the mathematical object storing all these curvatures is the Hessian (the matrix of second derivatives of ). Its eigenvalues are exactly the curvatures along the surface's natural axes, and we write for the largest one — the steepest direction. Convergence for a quadratic needs : the step must be small enough not to overshoot the steepest axis. Practically: if you see increase, cut by 10× and retry. Adaptive schemes live in learning-rate schedules.

Exercise 3.3

Argue that gradient descent on MSE for linear regression can never get stuck in a "false" local minimum. Which vault topic names this property?

Recall Solution

is a sum of squared linear functions of . Each squared term is a bowl (convex); a sum of bowls is a bowl. A bowl has exactly one lowest point — no side dips to get trapped in. So every downhill path reaches the global minimum.

This "single-bowl" property is convexity; the topic is convex optimization. Note: logistic regression needs a different cost precisely because plugging its nonlinear hypothesis into MSE would break this bowl shape.


Level 4 — Synthesis

Combine pieces into something new.

Exercise 4.1

Derive the gradient for the single-example update (this is stochastic gradient descent) from the batch rule, and explain why the single-example gradient still points, on average, in the same direction as the true batch gradient.

Recall Solution

Batch: . Drop the sum and the average, keep a single example chosen at random: Why this is still valid — the unbiased-estimator argument. First, one piece of notation: means the expected value — the long-run average of a random quantity if you repeated the random draw many times. (If you pick a random example again and again, is the average of what you get.) The batch gradient is exactly the average of the per-example gradients . If we pick uniformly at random from , each index is equally likely, so the expected (average) value of the single-example gradient is So on average the noisy single-example step points exactly along the true downhill direction — that is what "unbiased estimator" means. Any one sample is a scattered arrow, but its average is the correct arrow, so over many steps the wander cancels and you descend. Advantage: each update costs one example instead of — huge datasets update far more often per second. Cost: the per-step noise means you usually need a shrinking (schedules) to settle.

Exercise 4.2

For dataset you are told the exact best-fit line. Find by reasoning (two points → one line), then confirm both gradients are zero there.

Recall Solution

Two points determine a line exactly, so the best fit passes through both → zero error → global min. Slope ; intercept (line at ). Line: . Check errors: ; . Both zero ✓ — at the minimum the surface is flat, so gradient descent would take a step of size and stop.

Exercise 4.3

The normal equation gives in one shot. For the dataset in 4.2, plug into and confirm it returns ; then state when you'd prefer gradient descent instead.

Recall Solution

Build (first column of s for the intercept), . Computing returns — the same interpolating line found by reasoning in 4.2, as it must, since an exact-fit dataset has a unique zero-residual solution. Prefer gradient descent when: (rows) or number of features is large, since the normal equation needs the matrix inverse of . For millions of features, iterative descent — especially SGD — is the only feasible option.


Level 5 — Mastery

Invent, generalise, defend.

Exercise 5.1

Suppose someone replaces the square in MSE with a cube: . Give two independent reasons this is a broken cost function.

Recall Solution

Reason 1 — sign leak (positives and negatives cancel). A cube keeps the sign of its input: but . So a large negative error contributes a large negative cost that can cancel a large positive error. Concretely, take two errors and : their cubes are and , summing to . The cost reports — "perfect fit" — while both predictions are off by . Squaring forbids this because always, so errors can only add up, never cancel.

Reason 2 — no minimum to descend to (unbounded below). A valid cost must have a floor — a lowest value the algorithm can aim at. The cube has none. Fix any single example and push its prediction (achievable by driving large in the right direction); then , so . Gradient descent, always seeking lower cost, would ride this bottomless slope forever, sending off to infinity and never converging. A bowl (the square) has a finite lowest point; a cube is an endless downhill on one side.

(Bonus third reason: the cube is not convex, so it also breaks the single-global-minimum guarantee of Ex 3.3.)

Exercise 5.2

Design a tiny 2-point dataset where gradient descent with a fixed converges very slowly no matter how you choose , and justify using the ellipse idea from Ex 3.1.

Recall Solution

Use widely different magnitudes, e.g. and . The gradient weights errors by , so the huge makes the surface enormously steep along and nearly flat along — an extreme, thin ellipse. Any single safe for the steep axis (, tiny) crawls along the flat axis; any big enough to move the flat axis explodes the steep one. Slow either way. The real fix is not tuning but reshaping the surface: feature scaling rescales so both axes have comparable curvature, turning the ellipse round.

Exercise 5.3

Explain why the identical gradient-descent machinery here reappears in neural networks, and name the single new ingredient a network adds.

Recall Solution

The recipe never changed: define a cost , compute for every parameter, then step . Linear regression has a simple hypothesis , so each partial derivative is a one-line calculation (Ex 1.3). A neural network stacks many nonlinear layers, so its is a deep composition of functions — the output depends on the input through layer after layer. Computing for a parameter buried in an early layer therefore needs the chain rule applied repeatedly, once per layer. The single new ingredient is backpropagation: a systematic, efficient bookkeeping of that repeated chain rule, reusing each layer's stored intermediate result so all partials are computed in one backward sweep instead of recomputing from scratch. Crucially, the update rule itself is unchanged — only the way we obtain the gradient is new.


Recall Self-test cloze recap

Simultaneous update means compute all gradients from ::: the old parameter values, then overwrite all at once MSE is guaranteed to have one global minimum because it is ::: convex (a sum of squared linear terms = a bowl) The term equals ::: If cost increases every iteration, the culprit is usually ::: a learning rate that is too large SGD's single-example gradient is a valid step because ::: its expected value equals the true batch gradient (unbiased estimator) The single new ingredient a neural network adds to this machinery is ::: backpropagation (efficient repeated chain rule)