Linear regression

Lecture 7 (Linear Regression I), rebuilt as one storyline: the model, the line, the geometry behind it, and the matrix formula that covers every case.

How to read this page. It is ordered by concept, not by slide. Each card says which slides it came from, what to read first, and what uses it later.

Teal = explanation added by Claude, not on the slides. Amber = watch out. Dropdowns hide worked examples, practice questions, and their answers.

The road to the regression formula

RMSE, residual plots and the Iris examples are side stops: useful for interpreting a fit, but the main chain does not need them.

Lecture map: which slides each card covers

Part 1

From unsupervised to supervised

The regression model: a target plus noise

Until now we only had a data table and looked for structure in it. Now each row also has an answer, and we want a rule that predicts the answer for new rows.

Weeks 1–6 (unsupervised): only a data matrix \(D\). Find structure (mean, covariance, kernels), reduce dimensions (PCA, kernel PCA).

From today (supervised): a data matrix \(D\) and a target \(Y\). Learn a rule that predicts \(Y\) for new points.

Target \(Y\)TypeTask
delivery time, energy load, latencynumericlinear regression
spam or not, digit 0–9categoricallogistic regression

Given predictors \(\mathbf X = (X_1,\dots,X_d)^T\) and a response \(Y\):

\[ Y = f(\mathbf X) + \varepsilon \]

Goal: learn \(f\) from training data \(\{(\mathbf x_i, y_i)\}_{i=1}^n\).

Two goals: predict \(Y\) for new cases, and explain how each \(X_i\) affects \(Y\).

\(X_1,\dots,X_d\)
predictors (inputs), \(d\) of them
\(Y\)
response (the thing to predict)
\(f(\mathbf X)\)
the part of \(Y\) explained by the predictors
\(\varepsilon\)
random error, independent of \(\mathbf X\): measurement noise plus everything not measured (latent variables)
\(n\)
number of training rows

Delivery time depends on distance, but also on traffic, weather and the driver. What we do not measure ends up in \(\varepsilon\). The slides' examples: food delivery (distance, stops → time), power grid (temperature, hour → load), real estate (area, rooms → price), language models (compute → test loss).

Part 2

The line and the error

The linear model: bias plus weights

We guess that the answer is a weighted sum of the inputs plus a constant. With one input it is a straight line, with two it is a flat plane.

Assume \(f\) is linear in \(\mathbf X\):

\[ f(\mathbf X) = b + w_1 X_1 + w_2 X_2 + \cdots + w_d X_d \]

In vector form:

\[ f(\mathbf X) = b + \mathbf w^T \mathbf X \]
  • \(d = 1\): a line. \(d = 2\): a plane. General \(d\): a hyperplane in \(\mathbb R^{d+1}\).
  • \(d + 1\) unknown parameters.

Prediction for a point \(\mathbf x_i\):

\[ \hat y_i = b + \mathbf w^T \mathbf x_i \]

Residual:

\[ \epsilon_i = y_i - \hat y_i \]
\(b\)
bias or intercept: the prediction when every input is 0
\(w_i\)
regression coefficient (weight) of \(X_i\): how much \(\hat y\) changes per unit of \(X_i\)
\(\hat y_i\)
predicted value for row \(i\) (hat = fitted, not observed)
\(\epsilon_i\)
residual: observed minus predicted, for row \(i\)

\(\varepsilon\) in the model is the true, unknown noise. \(\epsilon_i = y_i - \hat y_i\) is the residual you can compute after fitting. The residual is our estimate of the noise.

Least squares: pick the line with the smallest squared error

There are many possible lines. We choose the one whose total squared miss, added over all points, is smallest.

Choose \(b\) and \(\mathbf w\) to minimize the sum of squared errors:

\[ \mathrm{SSE} = \sum_{i=1}^n \epsilon_i^2 \] \[ \mathrm{SSE} = \sum_{i=1}^n \big(y_i - b - \mathbf w^T \mathbf x_i\big)^2 \]

Why squares?

  • Positive and negative errors do not cancel.
  • Smooth: calculus gives a closed-form answer.
  • Large errors are penalized heavily.

Because SSE is a smooth bowl in \(b\) and \(\mathbf w\), setting its derivatives to zero gives the minimum directly. Every formula on this page comes from doing exactly that.

Part 3

One predictor

One predictor: intercept and slope

For one input, the best line always goes through the point of averages, and its slope is the covariance of the two variables divided by the variance of the input.

One predictor:

\[ \hat y_i = b + w\,x_i \] \[ \mathrm{SSE}(b, w) = \sum_i (y_i - b - w\,x_i)^2 \]

Intercept: set the derivative with respect to \(b\) to zero

