Linear regression and gradient descent

Least squares, projections, MLE view, gradient descent

9 lessons · 23 past questions · 69 marks in the papers collected here

Open the interactive lessons →Linear regression and gradient descent past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. Orientation: what you will learn and why
  2. Big picture: concept map, four roads and the shape table
  3. Start here: vectors, matrices and slopes, from zero
  4. The model, the loss and how to read a fitted line
  5. The optimal weight: normal equations, intercept and scaling
  6. Geometry: projection, orthogonality and spans
  7. Which model can lower the training loss?
  8. Gradient descent: updates, learning rate, SSE versus MSE
  9. Probabilistic view: why least squares is maximum likelihood

1. Orientation: what you will learn and why

Linear regression fits a straight line (or a flat plane) through data so that the predictions are as close as possible to the real numbers. Almost every later topic in this course (Ridge, Lasso, kernels, cross-validation) is a small change to this one, so this page is the foundation. It also introduces gradient descent, the step-by-step method that machine learning uses when a formula is too hard to solve directly.

What you will be able to do

Why this topic matters for Quiz 2

Counted only from the PYQs in this project (not a prediction):

What the PYQs askPYQsMarks
Model, loss and reading a fitted line14
Optimal weight: normal equations, intercept, scaling515
Which model lowers training loss414
Geometry: projection and spans411
Gradient descent512
Probabilistic view (MLE)413

In total 23 PYQs worth 69 marks across 9 papers (12 MCQ, 4 MSQ, 7 numeric). Gradient descent is a pure computation block; the geometry and normal-equation questions are short conceptual checks that reward knowing three or four facts exactly.

How this topic connects

In the likelihood section you attach a probability model to the data: $y\sim N(w^Tx,\sigma^2)$. Next topic (Ridge, Lasso and MAP) adds a penalty to the same loss. Kernel regression writes the same solution as $w=X\alpha$.

Tags: [SRC] comes from your files, [DERIVED] is an answer I worked out because the bank gives no key, [ADDED] is my own example, [FLAG] marks a disagreement with the bank.
How to use this page

Read a section, step through every worked example (predict the next step first), do the quick check, then attempt each PYQ before opening its solution.

What is new in this upgrade [ADDED]

The route through this topic
the lossnormal equationsgradient descentproperties and variants

2. Big picture: concept map, four roads and the shape table

[ADDED] This page shows the whole topic on one screen before the detail. Look at the picture first, then read the two tables. Every later section is one box of this map.

The concept map

DataX is (d, n), y is (n)Modelŷ = wTx (dummy 1 = intercept)LossL(w) = ‖XTw − y‖²Calculusset gradient = 0XXTw = XyGeometryXTw* = projection of yresidual ⊥ every featureGradient descentw ← w − η(2XXTw − 2Xy)many small stepsProbabilityGaussian noise: NLL =const + SSE/(2σ²)four different roads from the same lossSame answer w*w* = (XXT)−1Xy when XXT is invertible
Everything in this topic starts from the same loss. The four boxes in the middle are four different ways to reach the same optimal weight $w^*$. Each one is a section of this page.

Four roads, one destination

RoadWhat you doKey equationWhat it needsExam wording that points to it
CalculusSet the slope of the loss to zero in every direction and solve.$XX^Tw=Xy$$XX^T$ invertible for a unique answer"optimal weight", "minimiser", "sum of the elements of $X(X^Tw-y)$"
GeometryDrop a perpendicular from $y$ to the span of the features.$X(y-X^Tw^*)=0$nothing, only the span"orthogonal", "projection", "span", "zero error"
Gradient descentStart anywhere, repeat a small downhill step.$w\leftarrow w-\eta\nabla L$a learning rate $\eta$"next iteration", "learning rate", "after one step"
ProbabilityAssume Gaussian noise, maximise the likelihood.$\text{NLL}=\text{const}+\frac{1}{2\sigma^2}\text{SSE}$a noise variance $\sigma^2$"noise", "likelihood", "log-likelihood", "MLE"

The four roads agree, so an exam question about one road can often be answered by switching to a different road. If calculus is long, try geometry. If the geometry is unclear, try one number example.

The shape table: which space does each object live in?

The most common silly error in this topic is mixing up the two spaces. Use $d$ for the number of features and $n$ for the number of data points. Remember the order: $X$ is $(d,n)$, alphabetical. Each column of $X$ is one data point.

ObjectShapeLives inMeaningExample (d = 2, n = 3)
$X$$(d,n)$matrixcolumns are data points, rows are features$\begin{bmatrix}1&1&1\\1&2&3\end{bmatrix}$
$x_i$$d$ entries$\mathbb R^d$the $i$-th data point (a column of $X$)$x_2=(1,2)$
$f_j$$n$ entries$\mathbb R^n$the $j$-th feature across all points (a row of $X$)$f_2=(1,2,3)$
$w$$d$ entries$\mathbb R^d$the weights, one per feature$w=(\tfrac13,\tfrac32)$
$y$$n$ entries$\mathbb R^n$the labels, one per point$y=(2,3,5)$
$X^Tw$$n$ entries$\mathbb R^n$all predictions at once$(1.83,3.33,4.83)$
$r=X^Tw-y$$n$ entries$\mathbb R^n$all residuals (prediction minus truth)$(-0.17,0.33,-0.17)$
$XX^T$$(d,d)$matrixsums of products of features$\begin{bmatrix}3&6\\6&14\end{bmatrix}$
$Xy$$d$ entries$\mathbb R^d$sums of feature times label$(10,23)$
$X(X^Tw-y)$$d$ entries$\mathbb R^d$half the gradientzero at the optimum
Memory trick: shapes

Say it as "$X$ is $(d,n)$: Dimensions, then Number." If you ever see a product that does not fit, check the inner numbers: $(d,n)\cdot(n)$ works (that is $Xy$ and $Xr$), $(n,d)\cdot(d)$ works (that is $X^Tw$), $(d,n)\cdot(d)$ does not.

How to read the rest of this page

  1. Read the intuition and the picture of each section first.
  2. Predict the next line of every worked example before you reveal it.
  3. Do the short recall questions at the bottom of each section with the answer hidden.
  4. Attempt each PYQ before opening its solution.
  5. The last section is a one-page revision with a flowchart.

Recall: the big picture

Name the four roads to $w^*$.

Calculus (normal equations), geometry (projection), gradient descent, and probability (maximum likelihood with Gaussian noise).

Is $X$ of shape $(d,n)$ or $(n,d)$ in this course?

$(d,n)$: features are rows, data points are columns. So $X^Tw$ gives the $n$ predictions.

Which of $y$, $w$, $f_j$, $x_i$ live in $\mathbb R^n$?

$y$ and every feature vector $f_j$ (the rows of $X$). The weight vector $w$ and every data point $x_i$ live in $\mathbb R^d$.

3. Start here: vectors, matrices and slopes, from zero

Linear regression needs only five small tools. Read them once, slowly.

Tool 1. A vector is a list of numbers

Definition: vector and dot product

A vector such as $x=\begin{bmatrix}2\\3\end{bmatrix}$ is just a list of numbers. The dot product of $w=\begin{bmatrix}w_1\\w_2\end{bmatrix}$ and $x$ is $w^Tx=w_1x_1+w_2x_2$: multiply matching entries and add. The result is one number.

Example: $w=(2,-1)$, $x=(3,4)$: $w^Tx=2\cdot3+(-1)\cdot4=2$. If $w^Tx=0$ the two vectors are perpendicular (orthogonal). This one idea is the whole geometry section.

Tool 2. The data matrix $X$ has one column per data point

In this course $X$ has shape $(d,n)$: $d$ rows (features) and $n$ columns (data points). So $x_i$ is the $i$-th column. Then $X^Tw$ is an $n$-vector whose $i$-th entry is $w^Tx_i$: all the predictions at once. $XX^T$ is $d\times d$ and $Xy$ is a $d$-vector.

Trap: rows versus columns

Many other books put data points in rows. Here it is the opposite. Whenever you see $X^Tw$, read it as "the predictions for all points".

Tool 3. Residual and squared error

The residual of point $i$ is $r_i=w^Tx_i-y_i$ (prediction minus truth). The sum of squared errors is $\sum r_i^2=\|X^Tw-y\|^2$. Squaring makes every error positive and punishes big mistakes more.

