COMP328 Fundamentals of Machine Learning

1 Learning objectives

By the end of this tutorial you will be able to

  • Define a residual precisely, including its sign convention, and explain the difference between a residual and an error.
  • Write the residual sum of squares (RSS) for a linear model and explain each part of the expression.
  • Give three reasons why the residuals are squared rather than taken in absolute value or left raw.
  • Derive the least-squares solution for the no-intercept case by hand.
  • Derive the least-squares solution for the intercept case and state the two normal equations.
  • Write the solution in matrix form as ŵ = (XᵀX)⁻¹Xᵀy, and state the conditions under which this inverse exists.
  • State the four algebraic properties that any least-squares fit must satisfy.
  • Explain the geometric interpretation of least squares as an orthogonal projection.

Estimated time

35 minutes of reading, plus 25–30 minutes for the practice exercises and problem set. This is the most derivation-heavy tutorial in Unit 4; work through the algebra on paper rather than reading it.

2 Motivating example

Suppose you plot the eight bike-share observations from Tutorial 1 and, by eye, draw a line through them. You now have a model. But so does the person sitting next to you, and their line is slightly different, and neither of you can say which one is better — you only disagree about which points "look" more important.

Eyeballing is how regression was done before the 1800s, and it has two problems. It is subjective, so two analysts get two answers. And it does not scale: with one feature you can draw a line on paper, but with twenty features you cannot draw anything at all.

What we need is a rule: a single number that scores any candidate line, so that "best" becomes a well-defined question with a computable answer. Adrien-Marie Legendre proposed such a rule in 1805, and Gauss used it to predict the orbit of Ceres from a handful of observations — a prediction that turned out to be accurate enough to relocate the asteroid. The rule is least squares.

Among all straight lines, choose the one that minimises the sum of the squared vertical distances from the data points to the line.

That is the whole idea. The rest of this tutorial is the consequences of it: why squaring is the right choice, what the resulting formula is, and what guarantees come with it.

The rule gives you

  • One unique answer for a given dataset
  • A formula you can compute directly
  • A number you can compare across models
  • Provable guarantees about the fit

The rule costs you

  • Sensitivity to outliers (squaring amplifies them)
  • An assumption that errors are symmetric
  • A tendency to optimise the mean rather than the median
  • Nothing at all, if those trade-offs suit your problem

3 Concept explanation

3.1 The residual

For a single training example i, the model predicts ŷi = w xi + b. The observed value is yi. Their difference is the residual:

ei = yi − ŷi

The sign convention matters and is worth fixing in your memory now:

  • Positive residual — the model predicted too low. The point sits above the line.
  • Negative residual — the model predicted too high. The point sits below the line.
  • Zero residual — the point lies exactly on the line.

Residual vs. error

These are often used interchangeably, but there is a meaningful distinction. The error is the difference between the observation and the true underlying relationship — a quantity you never observe. The residual is the difference between the observation and your fitted model — a quantity you can always compute. Residuals are estimates of errors, and they are only good estimates if the model is appropriate. This distinction becomes important in Tutorial 6, when you use residuals to diagnose whether the linear assumption holds.

3.2 The residual sum of squares

You cannot simply add up all the residuals to get a single measure of badness, because positive and negative residuals cancel. In Tutorial 1 you saw this directly: the mean baseline's residuals summed to exactly zero, even though the baseline was a terrible predictor.

The least-squares criterion solves this by squaring each residual before summing:

RSS(w, b) = Σi=1n (yi − w xi − b)²

Read this as a function of the parameters. For any pair (w, b) you choose, RSS tells you how badly that particular line fits the data. The least-squares solution is the pair (ŵ, b̂) that makes RSS as small as possible:

(ŵ, b̂) = argminw, b RSS(w, b)

3.3 Why square?

Squaring is not the only way to combine residuals into a single number. You could sum the absolute values instead — that gives least absolute deviations, which is also a perfectly respectable method. So why does least squares dominate?

Three ways to combine residuals
Criterion Formula Property
Sum of residuals Σ ei Always zero for a model with an intercept. Useless as a loss.
Sum of absolute residuals Σ |ei| Robust to outliers, but not differentiable at zero.
Sum of squared residuals Σ ei² Smooth, differentiable, and has a closed-form solution.

Three reasons push least squares ahead:

  1. It is differentiable everywhere. The absolute value function has a sharp corner at zero, which makes it awkward to minimise with calculus. The square is smooth, so you can take derivatives and set them to zero — which is exactly how the closed-form solution is derived.
  2. It has a closed-form solution. Because the squared criterion is a quadratic in the parameters, its minimum can be written down directly. Least absolute deviations has no such formula and must be solved iteratively.
  3. It is the maximum-likelihood solution under Gaussian noise. If you assume the true relationship is linear and the deviations from it are independent draws from a normal distribution with constant variance, then maximising the likelihood of the observed data is exactly the same as minimising RSS. This is a strong justification, and it comes with a whole statistical toolkit for free.

The cost of squaring

Squaring is not free. A residual of 10 contributes 100 to RSS; a residual of 1 contributes 1. So a single point that is ten times further from the line has one hundred times the influence. A single extreme outlier can drag the entire fitted line toward itself. Whenever you fit a least-squares model, plot the residuals and look for points that dominate. If outliers are common in your data, least absolute deviations or a robust regression method may be the better choice — a point you will revisit in Tutorial 6 and again in Module 4.