\[ \frac{\partial\,\mathrm{SSE}}{\partial b} = -2 \sum_{i=1}^n (y_i - b - w\,x_i) = 0 \] \[ b = \frac1n \sum_i y_i - w \cdot \frac1n \sum_i x_i \] \[ b = \mu_Y - w\,\mu_X \]

The fitted line always passes through the mean point \((\mu_X, \mu_Y)\).

Slope: set the derivative with respect to \(w\) to zero

\[ \frac{\partial\,\mathrm{SSE}}{\partial w} = -2 \sum_{i=1}^n x_i\,(y_i - b - w\,x_i) = 0 \]

Substitute \(b = \mu_Y - w\,\mu_X\) and rearrange:

\[ w = \frac{\sum_i x_i y_i - n\,\mu_X \mu_Y}{\sum_i x_i^2 - n\,\mu_X^2} \] \[ w = \frac{\sum_i (x_i - \mu_X)(y_i - \mu_Y)}{\sum_i (x_i - \mu_X)^2} \] \[ w = \frac{\sigma_{XY}}{\sigma_X^2} = \frac{\operatorname{cov}(X, Y)}{\operatorname{var}(X)} \]

The slope has the sign of the covariance; Lecture 3 statistics are all we need.

\(\mu_X, \mu_Y\)
sample means of the input and the response
\(\sigma_{XY}\)
sample covariance of \(X\) and \(Y\)
\(\sigma_X^2\)
sample variance of \(X\)

Recipe: fit a line by hand

  1. Compute \(\mu_X\) and \(\mu_Y\).
  2. Make a table with columns \(x_i - \mu_X\), \(y_i - \mu_Y\), \((x_i - \mu_X)^2\), \((x_i-\mu_X)(y_i-\mu_Y)\).
  3. \[ w = \frac{\sum (x_i - \mu_X)(y_i - \mu_Y)}{\sum (x_i - \mu_X)^2} \]
  4. \[ b = \mu_Y - w\,\mu_X \]
  5. Write the line \(\hat y = b + w x\) and use it to predict.

The slope is a ratio of a covariance to a variance. Whether both use \(1/n\) or \(1/(n-1)\), the factor cancels. The sums in the table need no division at all.

Delivery times: fit the line by hand and predict 7 km

A delivery company records five orders in Doha. How long should a 7 km order take?

Order\(x\) (km)\(y\) (min)
1215
2416
3624
4830
51035
  1. \[ \mu_X = \frac{30}{5} = 6 \]
  2. \[ \mu_Y = \frac{120}{5} = 24 \]
  3. Deviation table:
    \(x_i\)\(y_i\)\(x_i - \mu_X\)\(y_i - \mu_Y\)\((x_i-\mu_X)^2\)\((x_i-\mu_X)(y_i-\mu_Y)\)
    215−4−91636
    416−2−8416
    6240000
    83026412
    10354111644
    sum40108
  4. \[ w = \frac{108}{40} = 2.7 \]
  5. \[ b = 24 - 2.7 \times 6 = 7.8 \]
  6. \[ \hat y = 7.8 + 2.7\,x \]
  7. \[ \hat y(7) = 7.8 + 2.7 \times 7 = 26.7 \text{ min} \]

Interpretation (s11): each extra km adds about 2.7 minutes; 7.8 min is the fixed time per order (pickup, parking). Predicting at 30 km is extrapolation: there is no data there.

Five delivery points with the fitted line through the mean point
L7 s11: the fitted line passes through \((\mu_X, \mu_Y) = (6, 24)\). The short vertical bars are residuals.
Same delivery line from the covariance numbers alone

Using \(1/n\), the delivery data has \(\sigma_X^2 = 8\) and \(\sigma_{XY} = 21.6\), with \(\mu_X = 6\) and \(\mu_Y = 24\). Find the line without the table, then check against the slide.

  1. \[ w = \frac{\sigma_{XY}}{\sigma_X^2} = \frac{21.6}{8} = 2.7 \]
  2. \[ b = 24 - 2.7 \times 6 = 7.8 \]
  3. Same line as the slide. The sums 108 and 40 divided by \(n = 5\) are 21.6 and 8, so the ratio is unchanged.

Residuals and their two zero-sum identities

A residual is how far each point sits above or below the line. For a least-squares line, the residuals always add up to zero and are not correlated with the input.

Residual of row \(i\):

\[ \epsilon_i = y_i - \hat y_i \]

Least-squares residuals always satisfy:

\[ \sum_i \epsilon_i = 0 \] \[ \sum_i x_i\,\epsilon_i = 0 \]

(the two derivative equations)