Tool 4. Slope of a curve tells you the direction of increase

Everyday analogy

You stand on a hill in fog. The slope under your feet tells you which way is uphill. To get down, step the opposite way. The slope of a loss with respect to a weight is the derivative; with many weights the list of slopes is the gradient. Gradient descent is "step opposite to the slope, repeat".

Example: $L(w)=(w-3)^2$ has slope $2(w-3)$. At $w=5$ the slope is $4$ (positive: loss rises to the right), so we move left. At $w=3$ the slope is $0$: the bottom.

Tool 5. Derivative rules used here

Function of $w$Derivative
$aw$$a$
$(aw-b)^2$$2a(aw-b)$
$\sum_i(w x_i-y_i)^2$$2\sum_ix_i(wx_i-y_i)$
$\log w$$1/w$

That is all the calculus in the topic.

[ADDED] Tool 6. The gradient of a function of several weights

With one weight, the slope is one number. With $d$ weights, the gradient is a list of $d$ slopes, one per weight: $\nabla L=(\partial L/\partial w_1,\dots,\partial L/\partial w_d)$. The symbol $\partial L/\partial w_1$ means "slope of $L$ when only $w_1$ moves and the others stay fixed".

Worked mini-example: the gradient of one squared error

One data point $x=(1,2)$, label $y=3$, weights $w=(2,1)$. Loss $L(w)=(w_1+2w_2-3)^2$.

Prediction $w^Tx=2\cdot1+1\cdot2=4$. Residual $r=4-3=1$.
$\partial L/\partial w_1=2(w_1+2w_2-3)\cdot1=2r\cdot1=2$ (the inner slope is the coefficient of $w_1$, which is $1$).
$\partial L/\partial w_2=2(w_1+2w_2-3)\cdot2=2r\cdot2=4$ (the coefficient of $w_2$ is $2$).
So $\nabla L=2r\,(1,2)=2r\,x=(2,4)$.
Answer: gradient $=2\times\text{residual}\times\text{feature vector}$
With many points, add one such term per point. That sum is exactly $2X(X^Tw-y)$. You can see where it comes from now.

[ADDED] I checked this numerically by nudging $w_1$ and $w_2$ by $10^{-6}$ and measuring the change of $L$.

[ADDED] Tool 7. Reading the sums you will meet

Take the running example used all through this page: $x=(1,2,3)$ and $y=(2,3,5)$ (three points, one feature).

SymbolMeaning in wordsValue
$\sum x_i$add all the $x$ values6
$\sum x_i^2$square each $x$ first, then add14
$\sum x_iy_i$multiply each pair first, then add23
$\sum y_i$add all the $y$ values10
$\bar x,\ \bar y$the averages$\bar x=2,\ \bar y=3.3333$
Trap: square the sum is not the sum of squares

$(\sum x_i)^2=36$ but $\sum x_i^2=14$. They are different. Every formula in this topic uses $\sum x_i^2$.

Recall: prerequisites

What is the gradient of $(w^Tx-y)^2$ with respect to $w$?

$2(w^Tx-y)\,x$: twice the residual times the feature vector.

For $x=(1,2,3)$, $y=(2,3,5)$, what are $\sum x_i^2$ and $\sum x_iy_i$?

$14$ and $23$.

Why do we step opposite to the gradient?

The gradient points uphill (direction of fastest increase). We want the loss to fall, so we go the other way.

Tips and tricks
  • Write the shape beside every vector and matrix; a product is valid only if the inner sizes match.
  • Check whether the question stores data points as rows or as columns.
Memory line

Match the inner sizes before multiplying.

Checking shapes
write each sizematch the inner sizesthe outer sizes give the resultthen calculate

4. The model, the loss and how to read a fitted line

Intuition

You have points $(x_i,y_i)$, for example house size and price. You want a rule $\hat y=w^Tx$ that predicts price from size. Many lines are possible; we want the one whose predictions are, overall, closest to the real values.

Everyday analogy

Imagine a straight rope pinned near a cloud of pins. You slide and tilt it until the total "pull" of all pins on it is smallest. Squared errors are that pull: a pin twice as far pulls four times as hard.

Definitions

Definition: linear model

$\hat y=w^Tx=w_1x_1+\dots+w_dx_d$, where $x\in\mathbb R^d$ is the feature vector and $w\in\mathbb R^d$ is the vector of weights we learn.

Definition: intercept (dummy feature)

A line $y=w_0+w_1x$ needs a constant term. We handle it by adding a feature that is always $1$: $x=(1,x_1)$ so $w^Tx=w_0\cdot1+w_1x_1$. This is the "dummy feature" of the exam questions. Without it the line is forced through the origin.

Formula: squared loss

$$L(w)=\sum_{i=1}^{n}(w^Tx_i-y_i)^2=\|X^Tw-y\|^2$$ Here $n$ is the number of data points, $x_i$ the $i$-th data point, $y_i$ its label, and $\|\cdot\|$ the usual length of a vector. The optimal weight is $w^*=\arg\min_wL(w)$: the $w$ that makes $L$ smallest.

Why squared?

Squares are smooth (easy derivative), always non-negative, and arise naturally from Gaussian noise (the MLE section). Absolute values and cubes behave differently: the cube is not even bounded below, so it has no minimum (see the model section).

Reading a fitted line from a picture (exam skill)

For $y=\beta_0+\beta_1x$: $\beta_1$ is the slope (rise over run between two points on the line) and $\beta_0$ is the value at $x=0$ (extrapolate back). $\hat\sigma$ is the typical vertical distance of points from the line, read from the scatter, not the range of the axis.

Worked example: Reading slope and intercept

Problem. A fitted line passes through $(20,48)$ and $(60,30)$.

What is asked. The slope $\beta_1$ and intercept $\beta_0$.

Idea / formula used. $\beta_1=\dfrac{y_2-y_1}{x_2-x_1}$, then $\beta_0=y_1-\beta_1x_1$.

Rise $30-48=-18$, run $60-20=40$.
$\beta_1=-0.45$.
$\beta_0=48-(-0.45)(20)=57$.
Answer: $\beta_1=-0.45$, $\beta_0=57$
Common mistake: reading the intercept as the first point's $y$ value.
Trap: sigma is a spread, not a scale

Points lie within a few units of the line, so $\hat\sigma$ is a small number like $3.6$, not $360$. A standard deviation larger than the whole $y$-range would make no sense.

Common mistakes

[ADDED] Reading the picture: three points, two fitted lines

012340123456xyr = -0.167r = +0.333r = -0.167with intercept: ŷ = 0.333 + 1.5xno intercept: ŷ = 1.6429x
Running example $x=(1,2,3)$, $y=(2,3,5)$. Green dots are the data. The solid line has an intercept; the dashed line is forced through the origin. The red vertical segments are the residuals of the solid line. The loss is the sum of their squares.

How to read it. Each vertical segment is one residual $r_i=\hat y_i-y_i$. The solid line has residuals $-0.167,\ +0.333,\ -0.167$, which add to $0$ (the line is pulled up by one point exactly as much as it is pulled down by the others). The dashed line has no intercept, so it must pass through the origin and it cannot balance the residuals: they add to $-0.143$.

[ADDED] Linear means linear in the weights, not in $x$

"Linear regression" requires the prediction to be a straight combination of the weights. The features themselves can be anything you compute from $x$: $1$, $x$, $x^2$, $\log x$. The model $\hat y=w_0+w_1x+w_2x^2$ is still linear regression, because $w_0,w_1,w_2$ appear only to the first power. You simply build a bigger $X$:

point 1point 2point 3
feature $1$111
feature $x$123
feature $x^2$149

Now $d=3$ and every formula of this topic applies unchanged, with $XX^T$ being $3\times3$. With three points and these three independent features the quadratic passes through all three points, so the training error is $0$ [ADDED] (checked: the residual vector has length $0$).

Recognition cue

If a question says "polynomial regression", "add the feature $x^2$" or "kernel regression", the algebra is still linear regression on a larger feature list.

[ADDED] Comparison: sum, half-sum, mean (the loss versions you will meet)

Same data as above, at $w=0$, so that the numbers can be checked: $\sum x_i^2=14$, $\sum x_iy_i=23$, $n=3$.