3.4 Deriving the solution — the simplest case

Start with a model that has no intercept, so the line is forced through the origin: ŷ = w x. This case is contrived but the algebra is short, and the result generalises.

The criterion is:

RSS(w) = Σ (yi − w xi)²

Expand the square and differentiate with respect to w:

RSS(w)  = Σ (yᵢ² − 2 yᵢ w xᵢ + w² xᵢ²)

dRSS
────  = Σ (−2 yᵢ xᵢ + 2 w xᵢ²)
 dw
      = −2 Σ xᵢ yᵢ  +  2 w Σ xᵢ²

Set the derivative to zero. The factor of 2 cancels, and the condition becomes:

Σ xi yi = w Σ xi²

So the least-squares slope is:

ŵ = Σ xi yi / Σ xi²

The second derivative is 2 Σ xi², which is positive unless every xi is zero. So this stationary point is a minimum, not a maximum or a saddle — the RSS curve is a parabola opening upward, and there is exactly one bottom.

3.5 Deriving the solution — with an intercept

Now the real case: ŷ = w x + b. RSS is now a function of two parameters, so we need two partial derivatives, and both must be zero at the minimum.

RSS(w, b) = Σ (yi − w xi − b)²

Partial derivative with respect to b:

∂RSS
────  = Σ −2 (yᵢ − w xᵢ − b)
 ∂b
      = −2 ( Σ yᵢ − w Σ xᵢ − n b )   =  0

Dividing by −2 and rearranging:

Σ yi − w Σ xi − n b = 0

Dividing through by n and using the notation x̄ = Σxi/n and ȳ = Σyi/n:

b̂ = ȳ − ŵ x̄

This is the first normal equation, and it has a memorable consequence: the fitted line always passes through the point (x̄, ȳ), the centroid of the data.

Partial derivative with respect to w:

∂RSS
────  = Σ −2 xᵢ (yᵢ − w xᵢ − b)
 ∂w
      = −2 ( Σ xᵢ yᵢ − w Σ xᵢ² − b Σ xᵢ )   =  0

Dividing by −2:

Σ xi yi − w Σ xi² − b Σ xi = 0

This is the second normal equation. Now substitute the first into the second to eliminate b:

Σ xᵢ yᵢ  −  w Σ xᵢ²  −  ( ȳ − w x̄ ) Σ xᵢ   =  0

Σ xᵢ yᵢ  −  w Σ xᵢ²  −  n x̄ ȳ  +  w n x̄²   =  0

( Σ xᵢ yᵢ − n x̄ ȳ )   =   w ( Σ xᵢ² − n x̄² )

The two grouped quantities have standard names:

Sxy = Σ xi yi − n x̄ ȳ      Sxx = Σ xi² − n x̄²

Sxy is the sum of cross-products; it measures how much x and y move together. Sxx is the sum of squared deviations of x; it measures how spread out the feature is. Both are directly computable from the raw sums, which is how statistical software has computed regression since long before computers.

The solution is therefore:

The least-squares solution for simple linear regression

ŵ = Sxy / Sxx      b̂ = ȳ − ŵ x̄

where Sxy = Σxiyi − n x̄ ȳ and Sxx = Σxi² − n x̄².

If Sxx is zero

Sxx = 0 means every xi is identical — the feature never varies. In that case the slope is undefined (the denominator is zero), which makes sense: if the input never changes, there is no way to estimate how the output responds to it. In this situation the model degenerates to predicting the mean. You will see this generalise in Section 3.7 to the condition that XᵀX must be invertible.

3.6 Four properties of the least-squares fit

The normal equations are not just a computational trick — they imply four properties that any least-squares fit must satisfy. They are also the fastest way to check whether a computer has done the arithmetic correctly.

Properties implied by the normal equations
Property Statement Why
Residuals sum to zero Σ ei = 0 This is the first normal equation, divided by −2.
Residuals are orthogonal to the features Σ xi ei = 0 This is the second normal equation, rearranged.
The line passes through the centroid (x̄, ȳ) lies exactly on the fitted line Direct consequence of b̂ = ȳ − ŵ x̄.
The mean of the predictions equals the mean of the targets Σ ŷi = Σ yi, so ȳ̂ = ȳ Follows from the residuals summing to zero.

The second property is the one that generalises most usefully. In the matrix form of the next section it becomes Xᵀe = 0 — the residual vector is orthogonal to every column of the design matrix. That single equation is the geometric heart of least squares.

3.7 The matrix form

With more than one feature, writing out the algebra feature by feature becomes unmanageable. The matrix form handles any number of features at once.

First, absorb the intercept into the weight vector by prepending a column of ones to the design matrix. Define:

      ⎡ 1  x₁₁  x₁₂  ⋯  x₁d ⎤              ⎡ w₀ ⎤            ⎡ y₁ ⎤
X  =  ⎢ 1  x₂₁  x₂₂  ⋯  x₂d ⎥  ,   w  =  ⎢ w₁ ⎥  ,   y  =  ⎢ y₂ ⎥
      ⎢ ⋮   ⋮    ⋮   ⋱   ⋮  ⎥              ⎢ ⋮  ⎥            ⎢ ⋮  ⎥
      ⎣ 1  xₙ₁  xₙ₂  ⋯  xₙd ⎦              ⎣ wd ⎦            ⎣ yₙ ⎦

