Least squares, projections, MLE view, gradient descent
Open the interactive lessons →Linear regression and gradient descent past questions
Contents
- Orientation: what you will learn and why
- Big picture: concept map, four roads and the shape table
- Start here: vectors, matrices and slopes, from zero
- The model, the loss and how to read a fitted line
- The optimal weight: normal equations, intercept and scaling
- Geometry: projection, orthogonality and spans
- Which model can lower the training loss?
- Gradient descent: updates, learning rate, SSE versus MSE
- 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
- Write the model $\hat y=w^Tx$ and the squared loss, and read the shapes of $X$, $w$, $y$ correctly ($X$ is $(d,n)$: columns are data points).
- Find the optimal weight from the normal equations $XX^Tw=Xy$, including the one-feature formula $w^*=\sum x_iy_i/\sum x_i^2$.
- Explain what an intercept (dummy feature) does, and why the residuals then add up to zero.
- Say what happens to $w^*$ when you scale $y$ or scale $x$.
- Use the geometric view: $X^Tw^*$ is the projection of $y$ onto the span of the features, and the error is perpendicular to it.
- Decide which model can reach a lower training error, and why regularisation cannot lower it.
- Run gradient descent by hand: compute the gradient, take a step, predict.
- Derive the maximum likelihood estimate from Gaussian noise and see why it equals least squares.
Why this topic matters for Quiz 2
Counted only from the PYQs in this project (not a prediction):
| What the PYQs ask | PYQs | Marks |
|---|---|---|
| Model, loss and reading a fitted line | 1 | 4 |
| Optimal weight: normal equations, intercept, scaling | 5 | 15 |
| Which model lowers training loss | 4 | 14 |
| Geometry: projection and spans | 4 | 11 |
| Gradient descent | 5 | 12 |
| Probabilistic view (MLE) | 4 | 13 |
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$.
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]
- A one-page concept map and shape table (next section).
- Figures for the loss bowl, the fitted line and residuals, the projection picture, nested fits, the learning-rate effect, the likelihood curves and an exam flowchart.
- Comparison tables, scaling and shifting rules, a singular-matrix example, the learning-rate limit, and the maximum-likelihood noise estimate.
- Mnemonics, recall questions (answers hidden) and a one-page revision with common mistakes.
- Everything new is marked [ADDED]. Nothing in the old notes was removed, and no PYQ was changed or added.
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
Four roads, one destination
| Road | What you do | Key equation | What it needs | Exam wording that points to it |
|---|---|---|---|---|
| Calculus | Set 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)$" |
| Geometry | Drop 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 descent | Start anywhere, repeat a small downhill step. | $w\leftarrow w-\eta\nabla L$ | a learning rate $\eta$ | "next iteration", "learning rate", "after one step" |
| Probability | Assume 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.
| Object | Shape | Lives in | Meaning | Example (d = 2, n = 3) |
|---|---|---|---|---|
| $X$ | $(d,n)$ | matrix | columns 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)$ | matrix | sums 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 gradient | zero at the optimum |
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
- Read the intuition and the picture of each section first.
- Predict the next line of every worked example before you reveal it.
- Do the short recall questions at the bottom of each section with the answer hidden.
- Attempt each PYQ before opening its solution.
- 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
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.
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
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".
One data point $x=(1,2)$, label $y=3$, weights $w=(2,1)$. Loss $L(w)=(w_1+2w_2-3)^2$.
[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).
| Symbol | Meaning in words | Value |
|---|---|---|
| $\sum x_i$ | add all the $x$ values | 6 |
| $\sum x_i^2$ | square each $x$ first, then add | 14 |
| $\sum x_iy_i$ | multiply each pair first, then add | 23 |
| $\sum y_i$ | add all the $y$ values | 10 |
| $\bar x,\ \bar y$ | the averages | $\bar x=2,\ \bar y=3.3333$ |
$(\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.
- 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.
Match the inner sizes before multiplying.
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.
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
$\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.
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.
$$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.
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$.
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
- Forgetting the dummy feature and then expecting residuals to add to zero.
- Reading $X^Tw$ with the wrong shape (rows are features).
- Calling the loss "mean" when it is a sum; sum and mean differ by a factor $n$ (matters in gradient descent).
[ADDED] Reading the picture: three points, two fitted lines
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 1 | point 2 | point 3 | |
|---|---|---|---|
| feature $1$ | 1 | 1 | 1 |
| feature $x$ | 1 | 2 | 3 |
| feature $x^2$ | 1 | 4 | 9 |
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$).
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 name | Formula | Gradient | Gradient at $w=0$ (example) | Same minimiser? |
|---|---|---|---|---|
| SSE (plain sum) | $\sum(wx_i-y_i)^2$ | $2\sum x_i(wx_i-y_i)$ | -46 | yes |
| half SSE | $\tfrac12\sum(wx_i-y_i)^2$ | $\sum x_i(wx_i-y_i)$ | -23 | yes |
| MSE | $\tfrac1n\sum(wx_i-y_i)^2$ | $\tfrac2n\sum x_i(wx_i-y_i)$ | -15.333 | yes |
| half MSE | $\tfrac1{2n}\sum(wx_i-y_i)^2$ | $\tfrac1n\sum x_i(wx_i-y_i)$ | -7.667 | yes |
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 error | 1 | 2 | 3 | 10 |
|---|---|---|---|---|
| absolute error | 1 | 2 | 3 | 10 |
| squared error | 1 | 4 | 9 | 100 |
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
| Convention | Residual | Gradient written as | Gradient 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.
"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
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)
- Loss $L(w)=\sum_i(w^Tx_i-y_i)^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.)
- At the minimum the gradient is $0$: $X(X^Tw-y)=0$, i.e. $XX^Tw=Xy$.
- If $XX^T$ can be inverted, $w^*=(XX^T)^{-1}Xy$.
$$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
| Change | Effect 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 points | no change | both $XX^T$ and $Xy$ double |
| add points on the fitted line | no change | they add zero residual, so the gradient is unchanged |
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$.
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$.
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$.
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
[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.
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.
[ADDED] Which sums are zero at the optimum? (computed on the two fits above)
| Quantity | No intercept (dashed fit) | With intercept (solid fit) | Why |
|---|---|---|---|
| $\sum_i r_ix_i$ (residual dotted with the feature) | 0.0000 | 0.0000 | normal equations: always zero |
| $\sum_i r_i$ (residuals added) | -0.1429 (not zero) | 0.0000 | zero only if a dummy feature of ones is present |
| $\sum_i r_i\hat y_i$ (residual dotted with prediction) | 0.0000 | 0 | prediction is a combination of the features |
| $\sum_i r_i^2$ (the loss) | 0.2143 | 0.1667 | zero 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$).
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.
[ADDED] What happens to $w^*$ when the data are changed? (every row verified by code)
| Change to the data | No intercept | With 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$intercept | all ×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^*$ changes | slope unchanged, intercept $-c\cdot$slope | $x+1$: intercept -1.167; no-intercept weight 1.1379 (was 1.6429) |
| duplicate every point | no change | no change | both sums double, the ratio stays |
| add a point exactly on the fitted line | no change | no change | its residual is zero, so the gradient is unchanged |
"$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$.)
"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.
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$.
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
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$.
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$.
(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
| Situation | Then | Squared 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$ |
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)$.
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$.
Common mistakes
- Mixing the two spans: features span lives in $\mathbb R^n$ (where $X^Tw$ and $y$ live); data points span lives in $\mathbb R^d$ (where $w$ lives).
- Thinking "orthogonal weight" means zero loss.
[ADDED] The picture, with every part labelled
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$.
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
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$.
[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?
| Situation | Is the training error $0$? | Reason |
|---|---|---|
| $y$ lies in the span of the features | yes | $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 point | no: error is $\|y\|^2$ | $X^Tw^*=0$, so all predictions are $0$ |
| one outlier far off the trend | no | a 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$) |
| contains | every 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) |
"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.
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
| Change | Training loss | Why |
|---|---|---|
| add a dummy feature (intercept) | can decrease, never increases | the old model is the special case $w_0=0$ |
| move from degree 1 to degree 2 (add $x^2$) | can decrease, never increases | quadratics include all lines ($w_2=0$) |
| add $L_2$ or $L_1$ penalty | cannot decrease (usually increases) | the penalty forbids the unpenalised optimum |
| kernel regression with degree-2 kernel | can decrease | more 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.
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.
"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
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
| Change | Training SSE | Reason | Test error |
|---|---|---|---|
| add an intercept | never rises | old model is the case $w_0=0$ | may rise or fall |
| add any extra feature (even a useless one) | never rises | old model is the case where its weight is $0$ | a useless feature can hurt |
| raise the polynomial degree | never rises | lower degree is a special case | can overfit |
| add an $L_1$ or $L_2$ penalty | never falls (usually rises) | the penalised optimum is a different point | may fall |
| add more data points | never 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 sum | same minimiser | differs by the constant $n$ | same |
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
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)$.
"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
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
$$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 small | moves correctly but very slowly |
| good | converges steadily |
| too large | overshoots; 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$.
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)$.
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.
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$.
Common mistakes
- Moving along the gradient instead of against it.
- Mixing the SSE and MSE gradients (factor $n$) or dropping the factor $2$.
- Using $XX^T$ of the wrong shape for $d>1$ (it is $d\times d$).
[ADDED] A 1-D picture of "how big a step is too big"
[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$ | behaviour | distance to optimum after 60 steps |
|---|---|---|---|
| $0.002$ | 0.944 | converges, slowly | 0.052 |
| $1/28\approx0.0357$ | 0.000 | converges in one step (exact) | $<10^{-9}$ |
| $0.05$ | -0.400 | zigzags, converges | $<10^{-9}$ |
| $1/14\approx0.0714$ | -1.000 | bounces between two values forever | 1.643 |
| $0.08$ | -1.240 | diverges | 662065.428 |
[ADDED] All five rows were produced by running the update in code, not typed.
[ADDED] Worked example with two weights (intercept and slope)
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}$.
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 equation | Gradient descent | |
|---|---|---|
| what it does | solves $XX^Tw=Xy$ in one go | repeats small downhill steps |
| answer | exact (if $XX^T$ is invertible) | approximate, closer with every step |
| extra choices | none | learning rate $\eta$, number of steps, start point |
| cost | about $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" |
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.
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)}$.
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.
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
$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)}$.
$$-\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)
- Maximising the likelihood in $w$ means minimising $\sum(y_i-w^Tx_i)^2$: MLE $=$ least squares.
- 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.
- If the fit is perfect ($\sum r_i^2=0$) the negative log-likelihood is just $\tfrac n2\log(2\pi\sigma^2)$.
- 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$.
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$.
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$.
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
- Thinking the noise variance changes $\hat w$.
- Forgetting $\tfrac n2\log(2\pi\sigma^2)$ is a constant that still counts in an NLL value.
- Confusing the sign: we minimise the negative log-likelihood.
[ADDED] Picture: the noise variance does not move the best $w$
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).
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$.
[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.8379 | 9.19 | 91.89 |
| $\log_{10}$ | 0.7982 | 3.99 | 39.91 |
| $\log_2$ | 2.6515 | 13.26 | 132.57 |
"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 want | You need | Result |
|---|---|---|
| $\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 function | minimise $\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.
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$.
Weeks covering this topic
- Week 5: Linear regression and kernel regression
- Week 6: Probabilistic view, Ridge, Lasso and cross-validation