Loss nameFormulaGradientGradient at $w=0$ (example)Same minimiser?
SSE (plain sum)$\sum(wx_i-y_i)^2$$2\sum x_i(wx_i-y_i)$-46yes
half SSE$\tfrac12\sum(wx_i-y_i)^2$$\sum x_i(wx_i-y_i)$-23yes
MSE$\tfrac1n\sum(wx_i-y_i)^2$$\tfrac2n\sum x_i(wx_i-y_i)$-15.333yes
half MSE$\tfrac1{2n}\sum(wx_i-y_i)^2$$\tfrac1n\sum x_i(wx_i-y_i)$-7.667yes

All four differ only by a positive constant, so they share the same bottom of the bowl. They do not share the same gradient, so a gradient-descent step with the same $\eta$ has a different size. This is the content of the PYQ where $P$ minimises one loss and $Q$ minimises its mean.

[ADDED] Why squares? A look at how a loss prices an error

Size of one error12310
absolute error12310
squared error149100

One error of size $10$ costs as much as $100$ errors of size $1$. So least squares works hard to avoid a single large miss, which also means one wild outlier can drag the whole line. That is the price of the smooth bowl and of the Gaussian link in the last section.

[ADDED] Sign convention: always check it

ConventionResidualGradient written asGradient step
this course$r_i=w^Tx_i-y_i$ (prediction minus truth)$2X(X^Tw-y)$$w-\eta\cdot2X(X^Tw-y)$
other books$e_i=y_i-w^Tx_i$ (truth minus prediction)$-2Xe$$w+\eta\cdot2Xe$

Squaring hides the sign inside the loss, but the sign of the gradient matters in every step calculation. If you flip the residual, you must flip the step.

Memory trick: sign of the residual

"Predicted minus True": P comes before T. Positive residual means the line is too high there. The gradient then tells the weight to come down.

Recall: model and loss

Is $\hat y=w_0+w_1x+w_2x^2$ linear regression?

Yes. It is linear in the weights. The features are $1,\ x,\ x^2$.

Do SSE and MSE have the same optimal $w$?

Yes (they differ by the positive constant $n$). Their gradients, and hence gradient-descent steps, differ by that factor.

The residual is positive at a point. Is the line above or below that point?

Above: residual $=$ prediction $-$ truth $>0$.

5. The optimal weight: normal equations, intercept and scaling

Picture it

Dropping a perpendicular onto a floor: the closest point leaves an error at right angles to the floor.

Intuition

The loss is a smooth bowl in the weights. The lowest point of a bowl is where the slope is zero in every direction. Setting all slopes to zero gives a set of linear equations, the normal equations.

Derivation (every step)

  1. Loss $L(w)=\sum_i(w^Tx_i-y_i)^2$.
  2. Its gradient is $\nabla L(w)=2\sum_ix_i(w^Tx_i-y_i)=2X(X^Tw-y)$. (Each data point contributes its feature vector times its residual.)
  3. At the minimum the gradient is $0$: $X(X^Tw-y)=0$, i.e. $XX^Tw=Xy$.
  4. If $XX^T$ can be inverted, $w^*=(XX^T)^{-1}Xy$.
Formula: optimal weight

$$w^*=(XX^T)^{-1}Xy,\qquad\text{one feature: } w^*=\frac{\sum_ix_iy_i}{\sum_ix_i^2}$$ $XX^T$ is the $d\times d$ matrix of feature products; $Xy$ is the $d$-vector of feature-times-label sums. For one feature they are just the numbers $\sum x_i^2$ and $\sum x_iy_i$.

What the normal equation says in words

$X(X^Tw^*-y)=0$ means: the residual vector is orthogonal to every feature. Every row of $X$ (a feature) has zero dot product with the residuals. This single fact answers several exam questions (for example "what is the sum of the elements of $X(X^Tw-y)$?": zero at the optimum).

Intercept and residuals

If one feature is the dummy $1$, its row of $X$ is all ones, so the normal equation for that row says $\sum_ir_i=0$: the residuals add to zero. So it is impossible that every prediction is above (or below) its label, whenever an intercept is present.

Scaling facts

ChangeEffect on $w^*$Why
multiply all $y$ by $c$multiplies $w^*$ by $c$$w^*=(XX^T)^{-1}X(cy)=c\,w^*$
multiply all $x$ by $c$divides $w^*$ by $c$$(c^2XX^T)^{-1}(cXy)=\tfrac1c w^*$
duplicate all pointsno changeboth $XX^T$ and $Xy$ double
add points on the fitted lineno changethey add zero residual, so the gradient is unchanged
Worked example: Simple: one feature

Problem. $x=(1,2,3)$, $y=(2,4,6)$. Find $w^*$.

What is asked. The best slope through the origin.

Idea / formula used. $w^*=\sum x_iy_i/\sum x_i^2$.

$\sum x_iy_i=2+8+18=28$.
$\sum x_i^2=1+4+9=14$.
$w^*=28/14=2$. The points lie exactly on $y=2x$, as expected.
Answer: $w^*=2$
Common mistake: dividing by $n$ or by $\sum x_i$ instead of $\sum x_i^2$.
Worked example: Exam level: noisy data

Problem. $x=(1,2,3)$, $y=(2,3,5)$, no intercept. Find $w^*$ and the residuals.

What is asked. Slope and whether residuals sum to zero.

Idea / formula used. Same formula; then compute $r_i=w^*x_i-y_i$.

$\sum xy=2+6+15=23$, $\sum x^2=14$.
$w^*=23/14=1.6429$.
Predictions: $1.6429,\ 3.2857,\ 4.9286$. Residuals: $-0.3571,\ 0.2857,\ -0.0714$.
Their sum is $-0.1429$, not zero (no intercept), but $\sum x_ir_i=0.000000$ is zero, the normal equation.
Answer: $w^*=1.6429$
Common mistake: expecting residuals to sum to zero without a dummy feature. Only $\sum x_ir_i=0$ is guaranteed.
Worked example: Tricky: with an intercept

Problem. Points $(1,2),(2,2),(3,5)$. Fit $y=w_0+w_1x$.

What is asked. $w_0,w_1$ and check $\sum r_i=0$.

Idea / formula used. Slope $=\sum(x-\bar x)(y-\bar y)/\sum(x-\bar x)^2$; intercept $=\bar y-w_1\bar x$.

$\bar x=2$, $\bar y=3$.
$\sum(x-\bar x)(y-\bar y)=(-1)(-1)+0\cdot(-1)+(1)(2)=3$; $\sum(x-\bar x)^2=2$.
$w_1=1.5$, $w_0=3-1.5\cdot2=0.0$.
Predictions $1.5,3,4.5$; residuals (prediction minus label) $1.5-2=-0.5$, $3-2=1$, $4.5-5=-0.5$, which add to $0$ ✓.
Answer: $w_0=0,\ w_1=1.5$
Common mistake: forgetting that centring ($x-\bar x$) is what the intercept does for you.
Trap: numbers that look like an answer

A tempting shortcut in the one-feature formula is to divide $\sum xy$ by "about $n$". Always compute $\sum x^2$. If the printed key and your correct computation differ, check $\sum x^2$ first (see the Aug 2024 flag in the PYQs).

[ADDED] Derivation 1: one feature, no intercept, every line

Loss: $L(w)=\sum_i(wx_i-y_i)^2$. Expand the bracket: $(wx_i-y_i)^2=w^2x_i^2-2wx_iy_i+y_i^2$. Add over all points:

$$L(w)=w^2\underbrace{\sum x_i^2}_{A}-2w\underbrace{\sum x_iy_i}_{B}+\underbrace{\sum y_i^2}_{C}$$

This is a parabola $Aw^2-2Bw+C$ with $A>0$, so it opens upward and has one lowest point. Its slope is $2Aw-2B$. Setting the slope to zero gives $w=B/A$, that is $w^*=\sum x_iy_i/\sum x_i^2$. The second derivative $2A=2\sum x_i^2>0$ confirms that it is a minimum.

The smallest loss is $L(w^*)=C-B^2/A$. For the running example, $A=14$, $B=23$, $C=38$, so $L(w)=14w^2-46w+38$ and $L_{\min}=38-23^2/14=0.2143=3/14$. [ADDED] (The code checks that the SSE of the fitted line equals this number.)

[ADDED] The loss is a bowl: what the slope tells you