The first column of ones multiplies w₀, which plays the role of the intercept. The model for all n examples at once is ŷ = Xw, and the criterion becomes:

RSS(w) = ‖y − Xw‖² = (y − Xw)ᵀ(y − Xw)

Expanding and differentiating with respect to the vector w (using the standard vector-calculus identities) gives the gradient:

∇RSS = −2 Xᵀ(y − Xw)

Setting this to zero:

Xᵀ ( y − X w )  =  0

Xᵀ y  −  Xᵀ X w  =  0

Xᵀ X w  =  Xᵀ y          ← the normal equations

Multiplying both sides by the inverse of XᵀX:

The normal equation

ŵ = (XᵀX)⁻¹ Xᵀy

This is the single most important formula in this tutorial. Everything in the preceding sections — the centroid property, the two normal equations, the residual orthogonality — is a special case of it. And it is what LinearRegression().fit(X, y) is Computing when you call it, though scikit-learn uses a numerically more stable decomposition rather than forming the inverse explicitly.

When the normal equation fails

The formula requires XᵀX to be invertible. That fails in two common situations:

  • Perfect collinearity. One feature is an exact linear combination of others — for example, including both "temperature in °C" and "temperature in °F", or all k levels of a categorical variable plus an intercept. The matrix is singular and there is no unique solution.
  • More features than examples. If d ≥ n, there are infinitely many parameter vectors that fit the training data perfectly, and the criterion cannot distinguish between them.

Both cases are solved by regularisation — adding a penalty term that makes the solution unique again. Ridge regression does exactly this, and you will meet it in Module 3.

3.8 The geometric interpretation

There is a way of seeing least squares that makes the orthogonality property obvious rather than algebraic.

Think of the target vector y as a point in n-dimensional space — one dimension per training example. The columns of X span a d+1-dimensional subspace of that space: every possible prediction Xw that the model could ever make lies in that subspace.

Least squares asks: which point in the subspace is closest to y? The answer, from elementary geometry, is the orthogonal projection of y onto the subspace. And the defining property of an orthogonal projection is that the difference between the original vector and its projection is perpendicular to the subspace:

Xᵀ(y − Xŵ) = 0

which is precisely the normal equations. The residual vector is orthogonal to every column of the design matrix. What looked like an algebraic convenience is actually a geometric necessity.

4 Visual illustration

Data points with a candidate line and vertical residual segments Five data points plotted against a feature axis and a target axis, with a candidate straight line. Vertical dashed segments connect each point to the line, representing the residuals. The segments vary in length, and the sum of their squared lengths is the residual sum of squares for this candidate line. Feature x Target y candidate line residual eᵢ
Figure 1. A candidate line and the residuals it produces. The residuals are the vertical distances — not the perpendicular distances — from each point to the line. The least-squares solution is the line that makes the sum of the squared lengths of these red segments as small as possible.
Contour plot of the residual sum of squares over the slope and intercept Concentric elliptical contours of the residual sum of squares plotted in the space of slope and intercept. The ellipses are nested, with the smallest at the centre, marking the unique least-squares solution. The bowl shape means the surface has a single global minimum and no local minima. Slope w Intercept b least-squares solution (ŵ, b̂) — the unique minimum RSS increasing outward →
Figure 2. Contours of RSS(w, b) for the bike-share data. Each ellipse is a set of parameter pairs that produce the same RSS. The contours are nested and the smallest closes around a single point — the least-squares solution. Because the surface is a convex bowl, that point is the global minimum, and there is no risk of gradient-based methods getting stuck somewhere else.
Geometric view of least squares as an orthogonal projection A diagram showing the target vector y and the two-dimensional subspace spanned by the columns of the design matrix. The least-squares prediction is the orthogonal projection of y onto that subspace, and the residual vector from the prediction to y is perpendicular to the subspace. column space of X y ŷ = Xŵ residual e = y − ŷ the residual is orthogonal to every column of X → Xᵀ(y − Xŵ) = 0
Figure 3. The geometric view. The model can only produce predictions that lie in the subspace spanned by the columns of X. Least squares chooses the point in that subspace closest to the observed y — the orthogonal projection. The residual is perpendicular to the subspace, which is exactly what the normal equations say.

5 Worked example

We return to the bike-share data from Tutorial 1 and fit a least-squares line by hand, then compare it against the mean baseline.

Step 1 — The data and the required sums

Bike-share sample with the quantities needed for the normal equations
i xi (°C) yi (rentals) xi yi xi²
1812096064
2121802,160144
3152403,600225
4183005,400324
5213607,560441
62443010,320576
72751013,770729
83056016,800900
Sum 2,700 60,570 3,403

From these totals:

n   = 8
x̄   = 155 / 8   = 19.375
ȳ   = 2700 / 8  = 337.5

Step 2 — Compute Sxy and Sxx

Sxy = Σ xᵢ yᵢ  −  n · x̄ · ȳ
    = 60,570   −  8 × 19.375 × 337.5
    = 60,570   −  52,312.5
    = 8,257.5