Setting \(\partial\,\mathrm{SSE}/\partial b = 0\) is the same as \(\sum \epsilon_i = 0\). Setting \(\partial\,\mathrm{SSE}/\partial w = 0\) is the same as \(\sum x_i \epsilon_i = 0\). The geometry card residuals are orthogonal says the same thing with vectors.

Delivery residuals and SSE
\(x_i\)\(y_i\)\(\hat y_i\)\(\epsilon_i = y_i - \hat y_i\)
21513.21.8
41618.6−2.6
62424.00.0
83029.40.6
103534.80.2
  1. \[ \mathrm{SSE} = 3.24 + 6.76 + 0 + 0.36 + 0.04 \]
  2. \[ \mathrm{SSE} = 10.4 \]
  3. Check one: \[ \sum_i \epsilon_i = 1.8 - 2.6 + 0 + 0.6 + 0.2 = 0 \]
  4. Check two: \[ \sum_i x_i \epsilon_i = 3.6 - 10.4 + 0 + 4.8 + 2.0 = 0 \]

Root mean squared error: a typical miss in the units of \(Y\)

SSE grows with the number of points and is in squared units. RMSE fixes both, so it tells you how far off a typical prediction is.

\[ \mathrm{RMSE} = \sqrt{\frac{\mathrm{SSE}}{n}} \] \[ \mathrm{RMSE} = \sqrt{\frac1n \sum_{i=1}^n (y_i - \hat y_i)^2} \]

RMSE is in the units of \(Y\), so it tells you whether the error matters in practice: 1.4 minutes is fine for a delivery app; 20 minutes would not be.

Delivery RMSE
  1. \[ \mathrm{RMSE} = \sqrt{\frac{10.4}{5}} \]
  2. \[ \mathrm{RMSE} = \sqrt{2.08} = 1.44 \text{ min} \]

A typical prediction is off by about 1.4 minutes.

Residual plots: what a good fit looks like

Plot each residual against its prediction. If you can see a shape, the straight line is missing something, no matter how small the error number is.

  • Plot \(\epsilon_i\) against \(\hat y_i\). A good model leaves no visible pattern.
  • A curve means the relationship is nonlinear; a funnel means the error size changes with \(\hat y\).
  • A small SSE or RMSE does not rule out either problem.
Three residual plots: random scatter, a curve, and a funnel
L7 s14: random scatter is fine; a curve means missing nonlinearity; a funnel means the spread grows with \(\hat y\).

Iris: petal width from petal length

The same recipe on 150 flowers. The numbers are bigger, but the only inputs are the two means, one variance and one covariance.

\(n = 150\). Predictor \(X\): petal length (cm). Response \(Y\): petal width (cm).

\[ \mu_X = 3.7587, \quad \mu_Y = 1.1987 \] \[ \sigma_X^2 = 3.0924, \quad \sigma_{XY} = 1.2877 \] \[ w = \frac{1.2877}{3.0924} = 0.4164 \] \[ b = 1.1987 - 0.4164 \times 3.7587 = -0.3665 \] \[ \hat y = -0.3665 + 0.4164\,x \]

SSE = 6.343, RMSE = 0.206 cm. No strong curve or funnel in the residual plot: a straight line is adequate.

The slides use the original UCI Iris file. scikit-learn's copy corrects two entries, so its means, slope and SSE differ in the third decimal (s32 says so). In an exam, use the numbers the question gives you.

Part 4

The geometry: least squares is a projection

This part explains why the formulas work. It is also the route HW2 Q6 asks for.

Two views of the data: rows as points, columns as vectors

So far each order was a dot on a 2-D plot. Now flip it: each variable becomes one long vector with one entry per order, and fitting a line means choosing one vector.

Row view (so far): each order is a point \((x_i, y_i)\) in \(\mathbb R^2\). Five points; the line passes through the cloud.

Column view (now): each variable is one vector in \(\mathbb R^n = \mathbb R^5\):

\[ \mathbf 1 = \begin{bmatrix}1\\1\\1\\1\\1\end{bmatrix}, \quad X = \begin{bmatrix}2\\4\\6\\8\\10\end{bmatrix}, \quad Y = \begin{bmatrix}15\\16\\24\\30\\35\end{bmatrix} \]

Every choice of \((b, w)\) turns the \(n\) predictions into one vector:

\[ \hat Y = b\,\mathbf 1 + w\,X \]

For the fitted line \((b, w) = (7.8, 2.7)\):