0123010203040wL(w)green dot = minimum: w* = 23/14 ≈ 1.643, where the slope is 0slope −32: uphill is left, so step RIGHTslope +38: uphill is right, so step LEFTstart: w = 0open dots: gradient descent from w = 0 with η = 0.02, first 4 steps
The loss of the running example as a function of $w$. Left of the minimum the slope is negative (the loss falls as $w$ grows), right of it the slope is positive. Gradient descent (dots) follows the slope downhill; the normal equation jumps straight to the bottom.

[ADDED] Derivation 2: with an intercept, where the centred formulas come from

With the dummy feature, $X$ has two rows: all ones, and $x$. The normal equations $XX^Tw=Xy$ become two equations, one per row. Write $n$ for the number of points:

$$nw_0+\Big(\sum x_i\Big)w_1=\sum y_i\qquad\text{and}\qquad\Big(\sum x_i\Big)w_0+\Big(\sum x_i^2\Big)w_1=\sum x_iy_i$$

The first equation says $w_0=\bar y-w_1\bar x$: the fitted line passes through the point of averages $(\bar x,\bar y)$. Put this into the second equation and the algebra turns into $w_1=\sum(x_i-\bar x)(y_i-\bar y)\big/\sum(x_i-\bar x)^2$. In words: slope = how $x$ and $y$ move together, divided by how much $x$ moves on its own.

Worked example: With an intercept (same data)

Problem. $x=(1,2,3)$, $y=(2,3,5)$. Fit $\hat y=w_0+w_1x$.

What is asked. The intercept $w_0$, the slope $w_1$ and the residuals.

Idea / formula used. The two normal equations from the dummy feature, solved by elimination.

$n=3$, $\sum x=6$, $\sum x^2=14$, $\sum y=10$, $\sum xy=23$.
Equation 1: $3w_0+6w_1=10$. Equation 2: $6w_0+14w_1=23$.
Double equation 1: $6w_0+12w_1=20$. Subtract it from equation 2: $2w_1=3$, so $w_1=1.5$.
Back in equation 1: $3w_0=10-9=1$, so $w_0=1/3$.
Check the average point: $w_0+w_1\bar x=\tfrac13+1.5\times2=3.333=\bar y$. ✓
Predictions: $1.833,\ 3.333,\ 4.833$. Residuals (prediction minus truth): $-0.167,\ +0.333,\ -0.167$. Sum $=0$ ✓.
Answer: $w_0=\tfrac13,\ w_1=\tfrac32$
Common mistake: using the no-intercept answer $23/14$ as the slope here. The slope changes when the intercept is allowed, because the line is free to move up or down.

[ADDED] Which sums are zero at the optimum? (computed on the two fits above)

QuantityNo intercept (dashed fit)With intercept (solid fit)Why
$\sum_i r_ix_i$ (residual dotted with the feature)0.00000.0000normal equations: always zero
$\sum_i r_i$ (residuals added)-0.1429 (not zero)0.0000zero only if a dummy feature of ones is present
$\sum_i r_i\hat y_i$ (residual dotted with prediction)0.00000prediction is a combination of the features
$\sum_i r_i^2$ (the loss)0.21430.1667zero only for a perfect fit; adding the intercept lowered it

[ADDED] What if $XX^T$ cannot be inverted?

The formula $w^*=(XX^T)^{-1}Xy$ needs the inverse. It does not exist when the features are not independent, for example when one feature is a multiple of another, or when there are fewer data points than features ($n<d$).

Worked example: A singular $XX^T$

Problem. Two features: $f_1=(1,2,3)$ and $f_2=2f_1=(2,4,6)$, labels $y=(2,3,5)$.

What is asked. Is $w^*$ unique?

Idea / formula used. Compute $XX^T$ and its determinant.

$XX^T=\begin{bmatrix}14&28\\28&56\end{bmatrix}$ and $Xy=\begin{bmatrix}23\\46\end{bmatrix}$.
Determinant $=14\cdot56-28\cdot28=784-784=0$: no inverse.
The two normal equations are $14a+28b=23$ and $28a+56b=46$. The second is just twice the first, so there is only one real equation for two unknowns.
Infinitely many weights satisfy it. For example $(a,b)=(\tfrac{23}{14},0)$ and $(a,b)=(0,\tfrac{23}{28})$. Both give the same predictions $\tfrac{23}{14}(1,2,3)$ and the same loss $3/14$.
Answer: not unique: infinitely many $w$, but the predictions and the loss are unique
Common mistake: writing $(XX^T)^{-1}$ without checking that the features are independent. Geometry still works: the projection is unique even when the weights are not.

[ADDED] What happens to $w^*$ when the data are changed? (every row verified by code)

Change to the dataNo interceptWith intercept (slope, intercept)Check on the running example
multiply all $y$ by $c$$w^*\to c\,w^*$slope $\to c\cdot$slope, intercept $\to c\cdot$interceptall ×3: 4.9286; slope 4.50
multiply all $x$ by $c$$w^*\to w^*/c$slope $\to$ slope$/c$, intercept unchanged$x\to2x$: 0.8214; slope 0.75
add $c$ to all $y$$w^*$ changes (the line must still go through $0$)slope unchanged, intercept $+c$y+5: intercept 5.333
add $c$ to all $x$$w^*$ changesslope unchanged, intercept $-c\cdot$slope$x+1$: intercept -1.167; no-intercept weight 1.1379 (was 1.6429)
duplicate every pointno changeno changeboth sums double, the ratio stays
add a point exactly on the fitted lineno changeno changeits residual is zero, so the gradient is unchanged
Memory trick: scaling

"$y$ goes WITH, $x$ goes AGAINST." Scale the labels by $c$ and the weight scales with them. Scale the inputs by $c$ and the weight must shrink by $c$ to give the same predictions. (Same prediction: $w\cdot x$ stays fixed when $x\to cx$ and $w\to w/c$.)

Memory trick: "normal"

"Normal equations" means "perpendicular equations": in geometry a normal is a right-angle line. The equations say the residual is at a right angle to every feature. When you read "normal equations", think "residual $\perp$ features".

Recall: the optimal weight

Write $w^*$ for one feature, no intercept.

$w^*=\sum x_iy_i/\sum x_i^2$.

At the optimum what is $X(X^Tw^*-y)$?

The zero vector. Its sum of entries is $0$ too (PYQ lr10).

With an intercept, why can all residuals not be positive?

The row of ones in $X$ gives $\sum r_i=0$. A sum of positive numbers cannot be zero.

Does the line with an intercept always pass through $(\bar x,\bar y)$?

Yes: $w_0=\bar y-w_1\bar x$ from the first normal equation.

$x\to x+1$ with an intercept: what happens to the slope?

Nothing: a shift of $x$ does not change the slope; only the intercept moves.

Interactive explorer

Move the slope and intercept and watch the residuals (red) and the sum of squared errors. Then jump to the least-squares line: no other line has a smaller SSE.

6. Geometry: projection, orthogonality and spans

Intuition

The label vector $y\in\mathbb R^n$ is one point in $n$-dimensional space. The predictions $X^Tw$ can only be points of a smaller flat set: all combinations of the feature vectors (the rows of $X$, each an $n$-vector). The best prediction is the point of that flat set closest to $y$. That closest point is the projection of $y$.

Everyday analogy

The floor is the set of reachable predictions; $y$ is a bird in the air. The closest floor point is straight below the bird. The line from the floor to the bird is perpendicular to the floor: that line is the residual.

Definitions

Definition: span of the features (column space of $X^T$)

All vectors of the form $a_1f_1+\dots+a_df_d$, where $f_j\in\mathbb R^n$ is the $j$-th feature vector (row $j$ of $X$). Every prediction vector $X^Tw$ is such a combination with $a=w$.

Definition: span of the data points

All combinations of the columns $x_1,\dots,x_n\in\mathbb R^d$. It lives in $\mathbb R^d$, the same space as $w$.

Formula: projection facts

(1) $X^Tw^*$ is the projection of $y$ onto the span of the features (in $\mathbb R^n$).
(2) The residual $y-X^Tw^*$ is orthogonal to every feature: $X(y-X^Tw^*)=0$.
(3) $w^*$ itself lies in $\mathbb R^d$ and can be written $w^*=X\alpha$, a combination of the data points.
(4) Pythagoras: $\|y\|^2=\|X^Tw^*\|^2+\|y-X^Tw^*\|^2$.

Why (2) and (3) hold