Sxx = Σ xᵢ²    −  n · x̄²
    = 3,403    −  8 × 19.375²
    = 3,403    −  8 × 375.390625
    = 3,403    −  3,003.125
    = 399.875

Note the shortcut: n x̄ ȳ = (Σx)(Σy)/n = (155 × 2700) / 8 = 52,312.5, which avoids Computing the means first. Both routes give the same answer.

Step 3 — Solve for the slope and intercept

ŵ = Sxy / Sxx
   = 8,257.5 / 399.875
   ≈ 20.6502

b̂ = ȳ − ŵ · x̄
   = 337.5 − 20.6502 × 19.375
   = 337.5 − 400.0976
   ≈ −62.5976

The fitted model is therefore:

rentals ≈ 20.65 × temperature − 62.60

Reading the coefficients

The slope of 20.65 means: each additional degree Celsius is associated with about 20.65 more rentals per hour, on average. The intercept of −62.60 is the predicted rental count at 0 °C. It is negative, which is physically impossible — but that is not a defect, because 0 °C is far outside the observed range of 8–30 °C. Extrapolating a fitted line beyond the data is almost always a mistake, and this is a clean illustration of why.

Step 4 — Verify the normal equations hold

Fitted values and residuals
x y ŷ = 20.6502x − 62.598 e = y − ŷ x · e e²
8120102.60+17.40139.20302.76
12180185.20−5.20−62.4027.04
15240247.16−7.16−107.4051.27
18300309.11−9.11−163.9882.99
21360371.06−11.06−232.26122.32
24430433.01−3.01−72.249.06
27510494.96+15.04406.08226.20
30560556.91+3.0992.709.55
Sum +0.00 −0.90 831.19

Both normal equations hold to within rounding error:

  • The residuals sum to +0.00, as the first normal equation requires.
  • The cross-products Σ xi ei sum to −0.90, which is negligible against the magnitudes involved (the individual terms reach ±406). It would be exactly zero with unrounded coefficients.

Step 5 — Compare with the baseline

RSS  = 831.19
MSE  = 831.19 / 8   = 103.90
RMSE = √103.90      ≈ 10.19 rentals

Baseline (from Tutorial 1):
RSS  = 171,350
RMSE = 146.3 rentals

Improvement in RMSE:  146.3 → 10.19   (a 93% reduction)

R² = 1 − RSS / TSS
   = 1 − 831.19 / 171,350
   ≈ 0.9951

The fitted line explains 99.5% of the variance in rentals. For this particular synthetic dataset that is unsurprising — the relationship really is almost perfectly linear in temperature — but the comparison is the point: the baseline had an RMSE of 146.3 and this model has 10.19, so the feature is doing real work.

On real bike-share data the fit will be much weaker, because weather is only one of several drivers and the relationship is not exactly linear. Tutorials 7 and 8 use real data for exactly that reason.

The same computation in code

import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression

df = pd.DataFrame({
    "temp_c":  [ 8, 12, 15, 18, 21, 24, 27, 30],
    "rentals": [120, 180, 240, 300, 360, 430, 510, 560],
})

x = df["temp_c"].to_numpy()
y = df["rentals"].to_numpy()
n = len(x)

# --- from scratch, using the normal equations ---
Sxy = (x * y).sum() - n * x.mean() * y.mean()
Sxx = (x ** 2).sum() - n * x.mean() ** 2

w = Sxy / Sxx
b = y.mean() - w * x.mean()

print(f"from scratch : w = {w:.4f}, b = {b:.4f}")

# --- the same thing via scikit-learn ---
model = LinearRegression().fit(x.reshape(-1, 1), y)

print(f"scikit-learn : w = {model.coef_[0]:.4f}, b = {model.intercept_:.4f}")

# --- residuals and metrics ---
y_hat = w * x + b
resid = y - y_hat

rss  = (resid ** 2).sum()
rmse = np.sqrt(rss / n)

print(f"residuals sum: {resid.sum():.6f}")
print(f"RSS          : {rss:.2f}")
print(f"RMSE         : {rmse:.2f}")
from scratch : w = 20.6502, b = -62.5976
scikit-learn : w = 20.6502, b = -62.5976
residuals sum: 0.000000
RSS          : 831.19
RMSE         : 10.19

The two approaches agree to four decimal places, as they must. scikit-learn computes the answer via a QR or SVD decomposition rather than forming (XᵀX)⁻¹ explicitly, because the decomposition is numerically more stable — but the mathematical answer is identical.

nb-03 · Least squares from scratch Implement the normal equations with NumPy, verify them against scikit-learn, and plot the fitted line with its residuals.

6 Interactive activity

Break the fit on purpose

Using the bike-share dataset and the fitted line ŷ = 20.65x − 62.60, do each of the following in the notebook and record what happens:

  1. Add an outlier. Append one observation: 20 °C, 2,000 rentals. Re-fit the model. By how much does the slope change? Compare with adding an observation 20 °C, 420 rentals instead.
  2. Change the units. Convert temperature from °C to °F using xF = 1.8xC + 32 and re-fit. What happens to the slope? What happens to the intercept? What happens to the predictions?
  3. Reflect the data. Negate the target — treat rentals as negative — and re-fit. What is the relationship between the new slope and the old one?
  4. Remove the intercept. Force the line through the origin by fitting ŷ = wx only. What is the new slope? Does the fit improve or get worse, and why must it be worse?