\[ \hat Y = 7.8 \begin{bmatrix}1\\1\\1\\1\\1\end{bmatrix} + 2.7 \begin{bmatrix}2\\4\\6\\8\\10\end{bmatrix} = \begin{bmatrix}13.2\\18.6\\24.0\\29.4\\34.8\end{bmatrix} \] \[ \boldsymbol\epsilon = Y - \hat Y = \begin{bmatrix}1.8\\-2.6\\0\\0.6\\0.2\end{bmatrix} \]
  • All possible \(\hat Y\) form a plane: \(\operatorname{span}\{\mathbf 1, X\}\) inside \(\mathbb R^5\).
  • \(\mathrm{SSE} = \|Y - \hat Y\|^2\) is the squared distance from \(Y\) to \(\hat Y\): here 10.4.
\(\mathbf 1\)
the vector of \(n\) ones (it carries the intercept)
\(X, Y\)
capital letters now mean the whole column of \(n\) values
\(\operatorname{span}\{\mathbf 1, X\}\)
every vector of the form \(b\mathbf 1 + wX\): a 2-D plane inside \(\mathbb R^n\)

Least squares = orthogonal projection of \(Y\) onto the plane

The data vector is not in the plane because the data are noisy. The closest point in the plane is found by dropping a perpendicular, and that closest point is the fitted vector.

  • \(Y\) is not in the plane: the data are noisy.
  • Least squares asks for the point of the plane closest to \(Y\).
  • The closest point is found by dropping a perpendicular: \(\boldsymbol\epsilon \perp\) the plane.
  • So \(\hat Y\) is the orthogonal projection of \(Y\) onto \(\operatorname{span}\{\mathbf 1, X\}\).
Y above a plane spanned by 1 and X, with its projection Y-hat and the perpendicular residual
L7 s20: \(\hat Y\) is the foot of the perpendicular from \(Y\) to the plane spanned by \(\mathbf 1\) and \(X\).

Projecting onto a unit vector was card “Projection” on the Lectures 3–4 page. The only new thing is that the target is a plane with two directions, and they are not at right angles, so we first split them.

Make the two directions orthogonal, then project onto each

\(\mathbf 1\) and \(X\) are not orthogonal. Split \(X\) into a part along \(\mathbf 1\) and a centred part:

\[ X = \mu_X \mathbf 1 + \bar X \] \[ \bar X = X - \mu_X \mathbf 1 \quad (\bar X \perp \mathbf 1) \]

Now project \(Y\) onto the orthogonal pair \(\mathbf 1, \bar X\):

\[ \operatorname{proj}_{\mathbf 1}(Y) = \frac{Y^T \mathbf 1}{\mathbf 1^T \mathbf 1} = \mu_Y \] \[ w = \operatorname{proj}_{\bar X}(Y) = \frac{Y^T \bar X}{\bar X^T \bar X} = \frac{\sigma_{XY}}{\sigma_X^2} \] \[ \hat Y = \mu_Y \mathbf 1 + w\,\bar X \] \[ \hat Y = \underbrace{(\mu_Y - w\,\mu_X)}_{b}\,\mathbf 1 + w\,X \]

Iris: \(\mu_Y = 179.8/150 = 1.1987\), \(w = 193.16/463.86 = 0.4164\). The same line as before.

\(Y^T \bar X = \sum (y_i)(x_i - \mu_X)\) equals \(\sum (y_i - \mu_Y)(x_i - \mu_X)\) because \(\bar X\) sums to zero. And \(\bar X^T \bar X = \sum (x_i - \mu_X)^2\). So \(w\) is the covariance-over-variance slope again.

What the perpendicular residual means

  • \(\boldsymbol\epsilon \perp \mathbf 1\) ⇒ residuals sum to zero.
  • \(\boldsymbol\epsilon \perp X\) ⇒ residuals are uncorrelated with the predictor: the line has used all the linear information in \(X\).
  • \(\hat Y\) is the closest point to \(Y\) in the plane: any other line gives a larger SSE.

Delivery check:

\[ \sum_i \epsilon_i = 1.8 - 2.6 + 0 + 0.6 + 0.2 = 0 \] \[ \sum_i x_i \epsilon_i = 3.6 - 10.4 + 0 + 4.8 + 2.0 = 0 \]

Recipe: the “geometric approach” a question may ask for

  1. Write \(\mathbf 1\), \(X\) and \(Y\) as column vectors of length \(n\).
  2. Form \(A = [\mathbf 1 \; X]\) and compute \(A^T A\) and \(A^T Y\).
  3. Solve \((A^T A)\,(b, w)^T = A^T Y\) with the 2×2 inverse (next part has the formula).
  4. \[ \hat Y = A\,(b, w)^T = b\,\mathbf 1 + w\,X \]
  5. Check: \(\boldsymbol\epsilon = Y - \hat Y\) sums to zero and \(X^T \boldsymbol\epsilon = 0\).
Predicted vector and the line by the geometric approach