(2) is the normal equation. For (3): the update $w\leftarrow w-\eta X(X^Tw-y)$ always adds a combination of data points, starting from $w=0$, so the weights stay in the span of the data points. The same is true of the exact solution. This is the key step that leads to kernels.

Zero training error

Training error is zero exactly when $y$ itself is in the span of the features. For features $f_1=(1,0,1)$ and $f_2=(0,1,1)$ the span is $\{(a,b,a+b)\}$: the third entry must equal the sum of the first two.

The two extreme cases

SituationThenSquared error
$y$ is in the span of the features$X^Tw^*=y$$0$
$y\ne0$ is orthogonal to every feature$X^Tw^*=0$ (projection of $y$ is the zero vector)$\|y\|^2$
$w^*$ is orthogonal to the data points (so $X^Tw^*=0$)all predictions are $0$$\|y\|^2$
Worked example: Exam level: which label vector fits exactly?

Problem. Features $f_1=(1,0,1)$, $f_2=(0,1,1)$. Which of $y=(1,2,3)$, $(1,2,4)$, $(2,1,4)$, $(0,0,1)$ gives zero error?

What is asked. The $y$ lying in the span.

Idea / formula used. $y=af_1+bf_2=(a,b,a+b)$.

Third entry must equal first plus second.
$(1,2,3)$: $1+2=3$ ✓. $(1,2,4)$: $3\ne4$. $(2,1,4)$: $3\ne4$. $(0,0,1)$: $0\ne1$.
Answer: $y=(1,2,3)$ with $w=(1,2)$
Common mistake: testing only that $y$ has the same length as the features; it must be in their span.
Worked example: Tricky: orthogonal label

Problem. $X$ has rows $f_1=(1,1,0)$ and $f_2=(0,0,1)$. Take $y=(1,-1,0)$. Find $w^*$ and the error.

What is asked. Projection and error.

Idea / formula used. Check $f_j^Ty$.

$f_1^Ty=1-1=0$, $f_2^Ty=0$: $y$ is orthogonal to both features.
So the projection is $0$, $X^Tw^*=0$, $w^*=0$.
Error $=\|y\|^2=1+1+0=2$.
Answer: $w^*=0$, error $2$
Common mistake: saying the error is $0$ because $w^*$ is "perfect". Predicting $0$ everywhere is as bad as it gets.

Common mistakes

[ADDED] The picture, with every part labelled

plane = span of the featuresoriginy (the labels)p = XTw* (closest point)r = y − XTw*residual, at 90° to the planeanother prediction qq is farther:‖y−q‖² = ‖y−p‖² + ‖p−q‖²
The label vector $y$ floats above the plane of reachable predictions. The closest point of the plane is the projection $p=X^Tw^*$. The residual $r=X^Tw^*-y$ meets the plane at a right angle. Any other prediction $q$ is farther away.

Read it in four steps. (1) The plane is "everything the model can predict": all vectors $X^Tw$. (2) $y$ is usually not on that plane, so zero error is usually impossible. (3) The best you can do is the nearest point $p$. (4) The line from $p$ to $y$ is the residual, and it is perpendicular to the plane, which is exactly the normal equation $X(y-X^Tw^*)=0$.

Everyday analogy

Think of the sun straight overhead. The projection $p$ is the shadow of $y$ on the floor. The residual is the height of $y$ above the floor.

Where the analogy breaks: the real "floor" is a flat sheet inside $n$ dimensions, where $n$ can be $50$ or $5000$; you cannot draw it. The picture only keeps the two facts that stay true in every dimension: the nearest point is the foot of a perpendicular, and Pythagoras holds.

[ADDED] Worked check of the picture with real numbers

Worked example: Project $y=(2,3,5)$ onto the feature $f=(1,2,3)$

Problem. One feature $f=(1,2,3)$, labels $y=(2,3,5)$, no intercept.

What is asked. The projection $p$, the residual $r$, and a check that $r\perp f$ and Pythagoras.

Idea / formula used. $p=w^*f$ with $w^*=\sum f_iy_i/\sum f_i^2$.

$w^*=23/14=1.6429$. So $p=1.6429\times(1,2,3)=(1.6429, 3.2857, 4.9286)$.
Residual (prediction minus truth) $r=p-y=(-0.3571, 0.2857, -0.0714)$.
Perpendicular check: $f\cdot r=-0.3571+2(0.2857)+3(-0.0714)=0$. ✓
Pythagoras: $\|y\|^2=4+9+25=38$; $\|p\|^2=529/14=37.7857$; $\|r\|^2=3/14=0.2143$; and $37.7857+0.2143=38.0000$.
Answer: $p=(1.643, 3.286, 4.929)$, squared error $\|r\|^2=0.2143$
Common mistake: calling $y$ itself the "prediction". The prediction is $p$, the projection, and the error is what is left.

[ADDED] Why the foot of the perpendicular is the closest point

Take any other point $q$ of the plane. Because $p$ and $q$ are both on the plane, the vector $p-q$ lies in the plane, so $r$ is perpendicular to it. Pythagoras then gives $\|y-q\|^2=\|y-p\|^2+\|p-q\|^2$, which is at least $\|y-p\|^2$. Equality needs $q=p$.

Numbers: pick $q=1.5f=(1.5,3,4.5)$, from $w=1.5$. Then $\|y-q\|^2=0.5000$, and $\|y-p\|^2+\|p-q\|^2=0.2143+0.2857=0.5000$. [ADDED] The two sides match.

[ADDED] With an intercept the plane has two directions

Now the features are $f_0=(1,1,1)$ and $f=(1,2,3)$, so the plane is spanned by both. The residual is $r=p-y=(-0.167, 0.333, -0.167)$. It is perpendicular to both: $f_0\cdot r=0$ (that is "the residuals add up to zero") and $f\cdot r=0$.

[ADDED] Comparison: when is the training error zero?

SituationIs the training error $0$?Reason
$y$ lies in the span of the featuresyes$y$ is a prediction vector: $y=X^Tw$ for some $w$
$n\le d$ and the features are independent (e.g. $3$ independent features, $3$ points)yes, for every $y$independent features span all of $\mathbb R^n$; [ADDED] checked on a $3\times3$ example
$y\ne0$ is orthogonal to every feature ($Xy=0$)no: error is $\|y\|^2$projection is $0$, so $w^*=0$ when $XX^T$ is invertible
$w^*$ is orthogonal to every data pointno: error is $\|y\|^2$$X^Tw^*=0$, so all predictions are $0$
one outlier far off the trendnoa few parameters cannot reach every point

[ADDED] Orthogonal example: features $f_1=(1,1,0)$, $f_2=(0,0,1)$, labels $y=(1,-1,0)$. Both $f_1\cdot y$ and $f_2\cdot y$ equal $0$, so $y\perp$ both features. The fit gives $w^*=(0,0)$ and the squared error $=\|y\|^2=2$ (checked).

[ADDED] Two spaces, two spans (the exam loves this)

Span of the features $f_j$Span of the data points $x_i$
lives in$\mathbb R^n$ (same space as $y$)$\mathbb R^d$ (same space as $w$)
containsevery prediction vector $X^Tw$the optimal weight $w^*$, and every gradient-descent iterate started from $0$
one fact$p=X^Tw^*$ is the projection of $y$ onto it$w^*=X\alpha$ (leads to kernels)
Memory trick: which span?

"Predictions live with the labels; weights live with the points." $\hat y$ and $y$ are both in $\mathbb R^n$. $w$ and $x_i$ are both in $\mathbb R^d$.

Recall: geometry

What does "projection" mean in one sentence?

The point of the span nearest to $y$; the residual from it to $y$ is perpendicular to the span.

$Xy=0$. What is $w^*$ and the error?

$w^*=0$ (when $XX^T$ is invertible) and the error is $\|y\|^2$.

Which span contains $w^*$?

The span of the data points (columns of $X$), in $\mathbb R^d$.

Write Pythagoras for the fit.

$\|y\|^2=\|X^Tw^*\|^2+\|y-X^Tw^*\|^2$.

7. Which model can lower the training loss?

Intuition

Training loss only measures how well the model matches the data it was fit on. A model that can do everything a simpler model can, plus more, can never do worse on the training set. Penalising the weights (regularisation) does the opposite: it forbids some solutions, so training loss cannot go down.

Everyday analogy

If a tailor may use all the tools in a big box, the suit fits at least as well as with only a few tools from that box.

Rules