Show the discussion
  1. The outlier dominates. A single point at 2,000 rentals has a squared residual that dwarfs every other term, and the fitted line will swing dramatically upward to reduce it. A point at 420 rentals — only 60 above what the line predicts — barely moves the fit. This is the cost of squaring, made concrete: influence grows with the square of the distance from the line.
  2. The slope shrinks by a factor of 1.8, the intercept changes substantially, and the predictions are identical. The model ŷ = 20.65xC − 62.60 and the model ŷ = 11.47xF − 429.6 produce exactly the same prediction for the same physical temperature. The parameters are not intrinsic properties of the data — they are tied to the units and the encoding. This is why standardising features matters when you compare coefficients across variables.
  3. Every coefficient flips sign. If you replace y with −y, the least-squares criterion is unchanged up to a sign, so the optimal slope becomes −20.65 and the intercept becomes +62.60. Least squares is linear in the target, which is a property you will use constantly when reasoning about model behaviour.
  4. The no-intercept fit must be worse. Removing the intercept restricts the model to lines through the origin, which is a strict subset of all lines. Since the unconstrained solution already achieves the minimum RSS over the larger set, any constraint can only hold RSS equal or raise it. Here the data are clearly not centred on the origin, so the constrained fit is substantially worse. The principle — adding parameters can never increase the minimum RSS — is the seed of overfitting, which is the subject of Tutorials 6 and 7.

The habit to build

Every one of those four manipulations is something you should do routinely when fitting a model for real. Perturb a point, change the units, flip a sign, remove a parameter — and watch what moves. A model whose coefficients you cannot predict the behaviour of is a model you do not yet understand.

7 Self-check questions

Answer each question in your own words before revealing the answer.

Question 1

A model predicts 250 rentals and the observed value is 230. What is the residual, and what does its sign tell you?

Show answer
e = y − ŷ = 230 − 250 = −20. The residual is negative, which means the model over-predicted — the point lies below the fitted line. Reversing the convention would flip every sign in the derivation but would not change the minimisation, because the square removes the sign anyway.

Question 2

Why can't we use the sum of residuals, Σ ei, as the quantity to minimise?

Show answer
Because any model with an intercept will have Σ ei = 0 at the minimum — and worse, many other parameter choices also give a sum near zero while fitting terribly. Positive and negative residuals cancel, so the sum carries no information about the magnitude of the errors. A model that is 500 too high on half the points and 500 too low on the others would score perfectly. Squaring removes the sign and makes each error contribute a positive amount.

Question 3

Give the three main reasons least squares is preferred over least absolute deviations, and one reason it might be the worse choice.

Show answer

Reasons for least squares:

  • The squared criterion is differentiable everywhere, so calculus applies cleanly.
  • It has a closed-form solution, so no iteration is required.
  • It coincides with maximum likelihood under Gaussian noise, which brings a full statistical toolkit with it.

Reason against: squaring gives outliers disproportionate influence, because influence grows with the square of the distance. When the data contain heavy-tailed noise or genuine outliers that should not drive the fit, least absolute deviations or a robust method will be more appropriate.

Question 4

State the four properties that any least-squares fit with an intercept must satisfy, and explain which normal equation each comes from.

Show answer
  1. Σ ei = 0 — from the first normal equation, ∂RSS/∂b = 0.
  2. Σ xi ei = 0 — from the second normal equation, ∂RSS/∂w = 0.
  3. The line passes through (x̄, ȳ) — an immediate consequence of b̂ = ȳ − ŵx̄.
  4. Σ ŷi = Σ yi — follows from (1), since Σŷi = Σ(yi − ei) = Σyi.

In matrix form, (1) and (2) together are Xᵀe = 0.

Question 5

A colleague fits a model with 40 features on 25 training examples and reports a perfect fit — every residual is zero. What has gone wrong, and why does the normal equation fail here?

Show answer
There are more parameters (41, including the intercept) than training examples (25). With d ≥ n, the design matrix has more columns than rows, so the columns cannot be linearly independent and XᵀX is singular — it has no inverse. In fact there are infinitely many parameter vectors that fit the 25 points exactly, and least squares cannot choose between them, because they all achieve RSS = 0. The "perfect fit" is not a success: the model has memorised the training data and will almost certainly generalise terribly. The fix is regularisation (ridge or lasso), which adds a penalty that makes the solution unique again, or reducing the number of features.

Question 6

In the geometric picture, what does the residual vector represent, and what is it perpendicular to?

Show answer
The residual vector e = y − Xŵ is the difference between the observed target vector and its orthogonal projection onto the column space of X. It is perpendicular to that entire subspace — equivalently, perpendicular to every column of the design matrix. That orthogonality condition, Xᵀe = 0, is the normal equations. The geometric view shows that least squares is not an arbitrary algebraic choice: it is the unique point in the model's reachable subspace that is closest to the data.

8 Practice exercises

Work these by hand first, then verify in the notebook. Use the formulas ŵ = Sxy/Sxx and b̂ = ȳ − ŵx̄.

Exercise 1 — No-intercept fit

Fit the model ŷ = wx (no intercept) to the following data using ŵ = Σxiyi / Σxi².