Data: \(X = (5, 0, 2, 1, 2)\), \(Y = (2, 1, 1, 1, 0)\). (a) Compute the predicted response vector \(\hat Y\) for least-squares regression using the geometric approach. (b) Extract the bias and slope and give the equation of the best-fitting line.

  1. \[ A = [\mathbf 1 \; X] = \begin{bmatrix}1&5\\1&0\\1&2\\1&1\\1&2\end{bmatrix} \]
  2. Sums: \(\sum x_i = 10\), \(\sum x_i^2 = 34\), \(\sum y_i = 5\), \(\sum x_i y_i = 13\).
  3. \[ A^T A = \begin{bmatrix} n & \sum x_i \\ \sum x_i & \sum x_i^2 \end{bmatrix} = \begin{bmatrix}5&10\\10&34\end{bmatrix} \]
  4. \[ A^T Y = \begin{bmatrix} \sum y_i \\ \sum x_i y_i \end{bmatrix} = \begin{bmatrix}5\\13\end{bmatrix} \]
  5. \[ \det(A^T A) = 5 \times 34 - 10 \times 10 = 70 \]
  6. \[ (A^T A)^{-1} = \frac{1}{70} \begin{bmatrix}34&-10\\-10&5\end{bmatrix} \]
  7. \[ \begin{bmatrix} b \\ w \end{bmatrix} = \frac{1}{70} \begin{bmatrix}34&-10\\-10&5\end{bmatrix} \begin{bmatrix}5\\13\end{bmatrix} = \frac{1}{70} \begin{bmatrix}170 - 130\\-50 + 65\end{bmatrix} \]
  8. \[ \begin{bmatrix} b \\ w \end{bmatrix} = \begin{bmatrix} 4/7 \\ 3/14 \end{bmatrix} = \begin{bmatrix} 0.5714 \\ 0.2143 \end{bmatrix} \]
  9. \[ \hat Y = \frac47 \mathbf 1 + \frac{3}{14} X = \begin{bmatrix} 23/14 \\ 4/7 \\ 1 \\ 11/14 \\ 1 \end{bmatrix} = \begin{bmatrix} 1.6429 \\ 0.5714 \\ 1.0000 \\ 0.7857 \\ 1.0000 \end{bmatrix} \]
  10. (b) Bias \(b = 4/7 = 0.5714\), slope \(w = 3/14 = 0.2143\): \[ \hat y = 0.5714 + 0.2143\,x \]
  11. Check: residuals \(Y - \hat Y = (0.3571, 0.4286, 0, 0.2143, -1)\) sum to 0, and \(X^T \boldsymbol\epsilon = 1.7857 + 0 + 0 + 0.2143 - 2 = 0\).

\(\mu_X = 2\), \(\mu_Y = 1\), \(\sum (x_i-2)(y_i-1) = 3\), \(\sum (x_i - 2)^2 = 14\), so \(w = 3/14\) and \(b = 1 - (3/14)(2) = 4/7\). Both routes agree; the question says “geometric”, so show the matrix route for credit.

Part 5

Multiple regression

Absorb the bias: one weight vector for all \(d + 1\) parameters

Add a column of ones to the data, and the intercept becomes just another weight. Then one matrix formula covers one predictor, two, or a hundred.

\(d\) predictors \(X_1, \dots, X_d\); training data \(D \in \mathbb R^{n \times d}\), responses \(Y \in \mathbb R^n\).

Add a constant column \(X_0 = \mathbf 1\):

\[ \tilde D = [\mathbf 1 \; D] \in \mathbb R^{n \times (d+1)} \] \[ \tilde{\mathbf w} = (b, w_1, \dots, w_d)^T \]

Prediction for row \(i\) and for all rows at once:

\[ \hat y_i = w_0 x_{i0} + w_1 x_{i1} + \cdots + w_d x_{id} = \tilde{\mathbf w}^T \tilde{\mathbf x}_i \] \[ \hat Y = \tilde D \tilde{\mathbf w} \]

One vector \(\tilde{\mathbf w}\) now holds all \(d+1\) parameters, so a single formula covers every case.

\(\tilde D\)
the data matrix with a column of ones in front (tilde = augmented)
\(\tilde{\mathbf w}\)
bias first, then the \(d\) weights
\(\tilde{\mathbf x}_i\)
row \(i\) of \(\tilde D\), i.e. \((1, x_{i1}, \dots, x_{id})^T\)

With \(d = 1\), \(\tilde D\) is exactly the matrix \(A = [\mathbf 1 \; X]\) from the projection card. HW2 Q6 calls it \(A\).

Normal equations: the closed-form solution

Write SSE with matrices, set its gradient to zero, and the best weights come out of one matrix inverse. This is the formula the exam will give you.