ChangeTraining lossWhy
add a dummy feature (intercept)can decrease, never increasesthe old model is the special case $w_0=0$
move from degree 1 to degree 2 (add $x^2$)can decrease, never increasesquadratics include all lines ($w_2=0$)
add $L_2$ or $L_1$ penaltycannot decrease (usually increases)the penalty forbids the unpenalised optimum
kernel regression with degree-2 kernelcan decreasemore features in $\phi(x)$

Training versus test

A lower training loss does not mean better test performance. A very flexible model can overfit: it has a tiny training error but follows the noise. "Model $Q$ always performs well on test data" is therefore false. Flexibility helps when the true pattern is curved; it hurts when there is little data or many outliers.

Why squared loss and not a cubic

For $\sum(w^Tx_i-y_i)^3$ the term can be made arbitrarily negative (take $w^Tx_i-y_i\to-\infty$), so the minimum does not exist and "the optimal $w_2$" is meaningless. Squared loss is bounded below by $0$ and has a unique bottom, so $w_1$ is well-defined and sensible.

Worked example: Exam level: P versus Q

Problem. Model $P$: $\hat y=w_0+w_1x$; model $Q$: $\hat y=w_0+w_1x+w_2x^2$. Which has lower (or equal) training MSE?

What is asked. The model with the lower training error.

Idea / formula used. Nested models.

Set $w_2=0$ in $Q$: it becomes $P$. So $Q$ can copy any $P$ fit.
Therefore $\text{train MSE}(Q)\le\text{train MSE}(P)$.
Answer: Model $Q$
Common mistake: choosing "depends on the data". The inequality holds for every dataset.
Trap: regularisation and training loss

"Penalising the weights could decrease training loss" is false: with the penalty added, the best penalised solution generally fits the training data worse than the unpenalised one. It may help on the test set.

[ADDED] Seeing the nesting on real data

01234567012345through the origin: training SSE = 2.417with intercept: training SSE = 1.537with x² added: training SSE = 0.017
Six points fitted three ways. The model with more freedom never has a larger training error: $2.417\ge1.537\ge0.017$. The curves pass closer and closer to the dots, but that says nothing about new points.

Each bigger model contains the smaller one as a special case: the line with an intercept becomes the through-origin line by setting $w_0=0$; the quadratic becomes the line by setting $w_2=0$. The optimiser can always choose those special values, so it can never do worse. Equal is possible: if the points already lie on a line through the origin, adding an intercept does not help. [ADDED] Example $(1,2),(2,4),(3,6)$: both fits have error $0$ (checked).

[ADDED] Comparison: what each change does to the training loss

ChangeTraining SSEReasonTest error
add an interceptnever risesold model is the case $w_0=0$may rise or fall
add any extra feature (even a useless one)never risesold model is the case where its weight is $0$a useless feature can hurt
raise the polynomial degreenever riseslower degree is a special casecan overfit
add an $L_1$ or $L_2$ penaltynever falls (usually rises)the penalised optimum is a different pointmay fall
add more data pointsnever falls (sum of squares)[ADDED] every new point adds a non-negative term (checked: SSE rose from 0.214 to 3.300 on one added point)usually improves
use the average (MSE) instead of the sumsame minimiserdiffers by the constant $n$same
Trap: "more data lowers the training loss"

The sum of squared errors cannot fall when you add a point. The mean may move either way. If a question asks about "training SSE", more data is never an improvement.

[ADDED] Zero training error, bad prediction

Worked example: A quadratic through three points

Problem. Points $(1,1),(2,3),(3,2)$. Compare the line and the quadratic.

What is asked. Their training errors, and their predictions at $x=5$.

Idea / formula used. Solve the normal equations for features $(1,x)$ and for $(1,x,x^2)$.

Quadratic through all three points: $\hat y=-4+6.5x-1.5x^2$. Check: $x=1$: $-4+6.5-1.5=1$ ✓; $x=2$: $-4+13-6=3$ ✓; $x=3$: $-4+19.5-13.5=2$ ✓.
Its training error is $0$.
The best line has training error $1.500$ (it cannot pass through all three).
Predict at $x=5$: quadratic gives $-4+32.5-37.5=-9$; the line $\hat y=1+0.5x$ gives $3.5$.
Answer: train error $0$ against $1.500$; predictions at $5$ are $-9$ and $3.50$
Common mistake: "zero training error means the better model". The quadratic bends down after $x=2$ because it was free to chase every point, including noisy ones.
Memory trick: nested

"Bigger never loses on the training set. A penalty never wins on it." Say it before every "which model has lower training error" question, then ask only one thing: is the old model a special case of the new?

Recall: model comparison

Add the feature $x^2$ to a line. Training loss?

Never higher. A line is the quadratic with $w_2=0$.

Add an $L_2$ penalty. Training loss?

Never lower (usually higher).

Add one more training point. Training SSE?

Never lower: one more non-negative term.

"Model Q always performs better on test data." True?

False. "Always" claims about generalisation are false; flexibility can overfit.

8. Gradient descent: updates, learning rate, SSE versus MSE

Picture it

Walking downhill in fog: feel the slope, take a step against it, repeat.

Intuition

Solving $XX^Tw=Xy$ needs an inverse, which is slow when $d$ is huge. Gradient descent instead starts anywhere and walks downhill in small steps. The gradient points uphill, so each step goes the opposite way.

The update rule

Formula: gradient descent for squared loss

$$w^{(t+1)}=w^{(t)}-\eta\,\nabla L\big(w^{(t)}\big),\qquad \nabla L(w)=2X(X^Tw-y)=2(XX^T)w-2Xy$$ $\eta>0$ is the learning rate (step size), $w^{(t)}$ the weight at step $t$. The factor $2$ appears because $L$ is a plain sum of squares; if the loss is $\tfrac12\sum$, the $2$ disappears.

Direction and size

Let $u$ be the unit vector along the gradient. The step $w^{(t+1)}=w^{(t)}+\eta\,v$ goes downhill fastest when $v=-u$, the unit vector opposite to the gradient. Its length is $\eta\|v\|=\eta$ for a unit vector.

Learning rate

$\eta$Behaviour
too smallmoves correctly but very slowly
goodconverges steadily
too largeovershoots; loss can rise and diverge

SSE versus MSE

Loss $L=\tfrac12\sum(\cdot)^2$ and $L'=\tfrac1{2n}\sum(\cdot)^2$ have the same minimiser (they differ by the positive constant $n$). But $\nabla L'=\tfrac1n\nabla L$, so with the same $\eta$ the second takes steps that are $n$ times smaller. To follow the same path, $Q$ needs learning rate $n\eta$.

Worked example: Simple: two steps

Problem. $x=(1,2)$, $y=(2,4)$, loss $\sum(wx_i-y_i)^2$, $w^{(0)}=0$, $\eta=0.05$. Do two steps.

What is asked. $w^{(1)},w^{(2)}$.

Idea / formula used. $\nabla L=2\sum x_i(wx_i-y_i)$.

At $w=0$: $\nabla L=2[1(0-2)+2(0-4)]=2(-2-8)=-20$.
$w^{(1)}=0-0.05(-20)=1.00$.
At $w=1$: $\nabla L=2[1(1-2)+2(2-4)]=2(-1-4)=-10$.
$w^{(2)}=1-0.05(-10)=1.50$. It is moving toward $w^*=2$.
Answer: $w^{(1)}=1,\ w^{(2)}=1.5$
Common mistake: forgetting the factor $2$ when the loss has no $\tfrac12$.
Worked example: Exam level: one update, then predict

Problem. $w=1$, data $(1,3),(2,5),(3,8)$, $\eta=0.05$, $\nabla f=2XX^Tw-2Xy$.

What is asked. The next weight and the prediction at $x=4$.

Idea / formula used. With one feature, $XX^T$ and $Xy$ are single numbers.

$XX^T=1+4+9=14$, $Xy=3+10+24=37$.
Gradient $=2(14)(1)-2(37)=-46$.
$w^{(1)}=1-0.05(-46)=3.3$.
Prediction $=3.3\times4=13.2$.
Answer: $w^{(1)}=3.3$, prediction $13.2$
Common mistake: adding $\eta\nabla f$ instead of subtracting it.
Worked example: Tricky: step along a unit direction

Problem. $w^{(t)}=(1.0,0.5)$, unit gradient direction $u=(0.8,0.6)$, step $\eta=0.5$ taken downhill.