x = [1, 2, 3, 4]
y = [2, 5, 7, 10]
  1. Compute Σxiyi and Σxi².
  2. Compute ŵ.
  3. Compute the residual for each point and verify that they do not sum to zero. Why not?
  4. Compute the RSS.
Show answers

1. Σxiyi = 1(2) + 2(5) + 3(7) + 4(10) = 2 + 10 + 21 + 40 = 73.
Σxi² = 1 + 4 + 9 + 16 = 30.

2. ŵ = 73 / 30 = 2.4333.

3. Predictions: 2.433, 4.867, 7.300, 9.733.
Residuals: −0.433, +0.133, −0.300, +0.267. Sum = −0.333. They do not sum to zero because there is no intercept. The property Σei = 0 comes from the first normal equation, which only exists when b is a free parameter. Constrain the line to pass through the origin and that equation no longer applies — the fit can be systematically biased above or below the data.

4. RSS = 0.1876 + 0.0178 + 0.0900 + 0.0711 = 0.3665.

Exercise 2 — Full fit with intercept

Now fit ŷ = wx + b to a slightly larger dataset.

x = [1, 2, 3, 4, 5]
y = [3, 5, 6, 9, 12]
  1. Compute x̄ and ȳ.
  2. Compute Sxy and Sxx.
  3. Compute ŵ and b̂.
  4. Compute all five residuals and verify they sum to zero.
  5. Compute RSS, MSE, RMSE and R².
Show answers

1. Σx = 15, so x̄ = 3. Σy = 35, so ȳ = 7.

2. Σxiyi = 1(3) + 2(5) + 3(6) + 4(9) + 5(12) = 3 + 10 + 18 + 36 + 60 = 127.
Sxy = 127 − 5(3)(7) = 127 − 105 = 22.
Σxi² = 1 + 4 + 9 + 16 + 25 = 55.
Sxx = 55 − 5(3²) = 55 − 45 = 10.

3. ŵ = 22 / 10 = 2.2.
b̂ = 7 − 2.2(3) = 7 − 6.6 = 0.4.
Model: ŷ = 2.2x + 0.4.

4. Predictions: 2.6, 4.8, 7.0, 9.2, 11.4.
Residuals: +0.4, +0.2, −1.0, −0.2, +0.6. Sum = 0.0. ✓

5. RSS = 0.16 + 0.04 + 1.00 + 0.04 + 0.36 = 1.60.
MSE = 1.60 / 5 = 0.32. RMSE = √0.32 ≈ 0.566.
TSS = (−4)² + (−2)² + (−1)² + 2² + 5² = 16 + 4 + 1 + 4 + 25 = 50.
R² = 1 − 1.60/50 = 0.968.

Exercise 3 — Verification by properties

Using your answer to Exercise 2, verify each of the four least-squares properties numerically:

  1. Σ ei = 0
  2. Σ xi ei = 0
  3. The fitted line passes through (x̄, ȳ)
  4. Σ ŷi = Σ yi
Show answers

1. 0.4 + 0.2 − 1.0 − 0.2 + 0.6 = 0.0 ✓

2. 1(0.4) + 2(0.2) + 3(−1.0) + 4(−0.2) + 5(0.6)
= 0.4 + 0.4 − 3.0 − 0.8 + 3.0 = 0.0 ✓

3. At x = 3: ŷ = 2.2(3) + 0.4 = 7.0 = ȳ ✓

4. Σŷi = 2.6 + 4.8 + 7.0 + 9.2 + 11.4 = 35.0 = Σyi ✓

Exercise 4 — Matrix form

Write out the design matrix X and the target vector y for the data in Exercise 2, then compute XᵀX and Xᵀy by hand.

  1. Confirm that XᵀX contains n, Σxi and Σxi².
  2. Confirm that Xᵀy contains Σyi and Σxiyi.
  3. Solve the 2×2 system by hand and verify that you recover ŵ = 2.2 and b̂ = 0.4.
Show answers
      ⎡ 1  1 ⎤        ⎡  3 ⎤
      ⎢ 1  2 ⎥        ⎢  5 ⎥
X  =  ⎢ 1  3 ⎥ ,  y = ⎢  6 ⎥
      ⎢ 1  4 ⎥        ⎢  9 ⎥
      ⎣ 1  5 ⎦        ⎣ 12 ⎦

              ⎡ n     Σxᵢ  ⎤   ⎡  5  15 ⎤
XᵀX  =        ⎢            ⎥ = ⎢        ⎥
              ⎣ Σxᵢ  Σxᵢ²  ⎦   ⎣ 15  55 ⎦

              ⎡  Σyᵢ  ⎤   ⎡ 35 ⎤
Xᵀy  =        ⎢       ⎥ = ⎢    ⎥
              ⎣ Σxᵢyᵢ ⎦   ⎣127 ⎦

3. The normal equations XᵀXŵ = Xᵀy give:

5b  +  15w  =  35
15b +  55w  =  127

From the first: b = 7 − 3w. Substituting into the second: 15(7 − 3w) + 55w = 127 → 105 − 45w + 55w = 127 → 10w = 22 → w = 2.2. Then b = 7 − 6.6 = 0.4. ✓

Notice that this is exactly the same system as the two scalar normal equations from Section 3.5 — the matrix form is simply a compact way of writing them.