\[ \mathrm{SSE} = \|Y - \tilde D \tilde{\mathbf w}\|^2 \] \[ \mathrm{SSE} = Y^T Y - 2\,\tilde{\mathbf w}^T (\tilde D^T Y) + \tilde{\mathbf w}^T (\tilde D^T \tilde D)\,\tilde{\mathbf w} \]

Set the gradient to zero:

\[ \nabla_{\tilde{\mathbf w}} \mathrm{SSE} = -2\,\tilde D^T Y + 2\,(\tilde D^T \tilde D)\,\tilde{\mathbf w} = 0 \] \[ (\tilde D^T \tilde D)\,\tilde{\mathbf w} = \tilde D^T Y \] \[ \tilde{\mathbf w} = (\tilde D^T \tilde D)^{-1} \tilde D^T Y \]
  • Geometry: \(\hat Y = \tilde D \tilde{\mathbf w}\) is the projection of \(Y\) onto the column space of \(\tilde D\).
  • Requires \(\tilde D^T \tilde D\) invertible: no predictor is an exact combination of the others.
\(\tilde D^T \tilde D\)
\((d+1) \times (d+1)\) matrix of sums of products of the columns
\(\tilde D^T Y\)
vector of sums of products of each column with \(Y\)

Recipe: normal equations by hand

  1. Build \(\tilde D\) by putting a column of ones before the predictors.
  2. Compute \(\tilde D^T \tilde D\): entry \((j,k)\) is the dot product of columns \(j\) and \(k\). The top-left entry is \(n\).
  3. Compute \(\tilde D^T Y\): entry \(j\) is the dot product of column \(j\) with \(Y\).
  4. Invert \(\tilde D^T \tilde D\) (2×2 by formula; 3×3 only if the question makes it easy) and multiply.
  5. Read off \(b\) first, then \(w_1, \dots, w_d\).

If one predictor is a copy or an exact combination of others (for example temperature in °C and in °F), \(\tilde D^T \tilde D\) is singular and there is no unique \(\tilde{\mathbf w}\). Nearly-dependent predictors are the topic of the correlated predictors card.

Hand calculation with centred data

Subtract the means first and the intercept drops out of the matrix. With two predictors you only need to invert a 2×2 matrix, then get the bias from the means.

Centre every column first: \(\bar D\) (predictors minus their means), \(\bar Y = Y - \mu_Y \mathbf 1\).

\[ \mathbf w = (\bar D^T \bar D)^{-1} \bar D^T \bar Y \] \[ b = \mu_Y - \mathbf w^T \boldsymbol\mu_X \]
  • \(\bar D^T \bar D = n\,\Sigma\): \(n\) times the covariance matrix of the predictors.
  • \(\bar D^T \bar Y\): \(n\) times the covariances of each \(X_i\) with \(Y\).

With \(d = 2\) we only need to invert a 2×2 matrix:

\[ \begin{bmatrix} a & c \\ c & e \end{bmatrix}^{-1} = \frac{1}{ae - c^2} \begin{bmatrix} e & -c \\ -c & a \end{bmatrix} \]
\(\bar D\)
\(n \times d\) matrix of centred predictors (no column of ones)
\(\boldsymbol\mu_X\)
vector of the \(d\) predictor means
\(\Sigma\)
covariance matrix of the predictors, with \(1/n\)

Recipe: two predictors by hand

  1. Compute the means \(\mu_1, \mu_2, \mu_Y\) and centre all three columns.
  2. \[ \bar D^T \bar D = \begin{bmatrix} \sum \bar x_{i1}^2 & \sum \bar x_{i1}\bar x_{i2} \\ \sum \bar x_{i1}\bar x_{i2} & \sum \bar x_{i2}^2 \end{bmatrix} \]
  3. \[ \bar D^T \bar Y = \begin{bmatrix} \sum \bar x_{i1} \bar y_i \\ \sum \bar x_{i2} \bar y_i \end{bmatrix} \]
  4. Invert the 2×2 with the formula and multiply to get \(\mathbf w = (w_1, w_2)^T\).
  5. \[ b = \mu_Y - w_1 \mu_1 - w_2 \mu_2 \]

With one predictor, \(w = \sigma_{XY}/\sigma_X^2\). With two, do not divide covariances one at a time; the inverse matrix mixes them. Dividing separately is only correct when the two predictors are uncorrelated (off-diagonal entry 0).

Delivery time from distance and number of stops

The company also records how many stops each driver made. Fit \(\hat y = b + w_1 x_1 + w_2 x_2\).