What is asked. $w^{(t+1)}$ and its norm.

Idea / formula used. Downhill is $-u$.

Step $=0.5\cdot(-0.8,-0.6)=(-0.4,-0.3)$.
$w^{(t+1)}=(0.6,0.2)$.
Norm $=\sqrt{0.36+0.04}=\sqrt{0.4}$.
Answer: $(0.6,0.2)$, norm $\approx0.632$
Common mistake: moving along $+u$, which goes uphill.

Common mistakes

[ADDED] A 1-D picture of "how big a step is too big"

η = 0.002 too smallerror × (0.94) each stepstep tη = 1/28 ≈ 0.036 perfecterror × (0.00) each stepstep tη = 0.05 zigzags, still convergeserror × (-0.40) each stepstep tη = 0.08 too large: divergeserror × (-1.24) each stepstep t
Gradient descent on the running example (starting at $w=0$) for four learning rates. The dashed green line is the optimum $23/14$. The error shrinks by the same factor at every step. When that factor is between $-1$ and $1$ it converges; at $-1$ it bounces forever; below $-1$ it blows up.

[ADDED] Derivation: the error is multiplied by a fixed number each step

For the running example $\nabla L=2(14w-23)=28w-46$ and $w^*=23/14$. Write $e_t=w^{(t)}-w^*$ for the distance from the optimum. Then

$$w^{(t+1)}-w^*=w^{(t)}-\eta(28w^{(t)}-46)-w^*=(1-28\eta)\,(w^{(t)}-w^*)$$

because $28w-46=28(w-w^*)$. In general, for one feature, the factor is $1-2\eta\sum x_i^2$. So $e_t=(1-2\eta\sum x_i^2)^t\,e_0$: converges if and only if $0<\eta<1/\sum x_i^2$ (here $1/14\approx0.0714$).

$\eta$factor $1-28\eta$behaviourdistance to optimum after 60 steps
$0.002$0.944converges, slowly0.052
$1/28\approx0.0357$0.000converges in one step (exact)$<10^{-9}$
$0.05$-0.400zigzags, converges$<10^{-9}$
$1/14\approx0.0714$-1.000bounces between two values forever1.643
$0.08$-1.240diverges662065.428

[ADDED] All five rows were produced by running the update in code, not typed.

[ADDED] Beyond the PYQs, for understanding only. With many features the same idea holds in every direction: if $\lambda_{\max}$ is the largest eigenvalue of $XX^T$, the iteration converges when $0<\eta<1/\lambda_{\max}$ (for the plain sum loss). If the loss has a $\tfrac12$ the threshold doubles; if it is the mean it is multiplied by $n$.

[ADDED] Worked example with two weights (intercept and slope)

Worked example: Two steps in two dimensions, and why it zigzags

Problem. $X=\begin{bmatrix}1&1&1\\1&2&3\end{bmatrix}$, $y=(2,3,5)$, loss $\sum(\cdot)^2$, $w^{(0)}=(0,0)$, $\eta=0.05$. The exact optimum is $w^*=(\tfrac13,\tfrac32)$.

What is asked. The first iterates and the pattern they follow.

Idea / formula used. $\nabla L=2XX^Tw-2Xy$ with $XX^T=\begin{bmatrix}3&6\\6&14\end{bmatrix}$ and $Xy=\begin{bmatrix}10\\23\end{bmatrix}$.

At $w=(0,0)$: $\nabla L=-2Xy=(-20,-46)$. Step: $w^{(1)}=(0,0)-0.05(-20,-46)=(1,\ 2.3)$.
At $w^{(1)}$: $XX^Tw=(3+13.8,\ 6+32.2)=(16.8,\ 38.2)$, so $\nabla L=2(16.8-10,\ 38.2-23)=(13.6,\ 30.4)$. Step: $w^{(2)}=(1-0.68,\ 2.3-1.52)=(0.320,\ 0.780)$.
The slope weight went $0\to2.3\to0.78$: it overshot the answer $1.5$, then undershot. The intercept $0\to1\to0.32$ also overshot $0.333$ only slightly.
Why: the eigenvalues of $XX^T$ are $\lambda\approx16.64$ and $0.36$. Along the steep direction the error is multiplied by $1-2(0.05)(16.64)=-0.664$ (flips sign, shrinks). Along the flat direction by $1-2(0.05)(0.36)=0.964$ (barely shrinks).
Answer: $w^{(1)}=(1,2.3)$, $w^{(2)}=(0.320,0.780)$
Common mistake: expecting the loss to fall by a steady amount. A learning rate that suits the steep direction crawls along the flat one.

The first six iterates and the loss (it falls overall, not necessarily in a straight line):

step $t$$w^{(t)}=(w_0,w_1)$loss
0(0.000, 0.000)38.000
1(1.000, 2.300)16.860
2(0.320, 0.780)7.540
3(0.756, 1.796)3.431
4(0.452, 1.128)1.618
5(0.639, 1.578)0.818
6(0.501, 1.285)0.465

[ADDED] Stability bound for this example: $\eta<1/\lambda_{\max}=0.0601$. I ran gradient descent at $\eta=0.059$ (converges) and $\eta=0.062$ (diverges) to check.

[ADDED] Comparison: normal equation or gradient descent?

Normal equationGradient descent
what it doessolves $XX^Tw=Xy$ in one gorepeats small downhill steps
answerexact (if $XX^T$ is invertible)approximate, closer with every step
extra choicesnonelearning rate $\eta$, number of steps, start point
costabout $nd^2+d^3$ (building and solving a $d\times d$ system)about $nd$ per step
good when$d$ is small$d$ is huge, or the loss has no formula
exam style"optimal weight", "minimiser""next iteration", "after one step", "learning rate"
Memory trick: gradient descent

Say "minus gradient, step small, predict last." (1) Compute the gradient. (2) Subtract $\eta\times$ gradient. (3) Predict with the new weight. And before step one, read the loss: is there a $\tfrac12$ or a $\tfrac1n$ in front? That changes the gradient.

Recall: gradient descent

Write the update for the squared-loss with no $\tfrac12$.

$w\leftarrow w-\eta\,(2XX^Tw-2Xy)$.

For $P$ minimising $L$ and $Q$ minimising $L/n$ with the same $\eta$, who moves further per step?

$P$: its gradient is $n$ times larger. Same minimiser.

For one feature, for which $\eta$ does gradient descent converge?

$0<\eta<1/\sum x_i^2$ (plain sum loss).

The learning rate is huge. What happens to the loss?

It can overshoot, rise and diverge: the error is multiplied by a factor of absolute value above $1$ each step.

Interactive explorer

Gradient descent on a one-weight squared loss. Change the step size: small steps creep in, medium steps zigzag, and too large a step makes it blow up.

Stochastic gradient descent: one point or a small batch per step [ADDED]

The full gradient $2XX^Tw-2Xy$ visits every data point at every step. Stochastic gradient descent picks a few points at random (a batch) and uses only their part of the gradient, $2(\tilde X\tilde X^Tw-\tilde X\tilde y)$. After $T$ steps the course notes report the average of the iterates, $\frac1T\sum_t w^{(t)}$.

Worked example: one step each way

Data $(1,2),(2,3),(3,5)$, model $\hat y=wx$, start $w=0$, $\eta=0.01$.

  • Point $(3,5)$ only: gradient $2\cdot3\cdot(0-5)=-30$, so $w=0.30$.
  • Batch $\{(1,2),(3,5)\}$: gradient $-4-30=-34$, so $w=0.34$.
  • All three points: gradient $-4-12-30=-46$, so $w=0.46$.

The three single-point gradients add up to the full gradient. Each cheap step points roughly downhill, not exactly.

9. Probabilistic view: why least squares is maximum likelihood

Intuition

So far we asked "which line is closest?". The probabilistic view asks "if the world really produced the data as line plus random noise, which line makes the observed data most probable?" The answer turns out to be the same line. This explains why squared error is the right loss when noise is Gaussian.

Everyday analogy

A dart player aims at the true value $w^Tx$ but each throw lands with bell-shaped scatter around it. Given where the darts landed, the best guess of the aim point is the one that makes those landings most likely.

Model and likelihood

Definition: Gaussian noise model