Exercise 5 — Reasoning about sensitivity

Consider a dataset with 20 points fitted by least squares. Without computing anything, predict what happens to the slope and intercept in each case, and explain your reasoning in one or two sentences.

  1. You add one point that lies exactly on the current fitted line.
  2. You add one point that lies very far above the current fitted line.
  3. You multiply every yi by 3.
  4. You multiply every xi by 3.
  5. You add 100 to every xi.
Show answers
  1. Both barely change. A point on the line has zero residual, so it contributes nothing to RSS. But it does shift x̄ and ȳ, so the intercept moves very slightly. The slope is essentially unchanged.
  2. The line swings upward toward the point. The squared residual for that point is enormous relative to all others, so reducing it dominates the objective. The slope increases and the intercept may move in either direction. This is the outlier sensitivity of least squares.
  3. The slope and intercept both triple. Because the model is linear in y, scaling the target scales every fitted coefficient by the same factor. Predictions triple as well.
  4. The slope divides by 3; the intercept is unchanged; predictions are unchanged. This is the unit-change effect from the interactive activity. Rescaling a feature is compensated exactly by rescaling its coefficient.
  5. The slope is unchanged; the intercept decreases by 100 × slope. Shifting every x by a constant does not change how y responds to x, only where the origin sits. The fitted line is the same line in space. This is why centring features — subtracting the mean — can make coefficients easier to interpret without changing the model.

9 Problem set

These problems are longer and more open-ended. They feed directly into Assignment 2.

Problem 1 — Derive, don't look up

Without consulting the notes, derive the least-squares solution for the model ŷ = w₁x₁ + w₂x₂ + b with two features.

  1. Write the RSS as a function of w₁, w₂ and b.
  2. Take all three partial derivatives and set them to zero.
  3. Write the resulting three equations in matrix form.
  4. Identify the entries of XᵀX in terms of Σx₁ᵢ, Σx₂ᵢ, Σx₁ᵢ², Σx₂ᵢ² and Σx₁ᵢx₂ᵢ.
  5. What has to be true about the relationship between x₁ and x₂ for the system to be singular?

You do not need to solve the system. The purpose is to see how the two-feature case generalises the one-feature case you derived in Section 3.5, and to see the condition for non-invertibility emerge naturally from the algebra.

Problem 2 — Empirical verification on real data

Load the California Housing dataset:

from sklearn.datasets import fetch_california_housing
data = fetch_california_housing(as_frame=True)
df = data.frame

Choose a single feature that you expect to be informative for the target.

  1. Fit a simple linear regression using only that feature.
  2. Compute ŵ and b̂ two ways: with LinearRegression, and from scratch using Sxy/Sxx. Confirm that they agree.
  3. Verify all four least-squares properties numerically.
  4. Compute RSS, RMSE and R².
  5. Plot the residuals against the feature. Is there a visible pattern? If so, what does it suggest about the linear assumption?

Part 5 is the important one. On real data, the residuals will not look like random noise, and the pattern you see is the model telling you what it is missing.

Problem 3 — Robustness study

Using the bike-share data from the worked example, conduct a small experiment on the influence of a single point.

  1. Fit the model to the original eight points and record the slope and RMSE.
  2. For each of the following added observations, re-fit and record the new slope: (20 °C, 400), (20 °C, 600), (20 °C, 1,000), (20 °C, 2,000).
  3. Plot the slope as a function of the added y value. What shape is the curve?
  4. Repeat the whole experiment using least absolute deviations instead of least squares. In Python, this is available as sklearn.linear_model.QuantileRegressor(quantile=0.5).
  5. Compare the two curves. How much does the least-squares slope move for the most extreme outlier, versus the least-absolute-deviations slope?
  6. Write a short paragraph on when you would choose each method in practice.

Problem 4 — The geometry, made concrete

Take the data from Exercise 2: x = [1, 2, 3, 4, 5], y = [3, 5, 6, 9, 12].

  1. Write down the design matrix X (with the column of ones) and the target vector y. These live in ℝ⁵.
  2. Compute the fitted vector ŷ = Xŵ and the residual vector e = y − ŷ.
  3. Verify that e is orthogonal to both columns of X by Computing the two dot products. They should both be zero.
  4. Compute ‖e‖² and confirm that it equals the RSS you calculated in Exercise 2.
  5. Compute the cosine of the angle between y and ŷ. What does this tell you about how close the target is to the model's reachable subspace?
  6. Explain in one paragraph why the fitted vector must be the closest point in the column space to y, and what would happen to ‖e‖ if you chose any other point in that subspace.

10 Discussion and projects

Discussion prompt — post 150–250 words

Least squares is not neutral. It encodes a decision about whose errors matter most.

Because RSS grows with the square of the residual, a model fitted by least squares will sacrifice accuracy on many ordinary points in order to reduce error on a single extreme one. Describe a real-world prediction context — hiring, lending, healthcare triage, insurance pricing — where this property would produce a model you would consider unfair or unsafe. Be specific about which observations would dominate the fit, and who would bear the cost of the resulting errors.

Then answer: is there an alternative fitting criterion you would prefer in that setting, and what would you give up by adopting it?

Mini-project — two criteria, one dataset