Distance \(x_1\)Stops \(x_2\)Time \(y\)\(x_1 - 6\)\(x_2 - 2\)\(y - 24\)
2115−4−1−9
4116−2−1−8
6224000
8330216
103354111
  1. Means: \(\mu_1 = 6\), \(\mu_2 = 2\), \(\mu_Y = 24\) (the centred columns are in the table).
  2. \[ \bar D^T \bar D = \begin{bmatrix} 40 & 12 \\ 12 & 4 \end{bmatrix} \]
  3. \[ \bar D^T \bar Y = \begin{bmatrix} 108 \\ 34 \end{bmatrix} \]
  4. \[ \det = 40 \times 4 - 12 \times 12 = 160 - 144 = 16 \]
  5. \[ (\bar D^T \bar D)^{-1} = \frac{1}{16} \begin{bmatrix} 4 & -12 \\ -12 & 40 \end{bmatrix} \]
  6. \[ \mathbf w = \frac{1}{16} \begin{bmatrix} 4 \cdot 108 - 12 \cdot 34 \\ -12 \cdot 108 + 40 \cdot 34 \end{bmatrix} = \frac{1}{16} \begin{bmatrix} 24 \\ 64 \end{bmatrix} \]
  7. \[ \mathbf w = \begin{bmatrix} 1.5 \\ 4 \end{bmatrix} \]
  8. \[ b = 24 - 1.5 \times 6 - 4 \times 2 = 7 \]
  9. \[ \hat y = 7 + 1.5\,x_1 + 4\,x_2 \]

Interpreting the coefficients (s28):

ModelWeight of distanceSSERMSE (min)
Distance only2.710.41.44
Distance + stops1.54.00.89
  • \(w_1 = 1.5\): one extra km adds 1.5 min when the number of stops is held fixed.
  • \(w_2 = 4\): each extra stop adds 4 min at the same distance.
  • Longer trips had more stops, so the simple model gave distance credit for the stops.

A coefficient's meaning depends on which other predictors are in the model.

Two predictors, four rows, by hand

\(x_1 = (1, 2, 3, 4)\), \(x_2 = (2, 1, 4, 3)\), \(y = (5, 6, 10, 12)\). Fit \(\hat y = b + w_1 x_1 + w_2 x_2\) with the centred method, then find the SSE.

  1. Means: \(\mu_1 = 2.5\), \(\mu_2 = 2.5\), \(\mu_Y = 8.25\).
  2. Centred columns: \(\bar x_1 = (-1.5, -0.5, 0.5, 1.5)\), \(\bar x_2 = (-0.5, -1.5, 1.5, 0.5)\), \(\bar y = (-3.25, -2.25, 1.75, 3.75)\).
  3. \[ \bar D^T \bar D = \begin{bmatrix} 5 & 3 \\ 3 & 5 \end{bmatrix} \]
  4. \[ \bar D^T \bar Y = \begin{bmatrix} 12.5 \\ 9.5 \end{bmatrix} \]
  5. \[ \det = 25 - 9 = 16 \]
  6. \[ (\bar D^T \bar D)^{-1} = \frac{1}{16} \begin{bmatrix} 5 & -3 \\ -3 & 5 \end{bmatrix} \]
  7. \[ \mathbf w = \frac{1}{16} \begin{bmatrix} 62.5 - 28.5 \\ -37.5 + 47.5 \end{bmatrix} = \frac{1}{16} \begin{bmatrix} 34 \\ 10 \end{bmatrix} = \begin{bmatrix} 2.125 \\ 0.625 \end{bmatrix} \]
  8. \[ b = 8.25 - 2.125 \times 2.5 - 0.625 \times 2.5 = 1.375 \]
  9. \[ \hat y = 1.375 + 2.125\,x_1 + 0.625\,x_2 \]
  10. Predictions \((4.75, 6.25, 10.25, 11.75)\), residuals \((0.25, -0.25, -0.25, 0.25)\).
  11. \[ \mathrm{SSE} = 4 \times 0.0625 = 0.25 \]

Iris with two predictors: a fitted plane

With sepal length added as a second input, the model is a plane and the error barely improves. The numbers show what the normal equations look like at full size.

\(X_1\): sepal length, \(X_2\): petal length, \(Y\): petal width, \(n = 150\).

\[ \tilde D^T \tilde D = \begin{bmatrix} 150.0 & 876.50 & 563.80 \\ 876.50 & 5223.85 & 3484.25 \\ 563.80 & 3484.25 & 2583.00 \end{bmatrix} \] \[ \tilde D^T Y = \begin{bmatrix} 179.80 \\ 1127.65 \\ 868.97 \end{bmatrix} \] \[ \tilde{\mathbf w} = (\tilde D^T \tilde D)^{-1} \tilde D^T Y = \begin{bmatrix} -0.014 \\ -0.082 \\ 0.450 \end{bmatrix} \] \[ \hat y = -0.014 - 0.082\,x_1 + 0.450\,x_2 \]

