Notes
All notes

Deriving Linear Regression (ML #1)

You fit a model to predict house prices and get coefficients that flip sign when you add one more column. Your R² looks fine, your residual plot looks fine, and yet the thing is quietly broken. Nobody taught you why — most courses hand you the formula \(w = (X^\top X)^{-1} X^\top y\) and move on.

The formula is not the interesting part. The interesting part is that it falls out of two lines of calculus, and once you’ve seen where it comes from, every practical question — why scale your features, why ridge exists, why \(X^\top X\) being singular means your columns are redundant — becomes obvious rather than memorized.

This chapter derives least squares from its objective function. By the end you will have derived the normal equation yourself, implemented gradient descent, and learned to predict which of three practical failure modes a dataset is about to spring on you.

Start from the objective, not the answer

Setup: \(n\) houses, each with features \(x_i \in \mathbb{R}^d\) and a price \(y_i \in \mathbb{R}\). We want a linear predictor

\[ \hat{y} = w^\top x + b = \theta^\top \tilde{x} \]

where \(\tilde{x} = [x, 1] \in \mathbb{R}^{d+1}\) absorbs the intercept into the weight vector \(\theta\). Stacking rows of \(\tilde{X} \in \mathbb{R}^{n \times (d+1)}\) and \(y \in \mathbb{R}^n\), the prediction for every house at once is \(\hat{y} = \tilde{X}\theta\). No loop, no for-each — matrix multiply.

Why squared error? Three reasons, and the third is the one that bites. Squared error punishes large misses hard, which is what you want when the target is noisy; it is differentiable everywhere except at zero; and crucially it makes the problem convex — the loss has a single global minimum, so local optimization reaches the global one. Least squares isn’t the “true” error model for most problems (Chapter 13 shows where it lies); it’s the one whose loss surface is bowl-shaped.

Define the mean squared error as the objective:

\[ L(\theta) = \frac{1}{n} \sum_{i=1}^{n} \left( y_i - \theta^\top \tilde{x}_i \right)^2 = \frac{1}{n} \| y - \tilde{X}\theta \|_2^2 \]

This is a quadratic in \(\theta\). Find its minimum by setting the gradient to zero.

The derivation, four lines

Expand the matrix form and differentiate term by term. Using that a scalar equals its own transpose, \(\frac{d}{d\theta}\theta^\top A\theta = (A + A^\top)\theta = 2A\theta\) for symmetric \(A\):

\[ \nabla_\theta L = \frac{2}{n} \left( \tilde{X}^\top \tilde{X}\theta - \tilde{X}^\top y \right) \]

Set it to zero, multiply by \(\frac{n}{2}\), and solve:

\[ \tilde{X}^\top \tilde{X}\theta = \tilde{X}^\top y \;\Longrightarrow\; \theta^* = (\tilde{X}^\top \tilde{X})^{-1} \tilde{X}^\top y \]

That’s the normal equation, derived. Two facts fall out of the same two lines, and both matter in practice.

Fact one — the solution is a projection. Write \(\theta^* = \tilde{X}^+ y\) where \(\tilde{X}^+ = (\tilde{X}^\top \tilde{X})^{-1}\tilde{X}^\top\) is the pseudo-inverse. Least squares projects \(y\) onto the column space of \(\tilde{X}\). Geometrically: among all predictions \(\tilde{X}\theta\) that could ever be produced, pick the one closest to \(y\) in Euclidean distance. That picture is why adding features can only help the fit — you’re projecting onto a larger subspace, and a larger subspace is closer.

Fact two — the inverse may not exist. The step from \(\tilde{X}^\top\tilde{X}\theta = \tilde{X}^\top y\) to the inverse requires \(\tilde{X}^\top\tilde{X}\) to be invertible, which holds exactly when the columns of \(\tilde{X}\) are linearly independent. Two features that are exact duplicates, or “price” and “price in dollars”, make it singular: infinitely many \(\theta\) give the same predictions, so \(\theta^*\) is not unique — the predictions are unique even though the coefficients aren’t. Practical consequence: never compute the inverse explicitly. Form the system and solve it.

import numpy as np

def normal_equation(X, y):
    """Least squares via the normal equation — for understanding, not production."""
    n = X.shape[0]
    Xb = np.c_[X, np.ones(n)]                          # augment with intercept column
    theta = np.linalg.solve(Xb.T @ Xb, Xb.T @ y)      # solve; never invert
    return theta[:-1], theta[-1]

rng = np.random.default_rng(0)
X = rng.normal(size=(60, 3))
y = X @ np.array([2.0, -1.0, 0.5]) + rng.normal(scale=0.1, size=60)

w, b = normal_equation(X, y)
print(np.round(w, 6), round(b, 6))        # ≈ [2. -1. 0.5]
print("residual loss:", np.mean((y - (X @ w + b)) ** 2))

np.linalg.solve uses LU factorization rather than an explicit inverse, so it is both faster and numerically stabler. Verified: at this solution the gradient \(\frac{2}{n}\tilde{X}^\top(\tilde{X}\theta - y)\) is zero to machine precision.

Gradient descent: the same optimum, iteratively

The normal equation needs \(\tilde{X}^\top\tilde{X}\), an \(O(nd^2)\) cost plus a \(d \times d\) solve. When \(d > n\) it is strictly better to never form \(\tilde{X}^\top\tilde{X}\) at all. The gradient we already derived is all gradient descent needs:

\[ \theta \leftarrow \theta - \eta \frac{2}{n} \tilde{X}^\top (\tilde{X}\theta - y) \]

One matrix–vector product per step. The step size \(\eta\) is not free: the Hessian is \(\frac{2}{n}\tilde{X}^\top\tilde{X}\) with largest eigenvalue \(\lambda_{\max}\), and gradient descent diverges when \(\eta > 2/\lambda_{\max}\). On a standardized dataset with \(d\) features \(\lambda_{\max} \approx 2d/n\), so a safe step is \(\eta \lesssim n/d\) — which is why the standard trick is to scale by \(\frac{1}{\lambda_{\max}}\) (Adam’s second moment, Chapter 4).

def gradient_descent(X, y, iters=3000):
    n, d = X.shape
    Xb = np.c_[X, np.ones(n)]
    theta = np.zeros(d + 1)
    H = (2.0 / n) * Xb.T @ Xb
    eta = 0.5 / np.linalg.eigvalsh(H).max()   # provably stable
    for _ in range(iters):
        theta -= eta * ((2.0 / n) * Xb.T @ (Xb @ theta - y))
    return theta[:-1], theta[-1]

w2, b2 = gradient_descent(X, y)
print(np.allclose(np.r_[w2, b2], np.r_[w, b], atol=1e-6))   # True

The stable bound is exactly \(\eta < 2/\lambda_{\max}\), and the run confirms both halves of that claim: at \(\eta = 0.5/\lambda_{\max}\), and even \(1.8/\lambda_{\max}\), the loss converges to \(10^{-10}\); at \(6/\lambda_{\max}\) it overflows to nan.

quantity meaning consequence
\(\theta^*\) fitted coefficients unique only if \(\tilde{X}^\top\tilde{X}\) is invertible
\(\tilde{X}^+ y\) the projection of \(y\) unique always, even when \(\theta^*\) is not
\(\lambda_{\max}(\tilde{X}^\top\tilde{X})\) stiffest direction bounds the stable step: \(\eta < 2/\lambda_{\max}\)
\(\lambda_{\min}\) softest direction sets iterations to converge: \(\sim(1-\eta\lambda_{\min})^{-t}\)
\(\kappa = \lambda_{\max}/\lambda_{\min}\) conditioning the practical reason GD is slow on raw features

Failure mode one: scale

Squared error penalizes weights, and a feature measured in thousands (square feet) needs a much smaller weight than one measured in ones (bedrooms). The level sets of \(L\) are ellipses, and unequal feature scales stretch them into a thin diagonal:

\begin{tikzpicture}[font=\rmfamily, >=stealth]
  \fill[blue!12] (0,0) -- (4.2,0) -- (4.2,3) -- (0,3) -- cycle;
  \draw[->, thick] (4.2,0) -- (5,0) node[right, font=\rmfamily\scriptsize] {$w_1$};
  \draw[->, thick] (0,3) -- (0,3.7) node[above, font=\rmfamily\scriptsize] {$w_2$};
  \foreach \s in {0.5,1.0,1.5,2.0,2.5}
    \draw[red, thick] (0.3,{\s*1.05+0.2}) parabola bend ({2.1+\s*0.35},{\s*1.05+0.75});
  \draw[->, dashed, green!45!black] (2.1,1.25) -- (3.3,2.05);
  \node[font=\rmfamily\scriptsize, text=red!70!black] at (1.5,0.65) {contours: thin ellipse};
  \node[font=\rmfamily\scriptsize, text=green!45!black] at (3.75,1.6) {GD zigzags\\along thin axis};
  \node[font=\rmfamily\scriptsize, text=black!60] at (2.1,-0.42) {unstandardized features};
\end{tikzpicture}

Mathematically, the condition number \(\kappa = \lambda_{\max}/\lambda_{\min}\) of \(\tilde{X}^\top\tilde{X}\) is large, and convergence rate degrades with \(\kappa\). Standardizing columns to zero mean and unit variance fixes it, at the cost of interpretability — you must un-standardize coefficients to report them in original units.

Failure mode two: collinearity

Perfectly correlated features make \(\lambda_{\min} \to 0\), so the ellipse becomes infinitely thin: the objective is nearly flat along an entire line of equivalent \(\theta\). Coefficients become unstable — add an irrelevant column and a relevant one flips sign — while predictions barely change. This is not a numerical accident to be patched; it is a genuine statement that the data cannot separate those two effects. Chapter 2 derives exactly how much.

Failure mode three: extrapolation

Least squares is linear in \(\theta\), and the fit is only meaningful inside the data’s convex hull. The model happily extrapolates a negative price for a house twice the largest one ever sold. No amount of algebra fixes this; only features that are physically bounded (log price, price per square foot) or a different model class do.

sqft = np.array([800, 1000, 1200, 1500, 1800], dtype=float)
price = 50 * sqft + 30_000 + rng.normal(scale=5_000, size=5)
Xb = np.c_[sqft[:, None], np.ones(len(sqft))]
th = np.linalg.solve(Xb.T @ Xb, Xb.T @ price)      # [slope, intercept]

resid = price - Xb @ th
print("in-sample R2:", round(1 - resid.var() / price.var(), 4))
print("price at 10,000 sqft:", round(float(10_000 * th[0] + th[1])))

R² = 0.9902, and the model cheerfully predicts $507,662 for a 10,000 sqft house. Nothing in the algebra objects: the extrapolation is a straight line because \(\theta\) is a straight line.

Reading coefficients back after standardizing

One consequence of standardization deserves its own note, because the error it causes is invisible in the output. If features are scaled to unit variance, the fitted weights are not in original units. To report a raw-unit effect, divide by the feature’s standard deviation:

\[ w_j^{\text{raw}} = \frac{w_j^{\text{standardized}}}{\sigma_j} \]

A weight of 0.03 on a standardized feature might mean $3,000 per unit or $0.03 per unit depending entirely on \(\sigma_j\). Reporting standardized coefficients in raw units is one of the most common mistakes in applied linear modeling. Chapter 2 adds the second subtlety: a penalized coefficient isn’t just rescaled, it’s been shrunk, and non-uniformly across features — yet another reason to standardize before penalizing.

mu, sd = X.mean(0), X.std(0)
w_s, b_s = gradient_descent((X - mu) / sd, y)
print("raw-unit coefficients:", np.round(w_s / sd, 4))   # ≈ [2, -1, 0.5]

Pitfalls

QQuestionSelf-check

Derive \(\nabla_\theta L\) from \(L(\theta) = \frac{1}{n}\|y - \tilde{X}\theta\|^2\) and show the normal equation follows. Why does gradient descent diverge when \(\eta > 2/\lambda_{\max}\)? Your model’s \(R^2\) jumps when you add a feature but out-of-sample error rises — what is happening, and why does the derivation predict it?

ASolution

Expanding \(\|y - \tilde{X}\theta\|^2 = y^\top y - 2y^\top\tilde{X}\theta + \theta^\top\tilde{X}^\top\tilde{X}\theta\) and using \(\frac{d}{d\theta}\theta^\top A\theta = 2A\theta\) for symmetric \(A\) gives \(\nabla_\theta L = \frac{2}{n}(\tilde{X}^\top\tilde{X}\theta - \tilde{X}^\top y)\); setting it to zero yields \(\theta^* = (\tilde{X}^\top\tilde{X})^{-1}\tilde{X}^\top y\). Divergence past \(2/\lambda_{\max}\) follows because the error is a quadratic with Hessian \(\frac{2}{n}\tilde{X}^\top\tilde{X}\): each step scales the error component along eigendirection \(i\) by \((1 - \eta\lambda_i)\), and any \(\lambda_i\) with \(\eta\lambda_i > 2\) makes that component oscillate and grow. On the added feature: in-sample fit improved because adding a column enlarges the projection subspace, so \(\|y - \tilde{X}\theta\|\) can only shrink — least squares must use every column it is given, with no mechanism to decline one. Chapter 13’s decomposition names the cost: variance rose as the model absorbed noise, and it outgrew the bias it removed.

Next: Deriving Regularization (ML #2) — adding a penalty to the objective, and why L1 zeroes coefficients while L2 only shrinks them.