Choose a small regression dataset — 50 to 500 rows, two or three features. Fit it twice: once with least squares and once with least absolute deviations.

  1. Report the coefficients from both fits side by side.
  2. Identify the three points with the largest squared residuals under the least-squares fit. Where do they sit relative to the least-absolute-deviations line?
  3. Plot both fitted lines on the same axes. Where do they diverge, and what is happening at those locations in the data?
  4. Compute the mean absolute error for both models. Does the model that minimises squared error also minimise absolute error? Explain why or why not.
  5. Write a 200-word recommendation: for this dataset, which criterion would you report, and why?

This is a compact version of a real model-selection decision. The point is not that one criterion is correct — it is that the choice is a modelling decision with consequences, and you should be able to defend it.

11 Summary

What you should take away

  • The residual is ei = yi − ŷi: the vertical distance from a point to the fitted line. Positive means the model predicted too low.
  • The residual sum of squares RSS(w, b) = Σ(yi − wxi − b)² is the criterion. Least squares chooses the parameters that minimise it.
  • We square because the result is differentiable, has a closed-form solution, and coincides with maximum likelihood under Gaussian noise.
  • For simple linear regression: ŵ = Sxy/Sxx and b̂ = ȳ − ŵx̄.
  • In general: ŵ = (XᵀX)⁻¹Xᵀy. This requires XᵀX to be invertible, which fails under perfect collinearity or when d ≥ n.
  • Every least-squares fit satisfies four properties: residuals sum to zero, residuals are orthogonal to the features, the line passes through the centroid, and the mean prediction equals the mean target.
  • Geometrically, least squares is the orthogonal projection of the target vector onto the column space of the design matrix.
  • The main weakness is outlier sensitivity, because influence grows with the square of the residual.

Key terms

Residual
The difference between an observed value and its fitted value: ei = yi − ŷi.
Residual sum of squares (RSS)
The sum of the squared residuals across all training examples. The quantity least squares minimises.
Least squares
The fitting principle that chooses parameters to minimise the sum of squared residuals.
Least absolute deviations
An alternative criterion that minimises the sum of absolute residuals. More robust to outliers, but has no closed-form solution.
Sum of cross-products (Sxy)
Σxiyi − n x̄ ȳ. Measures how much the feature and target vary together.
Sum of squared deviations (Sxx)
Σxi² − n x̄². Measures the spread of the feature values.
Normal equations
The system XᵀXw = Xᵀy obtained by setting the gradient of RSS to zero. Their solution is the least-squares estimate.
Design matrix (X)
The n × (d+1) matrix of feature values, with a leading column of ones to absorb the intercept.
Centroid
The point (x̄, ȳ). Every least-squares line with an intercept passes exactly through it.
Orthogonal projection
The closest point in a subspace to a given vector, characterised by the residual being perpendicular to the subspace.
Collinearity
A situation in which one feature is an exact or near-exact linear combination of others, making XᵀX singular or ill-conditioned.

You are ready for Tutorial 4 when…

  • You can write the RSS expression from memory and explain each term.
  • You can derive ŵ = Sxy/Sxx on paper without notes.
  • You can compute a simple least-squares fit by hand from a small table of data.
  • You can state all four properties of a least-squares fit and say where each comes from.
  • You can explain in one paragraph why least squares is a projection.

12 Further reading

James, Witten, Hastie & Tibshirani — An Introduction to Statistical Learning, ch. 3 free online Section 3.1 covers simple linear regression with essentially the same derivation. Section 3.2 extends it to multiple features and introduces the matrix formulation. The book's treatment of the standard errors and significance tests around the coefficients goes beyond this course but is worth skimming.
Hastie, Tibshirani & Friedman — The Elements of Statistical Learning, §3.2 free online A concise, more geometric treatment of least squares, including the projection interpretation used in Section 3.8 of this tutorial. Read it after you are comfortable with the algebra; it will make the geometry click.
Strang, Linear Algebra and Its Applications — chapters on orthogonal projection textbook If the projection picture in Section 3.8 felt unfamiliar, any good linear algebra text will fill in the background. The four fundamental subspaces and the projection formula are the prerequisites for really understanding why the normal equations take the form they do.
Stigler — "The History of Statistics" history The chapters on Legendre, Gauss and the discovery of Ceres tell the story behind least squares. Optional, but it makes the method considerably more memorable to know it was invented to find an asteroid.
scikit-learn — Linear Models user guide reference The LinearRegression documentation, including the note on why scikit-learn uses a decomposition rather than forming (XᵀX)⁻¹ explicitly. Short and directly relevant to the code in this tutorial.
Rousseeuw & Leroy — Robust Regression and Outlier Detection advanced The standard reference on what to do when least squares is the wrong criterion. Read the first chapter for the motivation; the rest is beyond this course but useful to know exists.
Belsley, Kuh & Welsch — Regression Diagnostics advanced The classic text on detecting the problems — outliers, influential points, collinearity — that this tutorial warned about. Tutorial 6 covers the practical essentials; this is where to go if you want the full treatment.

What to read next

If you read one thing from this list before Tutorial 4, read Section 3.1 of An Introduction to Statistical Learning. It presents the same derivation with a slightly different emphasis and includes the standard-error formulas, which give you a sense of how much confidence to place in each coefficient. That material sits just outside this course's scope, but knowing it exists is useful.

👤