SSE = 6.179 (vs. 6.343 with petal length alone), RMSE = 0.203 cm.

  • The model is a plane in \((X_1, X_2, Y)\) space.
  • Open points lie above the plane (\(\epsilon_i \gt 0\)), filled points below.
  • Adding sepal length barely reduces the SSE.

Top-left is \(n = 150\). The first row holds the column sums \(\sum x_{i1} = 876.5\) and \(\sum x_{i2} = 563.8\). The rest are sums of squares and cross products. You will not be asked to invert a 3×3 like this by hand; the centred route reduces it to 2×2.

Correlated predictors: why a weight can flip sign

When two inputs carry almost the same information, the model cannot tell which one deserves the credit, so individual weights become unstable and hard to interpret.

  • Sepal length alone: \(\hat y = -3.206 + 0.754\,x_1\).
  • With petal length in the model: \(w_1 = -0.082\).
  • The predictors are strongly correlated (\(r = 0.87\)): they carry almost the same information.
  • With petal length fixed, sepal length adds almost nothing.

Correlated predictors (multicollinearity) make individual weights unstable. Lecture 8 fixes this with ridge regression.

Scatter of petal length against sepal length for Iris, correlation 0.87
L7 s31: sepal length and petal length move together (\(r_{12} = 0.87\)).

High correlation makes \(\bar D^T \bar D\) nearly singular: its determinant \(ae - c^2\) is small, so the inverse has large entries and small changes in the data swing the weights a lot.

In software, and a warning about training error

Software does the whole fit in three lines. But a small error on the training data does not prove the model will predict well on new data.

from sklearn.datasets import load_iris
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

X = load_iris().data
D, y = X[:, [0, 2]], X[:, 3]        # sepal & petal length -> petal width
model = LinearRegression().fit(D, y)
print(model.intercept_, model.coef_)   # b, (w1, w2)
y_hat = model.predict(D)
print(mean_squared_error(y, y_hat) ** 0.5)     # RMSE

scikit-learn's Iris corrects two entries, so its results differ slightly from the slides.

  • Adding a predictor can never increase the training SSE, even when the new predictor is pure noise.
  • With as many parameters as points (\(d + 1 = n\)) the fit is perfect: SSE = 0.
  • A small training error does not guarantee good predictions on new data.

Next lecture: evaluate on test data, control model complexity with ridge and lasso, and solve large problems with gradient descent.

The old model is a special case of the new one (set the new weight to 0). Least squares picks the best of a bigger set, so it can only do at least as well. That is also why training error is a poor judge.

Part 6

Exam toolkit

Which formula, when

The question asks for…UseCard
the line for one predictor, data given as a table\(w = \dfrac{\sum (x_i-\mu_X)(y_i-\mu_Y)}{\sum (x_i-\mu_X)^2}\), then \(b = \mu_Y - w\mu_X\)Slope & intercept
the line when only \(\sigma_{XY}\), \(\sigma_X^2\) and the means are given\(w = \sigma_{XY}/\sigma_X^2\), \(b = \mu_Y - w\mu_X\)Slope & intercept
“the geometric approach” or “the normal equations”\(A = [\mathbf 1 \; X]\), \((b,w)^T = (A^T A)^{-1} A^T Y\), \(\hat Y = A(b,w)^T\)Projection view
two or more predictors by handcentre, \(\mathbf w = (\bar D^T \bar D)^{-1} \bar D^T \bar Y\), \(b = \mu_Y - \mathbf w^T \boldsymbol\mu_X\)Hand calculation (centred)
a prediction for a new input\(\hat y = b + \mathbf w^T \mathbf x\); flag extrapolation if \(\mathbf x\) is outside the data rangeLinear model
the residuals, SSE, or a check of the fit\(\epsilon_i = y_i - \hat y_i\), \(\mathrm{SSE} = \sum \epsilon_i^2\), confirm \(\sum \epsilon_i = 0\) and \(\sum x_i \epsilon_i = 0\)Residuals
a typical error size in the units of \(Y\)\(\mathrm{RMSE} = \sqrt{\mathrm{SSE}/n}\)RMSE
whether a straight line is adequatelook at the residual plot, not just the SSEResidual plots
why a weight changed after adding a predictorcorrelated predictors share the creditCorrelated predictors
  • Show every step: the sums table, the determinant, the inverse, then the weights.
  • Check the mean point: the fitted line must pass through \((\mu_X, \mu_Y)\). If it does not, something is wrong.
  • Matrix multiplication: for \((A^T A)^{-1} A^T Y\), compute \(A^T Y\) first (a small vector), then multiply by the inverse.