$y_i=w^Tx_i+\epsilon_i$ with independent $\epsilon_i\sim N(0,\sigma^2)$. Equivalently $y_i\mid x_i\sim N(w^Tx_i,\sigma^2)$, density $\dfrac1{\sqrt{2\pi\sigma^2}}e^{-(y_i-w^Tx_i)^2/(2\sigma^2)}$.

Formula: negative log-likelihood

$$-\log P(y\mid X,w)=\frac n2\log(2\pi\sigma^2)+\frac1{2\sigma^2}\sum_{i=1}^n(y_i-w^Tx_i)^2$$ $n$ is the number of points, $\sigma^2$ the noise variance. Only the second term depends on $w$.

Consequences (each is an exam question)

  1. Maximising the likelihood in $w$ means minimising $\sum(y_i-w^Tx_i)^2$: MLE $=$ least squares.
  2. The noise variance $\sigma^2$ multiplies the loss by a constant, so it does not change $\hat w_{ML}$. Changing the assumed $\sigma^2$ (say from $\sigma^2$ to $4\sigma^2$) leaves $\hat w$ unchanged.
  3. If the fit is perfect ($\sum r_i^2=0$) the negative log-likelihood is just $\tfrac n2\log(2\pi\sigma^2)$.
  4. If the model mean is a different function, for instance $\log(wx_i)$, apply the same recipe: minimise $\sum(y_i-\text{mean}_i)^2$.
Worked example: Simple: NLL with a perfect fit

Problem. $\sigma^2=1$, $n=100$, $\sum r_i^2=0$. Find the negative log-likelihood in base $10$.

What is asked. $-\log_{10}P$.

Idea / formula used. $\tfrac n2\log_{10}(2\pi)+0$.

$\tfrac{100}{2}=50$.
$\log_{10}(2\pi)=0.7982$.
$50\times0.7982=39.91$.
Answer: about $39.9$
Common mistake: using the natural log ($\ln$) when the question says base $10$, which would give about $91.9$.
Worked example: Exam level: a log model

Problem. $y_i\mid x_i\sim N(\log(wx_i),1)$, $x_i>0$, $w>0$. Find $\hat w_{MLE}$.

What is asked. A formula for $\hat w$.

Idea / formula used. Minimise $\sum(y_i-\log w-\log x_i)^2$.

Let $u=\log w$. Loss $=\sum(y_i-\log x_i-u)^2$: a squared error around the constant $u$.
The minimiser of $\sum(a_i-u)^2$ is the average: $\hat u=\tfrac1n\sum(y_i-\log x_i)$.
Convert back: $\hat w=e^{\hat u}=\exp\!\big(\tfrac1n\sum(y_i-\log x_i)\big)$.
Numeric check with $x=(1,2,3)$, $y=(1.2, 2.1, 2.7)$: mean of $y_i-\log x_i$ is $1.4027$, so $\hat w=4.0664$.
Answer: $\hat w=\exp\!\big(\tfrac1n\sum(y_i-\log x_i)\big)$
Common mistake: dropping the $\exp$ (that gives $\log w$, not $w$) or multiplying the terms by $x_i$.
Trap: MLE versus MAP, and unbiased versus lowest error

The MLE is unbiased but may have higher mean squared error than a MAP/ridge estimate for a suitable $\lambda>0$ (bias is traded for lower variance). So "MLE always has lower MSE" is false. This is developed in the next topic.

Common mistakes

[ADDED] Picture: the noise variance does not move the best $w$

0.51.01.52.02.53.0010203040wσ² = 0.5σ² = 1σ² = 2same minimiser for every σ²: w = 23/14NLL(w) − constant = SSE(w) / (2σ²)
The part of the negative log-likelihood that depends on $w$, $\text{SSE}(w)/(2\sigma^2)$, for three noise variances on the running example. A larger $\sigma^2$ makes the bowl flatter, but the lowest point is at the same $w=23/14$ every time.

Reason: $\sigma^2$ only multiplies the whole $w$-dependent part by $\tfrac1{2\sigma^2}$. Multiplying a bowl by a positive number does not move its bottom.

[ADDED] Derivation: what if $\sigma^2$ is not given?

Fix $w$ at its best value, so that $\text{SSE}=S$. The negative log-likelihood as a function of $\sigma^2$ is $\ell(\sigma^2)=\tfrac n2\log(2\pi\sigma^2)+\dfrac{S}{2\sigma^2}$. Its slope is $\dfrac{n}{2\sigma^2}-\dfrac{S}{2\sigma^4}$. Set it to zero and multiply by $2\sigma^4$: $n\sigma^2-S=0$, so

$$\hat\sigma^2_{ML}=\frac{S}{n}=\frac1n\sum_i(y_i-\hat w^Tx_i)^2$$

In words: the best noise variance is the average squared residual. The smallest value of the negative log-likelihood is then $\tfrac n2\log(2\pi\hat\sigma^2)+\tfrac n2$ (natural log).

Worked example: Estimate the noise from a fitted line

Problem. The intercept fit of the running example: residuals $(-\tfrac16,\ \tfrac13,\ -\tfrac16)$, $n=3$.

What is asked. $\hat\sigma^2$ and the minimum NLL (natural log).

Idea / formula used. $\hat\sigma^2=S/n$.

$S=\tfrac1{36}+\tfrac19+\tfrac1{36}=\tfrac16=0.1667$.
$\hat\sigma^2=\tfrac16/3=\tfrac1{18}=0.0556$.
$\text{NLL}_{\min}=\tfrac32\ln(2\pi\cdot0.0556)+\tfrac32=\tfrac32(-1.0525)+1.5=-0.079$.
A negative value is fine: the density can be larger than $1$ when $\sigma^2$ is small. [ADDED] (A grid search over $\sigma^2$ in code lands on the same minimiser.)
Answer: $\hat\sigma^2=0.0556$, $\text{NLL}_{\min}=-0.079$
Common mistake: dividing by $n-1$ or by $n-d$. That is a different (unbiased) estimator. The maximum likelihood one divides by $n$.

[ADDED] Comparison: the same constant in three logarithm bases

The perfect-fit value is $\tfrac n2\log(2\pi\sigma^2)$ with $\sigma^2=1$. Only the base of the log changes the number:

$\log(2\pi)$$n=10$: $5\log(2\pi)$$n=100$: $50\log(2\pi)$
natural log $\ln$1.83799.1991.89
$\log_{10}$0.79823.9939.91
$\log_2$2.651513.26132.57
Memory trick: which log?

"Read the base before you touch the calculator." Convert between bases by multiplying: $\log_{10}x=\ln x\times0.4343$. The question in the PYQ bank asks for base $10$ (answer about $39.9$ for $n=100$); the same data in $\ln$ gives about $91.9$.

[ADDED] Comparison: what you must know to get each quantity

You wantYou needResult
$\hat w_{ML}$nothing about $\sigma^2$least squares solution
NLL value at the optimum$\sigma^2$, $n$ and the SSE$\tfrac n2\log(2\pi\sigma^2)+\tfrac{\text{SSE}}{2\sigma^2}$
best $\sigma^2$the SSE at the best $w$ and $n$$\text{SSE}/n$
NLL for a non-linear mean (e.g. $\log(wx)$)the mean functionminimise $\sum(y_i-\text{mean}_i)^2$; convert back

[ADDED] One more link worth knowing: Gaussian noise gives squared error. Other noise gives other losses (for example Laplace noise gives the sum of absolute errors). The loss you minimise is a statement about the noise you believe in.

Everyday analogy

Think of a thermometer reading that scatters around the true temperature. "Most likely true temperature" is the one that makes your actual readings least surprising.

Where this breaks: it assumes the scatter is bell-shaped, the same size everywhere, and independent between readings. If the noise is lopsided or grows with $x$, least squares is no longer "the" maximum-likelihood answer.

Recall: probabilistic view

Why is MLE the same as least squares for Gaussian noise?

The $w$-dependent part of the NLL is $\tfrac1{2\sigma^2}\sum(y_i-w^Tx_i)^2$. Minimising it is least squares.

Does changing $\sigma^2$ change $\hat w_{ML}$?

No. It only rescales the loss.

Perfect fit, $\sigma^2=1$, $n=10$. NLL (natural log)?

$5\ln(2\pi)=9.19$.

What is the ML estimate of $\sigma^2$?

The mean squared residual, $\text{SSE}/n$.

Practise this topic →

Weeks covering this topic

Other MLT topics