Linear regression from scratch¶
Fit a weighted sum of the inputs to a target by minimising squared error. It is the oldest learning algorithm still in daily use, and it contains in miniature almost everything the rest of machine learning does: a model, a loss, a solver, a geometry and a probabilistic story that all agree.
10,000 ft
Linear regression is where learning from data began: Legendre and Gauss used least squares to fit planetary and comet orbits two centuries before anyone said "machine learning". It is still the right first model for any numeric target, the baseline every fancier model must beat, and the last layer of almost every neural network: a transformer's final step is a linear map from a hidden vector to a score per token. Its ideas recur everywhere: logistic regression bends the same weighted sum through a sigmoid; regularisation adds a penalty to the same loss; kernels and neural networks replace the raw inputs with learned or implicit features and then do linear regression on top. If you understand this page completely (the projection picture, the normal equations, the Gaussian likelihood and why gradient descent crawls on badly scaled features) you have the core vocabulary of the whole field.
2,000 ft
You have \(n\) examples, each a row of \(d\) numbers \(\mathbf{x}_i\) with a target \(y_i\). The model predicts \(\hat y_i = \mathbf{w}^\top \mathbf{x}_i + b\). You choose \(\mathbf{w}, b\) to minimise the mean squared residual. Because the loss is a convex quadratic in the weights, there is one bowl-shaped valley with a single bottom, and you can find it two ways: solve the normal equations \(X^\top X \mathbf{w} = X^\top \mathbf{y}\) directly, or walk downhill with gradient descent. Geometrically the answer is the orthogonal projection of the target vector onto the space spanned by the feature columns; statistically it is the maximum-likelihood estimate if the noise is Gaussian.
Ground level¶
The setup¶
Every supervised learning problem on this site has the same four parts, and linear regression is the cleanest place to see them:
- Data. A design matrix \(X \in \mathbb{R}^{n \times d}\) (one row per example, one column per feature) and a target vector \(\mathbf{y} \in \mathbb{R}^{n}\). A house-price dataset might have rows for houses and columns for floor area, bedrooms and distance to the station.
- Model (hypothesis class). All functions of the form \(f(\mathbf{x}) = \mathbf{w}^\top\mathbf{x} + b\). Choosing this family is the inductive bias: you are betting that the target changes at a constant rate along each feature.
- Loss. The squared error \((y - \hat y)^2\), averaged over the training set: the mean squared error (MSE).
- Optimiser. Something that finds the \(\mathbf{w}, b\) with the smallest loss.
A standard trick removes the separate bias: prepend a column of ones to \(X\) so that \(b\) becomes weight \(w_0\). From here on \(X\) includes that column, has \(d+1\) columns, and the model is simply \(\hat{\mathbf{y}} = X\mathbf{w}\).
A worked example you can do by hand¶
Five points: \(x = (1, 2, 3, 4, 5)\) and \(y = (2, 3, 5, 4, 6)\). With one feature, the least-squares line has a closed form that is worth memorising:
Here \(\bar x = 3\), \(\bar y = 4\). The deviations are \(x - \bar x = (-2,-1,0,1,2)\) and \(y - \bar y = (-2,-1,1,0,2)\), so the numerator is \(4 + 1 + 0 + 0 + 4 = 9\) and the denominator is \(4+1+0+1+4 = 10\). The slope is \(0.9\) and the intercept is \(4 - 0.9 \times 3 = 1.3\):
The predictions are \((2.2, 3.1, 4.0, 4.9, 5.8)\) and the residuals \(y - \hat y\) are \((-0.2, -0.1, 1.0, -0.9, 0.2)\). Two facts you can check on the spot: the residuals sum to zero (the intercept guarantees it), and \(\sum_i r_i x_i = -0.2 - 0.2 + 3.0 - 3.6 + 1.0 = 0\) (the slope guarantees it). Those two zeros are the normal equations, as we will see.
The sum of squared residuals is \(0.04 + 0.01 + 1 + 0.81 + 0.04 = 1.9\). The total variation of \(y\) around its mean is \(\sum (y-\bar y)^2 = 10\). So the line explains \(1 - 1.9/10 = 0.81\) of the variance: \(R^2 = 0.81\).
Three ways to find the weights¶
1. Solve the normal equations. In matrix form the same example has
\(\det(X^\top X) = 275 - 225 = 50\), so
Same line. This costs \(O(nd^2)\) to form \(X^\top X\) and \(O(d^3)\) to solve, which is instant for thousands of features and millions of rows.
2. A numerically careful direct solve (QR or SVD). Forming \(X^\top X\) squares the condition number of the problem (more in The maths), so libraries factor \(X\) itself instead: np.linalg.lstsq uses the SVD, R's lm uses QR. Same answer in exact arithmetic, far fewer lost digits in floating point. Use this in real code.
3. Gradient descent. Start anywhere and step against the gradient of the loss \(L(\mathbf{w}) = \tfrac{1}{2n}\lVert X\mathbf{w}-\mathbf{y}\rVert^2\):
From \(\mathbf{w}=\mathbf{0}\) on the toy data the residuals are just \(-\mathbf{y}\), so \(\nabla L = \tfrac15(-20, -69) = (-4, -13.8)\); one step with \(\eta = 0.05\) lands at \((0.2, 0.69)\). Nobody needs gradient descent for a five-point line, but it is the only option once the model is not linear in its parameters (every neural network), or when \(n\) is too large to touch every row per step (use stochastic gradient descent: the same update on a random mini-batch). Linear regression is where you can watch it work against a known answer.
Why gradient descent crawls on unscaled features¶
On the toy data, gradient descent with step size \(1/\lambda_{\max}\) (half the largest stable step) takes 835 steps to get the gradient below \(10^{-6}\). Subtract the mean from \(x\) first (centre it) and the same algorithm takes 22 steps. Nothing about the problem changed except the coordinates.
The reason is the shape of the bowl. The loss is a quadratic whose curvature is the matrix \(H = \tfrac1n X^\top X\). For the raw toy data \(H = \begin{pmatrix}1 & 3\\ 3 & 11\end{pmatrix}\) with eigenvalues \(11.83\) and \(0.169\): the valley is 70 times steeper in one direction than the other (the condition number \(\kappa = 70\)). The step size must be small enough not to overshoot across the steep direction (\(\eta < 2/11.83 = 0.169\)), and at that step the shallow direction barely moves. After centring, \(H = \begin{pmatrix}1 & 0\\0 & 2\end{pmatrix}\), \(\kappa = 2\), and the bowl is nearly round. Every practical rule about standardising features (subtract the mean, divide by the standard deviation) comes from this picture, and so do the adaptive optimisers like Adam, which in effect rescale each coordinate on the fly. Play with the step size and the stretched bowl here:
Reading the coefficients¶
\(\hat w_j\) is the change in the prediction when feature \(j\) rises by one unit with every other feature held fixed. That last clause matters more than it looks:
- Units. A weight of \(0.03\) on a feature measured in rupees and \(30\) on the same feature in thousands of rupees are the same model. Compare magnitudes only after standardising.
- Collinearity. If two features nearly duplicate each other (floor area in square feet and in square metres, or "age" and "years since graduation"), the data cannot say how to split the effect between them. \(X^\top X\) is nearly singular, the weights can be huge with opposite signs, and they swing wildly between resamples while the predictions stay fine. Ridge regression fixes this.
- Association, not causation. A positive weight on "number of fire engines sent" for predicting fire damage does not mean fire engines cause damage. Regression describes the joint distribution you sampled; intervening on a feature is a different question (the subject of causal inference).
- Omitted variables. Leave out a feature correlated with both an included feature and the target, and the included feature's weight absorbs part of the missing one's effect.
Linear in the parameters, not in the inputs¶
"Linear" regression means linear in \(\mathbf{w}\). You may transform the inputs however you like, \(\phi(\mathbf{x}) = (1, x, x^2, x^3)\), or \(\log x\), or \(\sin(2\pi x/24)\) for an hour of the day, and the solver is unchanged: build a new design matrix \(\Phi\) with those columns and solve least squares on it. This basis expansion is how a straight-line method fits curves, and it is the bridge to everything that follows: polynomial degree is the classic bias-variance dial; kernel methods use infinitely many basis functions implicitly; a neural network learns its basis functions and then does linear regression (or classification) on the last layer.
What \(R^2\) does and does not tell you¶
\(R^2 = 1 - \text{SSE}/\text{SST}\) is the fraction of the target's variance around its mean that the model removes. \(R^2 = 0\) means "no better than predicting \(\bar y\)"; on held-out data it can be negative. It always rises (weakly) when you add a feature to the training fit, even a column of noise, so a high training \(R^2\) proves nothing about generalisation; judge on a held-out set. It also says nothing about whether the relationship is linear: Anscombe's quartet is four datasets with essentially the same \(R^2\), slope and intercept that look completely different when plotted. Always plot the residuals against the predictions; any visible structure (a curve, a funnel) is signal the model missed.
History¶
From comets to genes
Adrien-Marie Legendre published the method of least squares in 1805, in an appendix to a book on the orbits of comets. Carl Friedrich Gauss published his version in 1809 and claimed he had used it since 1795; in 1801 he had used it to predict where the newly discovered dwarf planet Ceres would reappear from behind the Sun, and astronomers found it there. Gauss also supplied the probabilistic justification: least squares is what you get if errors are normally distributed (he derived the normal distribution partly to make this argument). Stephen Stigler's 1981 paper untangles the priority dispute.
The word regression came later and from biology. Francis Galton (1886) regressed children's heights on their parents' and found that the children of unusually tall parents were, on average, less extreme: "regression towards mediocrity". That is not a biological force but a statistical inevitability whenever the correlation is less than one, and it is still a trap in A/B tests and performance reviews (the best performers this quarter will, on average, look worse next quarter).
First principles¶
Why squared error, of all the ways to score a miss? Three independent arguments land on the same answer, which is why least squares has lasted.
It predicts the conditional mean. For any random variable \(Y\), the constant \(c\) that minimises \(\mathbb{E}[(Y-c)^2]\) is \(c = \mathbb{E}[Y]\) (differentiate: \(-2\,\mathbb{E}[Y - c] = 0\)). So a model trained on squared error is trying to output \(\mathbb{E}[y \mid \mathbf{x}]\), the average outcome for inputs like these. Absolute error instead targets the median, which is why it is robust to outliers; pinball loss targets other quantiles. Choosing a loss is choosing which summary of \(p(y\mid\mathbf{x})\) you want.
It is maximum likelihood under Gaussian noise. Assume \(y = \mathbf{w}^\top\mathbf{x} + \varepsilon\) with \(\varepsilon \sim \mathcal{N}(0, \sigma^2)\). The log-likelihood of the data is \(-\frac{1}{2\sigma^2}\sum_i (y_i - \mathbf{w}^\top\mathbf{x}_i)^2\) plus terms without \(\mathbf{w}\), so maximising likelihood is minimising squared error (derivation below). This is the template for the whole field: pick a noise model, take the negative log-likelihood, and that is your loss. A Bernoulli noise model gives logistic regression's cross-entropy; a categorical one gives the softmax cross-entropy that trains every language model (language modelling objective).
It is orthogonal projection. Think of \(\mathbf{y}\) as one point in \(\mathbb{R}^n\) (one axis per training example). Every possible prediction \(X\mathbf{w}\) lies in the column space of \(X\), a flat \((d{+}1)\)-dimensional subspace. Minimising \(\lVert \mathbf{y} - X\mathbf{w}\rVert\) asks for the point of that subspace nearest to \(\mathbf{y}\), which is the foot of the perpendicular. "The residual is perpendicular to every column" is exactly \(X^\top(\mathbf{y} - X\hat{\mathbf{w}}) = \mathbf{0}\): the normal equations, and the two zeros you checked by hand above.
What breaks if you change things. Replace squared error with absolute error and the projection picture and closed form vanish (you need linear programming or iterative methods), but you gain robustness: one corrupted label can drag a least-squares line arbitrarily far, while it moves a least-absolute-deviation line only so much. Huber loss is quadratic near zero and linear in the tails, a compromise used widely (and in deep RL as the "smooth L1" loss). Let \(d+1 > n\) and the plane has more dimensions than there are points to pin it: infinitely many weight vectors fit perfectly, and you must add a preference (the smallest-norm one, or a penalty) to choose; that regime is the doorway to double descent.
The maths¶
Notation. \(X \in \mathbb{R}^{n\times p}\) (here \(p = d+1\), including the ones column), \(\mathbf{y}\in\mathbb{R}^n\), \(\mathbf{w}\in\mathbb{R}^p\). Loss \(L(\mathbf{w}) = \lVert \mathbf{y} - X\mathbf{w}\rVert^2 = (\mathbf{y}-X\mathbf{w})^\top(\mathbf{y}-X\mathbf{w})\).
Gradient. Expand: \(L = \mathbf{y}^\top\mathbf{y} - 2\mathbf{w}^\top X^\top\mathbf{y} + \mathbf{w}^\top X^\top X\mathbf{w}\). Using \(\nabla_{\mathbf{w}}(\mathbf{a}^\top\mathbf{w}) = \mathbf{a}\) and \(\nabla_{\mathbf{w}}(\mathbf{w}^\top A\mathbf{w}) = 2A\mathbf{w}\) for symmetric \(A\):
Normal equations. Setting the gradient to zero:
The Hessian \(2X^\top X\) is positive semi-definite (\(\mathbf{v}^\top X^\top X\mathbf{v} = \lVert X\mathbf{v}\rVert^2 \ge 0\)), so \(L\) is convex and every solution of the normal equations is a global minimum. If \(X\) has full column rank (\(\operatorname{rank} X = p\), which needs \(n \ge p\) and no column a combination of others), \(X^\top X\) is positive definite and invertible, and the minimiser is unique: \(\hat{\mathbf{w}} = (X^\top X)^{-1}X^\top\mathbf{y}\).
Projection (hat) matrix. The fitted values are \(\hat{\mathbf{y}} = X(X^\top X)^{-1}X^\top\mathbf{y} = P\mathbf{y}\). \(P\) is symmetric and idempotent (\(P^2 = P\)): projecting twice changes nothing. Its trace is \(p\), the number of parameters, a fact that generalises to "effective degrees of freedom" for ridge regression. The residual is \((I-P)\mathbf{y}\), the projection onto the orthogonal complement.
Rank-deficient and wide problems. If \(X\) lacks full column rank, use the Moore–Penrose pseudoinverse: with the thin SVD \(X = U\Sigma V^\top\), \(X^+ = V\Sigma^{+}U^\top\) (invert the non-zero singular values, leave zeros as zeros). \(\hat{\mathbf{w}} = X^+\mathbf{y}\) is the least-squares solution with the smallest \(\lVert\mathbf{w}\rVert\). Gradient descent started from \(\mathbf{w}=\mathbf{0}\) converges to exactly this minimum-norm solution, because every gradient \(X^\top(\cdot)\) lies in the row space of \(X\), so the iterates never acquire a component in the null space. This "implicit regularisation" of gradient descent is one of the explanations offered for why huge, over-parameterised networks generalise.
Derivation: least squares is maximum likelihood under Gaussian noise
Model: \(y_i = \mathbf{w}^\top\mathbf{x}_i + \varepsilon_i\), with \(\varepsilon_i\) independent and \(\mathcal{N}(0,\sigma^2)\). Then \(p(y_i \mid \mathbf{x}_i, \mathbf{w}) = \frac{1}{\sqrt{2\pi\sigma^2}}\exp\!\left(-\frac{(y_i - \mathbf{w}^\top\mathbf{x}_i)^2}{2\sigma^2}\right)\).
By independence the log-likelihood is a sum:
The first term does not involve \(\mathbf{w}\) and \(\frac{1}{2\sigma^2} > 0\), so \(\arg\max_{\mathbf{w}}\) of the log-likelihood equals \(\arg\min_{\mathbf{w}}\sum_i (y_i - \mathbf{w}^\top\mathbf{x}_i)^2\). Maximising over \(\sigma^2\) as well (differentiate and set to zero) gives \(\hat\sigma^2_{\text{MLE}} = \frac{1}{n}\lVert\mathbf{y}-X\hat{\mathbf{w}}\rVert^2\), which is biased low; the unbiased estimate divides by \(n-p\), because the fit has used up \(p\) dimensions of the residual (the residual lives in an \((n-p)\)-dimensional subspace).
Swap the Gaussian for a Laplace distribution, \(p(\varepsilon)\propto e^{-|\varepsilon|/b}\), and the same steps give absolute-error regression. The loss is the noise model.
Sampling distribution. Under the model above with fixed \(X\), \(\hat{\mathbf{w}} = (X^\top X)^{-1}X^\top(X\mathbf{w}+\boldsymbol{\varepsilon}) = \mathbf{w} + (X^\top X)^{-1}X^\top\boldsymbol{\varepsilon}\). So \(\mathbb{E}[\hat{\mathbf{w}}] = \mathbf{w}\) (unbiased) and
Small eigenvalues of \(X^\top X\) (collinear features) mean huge variance along those directions: the formal version of "collinear weights swing wildly". Standard errors and confidence intervals for each \(w_j\) come from the diagonal of this matrix with \(\hat\sigma^2\) plugged in. The Gauss–Markov theorem says that, if the errors have mean zero, equal variance and no correlation (not necessarily Gaussian), no other linear unbiased estimator has smaller variance than OLS. The loophole is the word unbiased: accept a little bias and you can cut variance a lot, which is exactly what ridge regression does.
Gradient descent convergence. Write \(H = \frac1n X^\top X\) with eigenvalues \(\mu = \lambda_{\min} \le \dots \le \lambda_{\max} = L\). For the loss \(\frac{1}{2n}\lVert X\mathbf{w}-\mathbf{y}\rVert^2\), the error \(\mathbf{e}_t = \mathbf{w}_t - \hat{\mathbf{w}}\) obeys \(\mathbf{e}_{t+1} = (I - \eta H)\mathbf{e}_t\) exactly. In the eigenbasis each component is multiplied by \((1-\eta\lambda_i)\) per step. Stability needs \(|1 - \eta\lambda_i| < 1\) for all \(i\), i.e. \(\eta < 2/L\). With \(\eta = 1/L\) the slowest component shrinks by \(1 - \mu/L = 1 - 1/\kappa\) per step, so reaching accuracy \(\epsilon\) takes about \(\kappa\ln(1/\epsilon)\) steps. For the toy data, \(\kappa \approx 70\) versus \(2\) after centring: hundreds of steps versus tens, as measured.
Conditioning of the direct solve. \(\kappa(X^\top X) = \kappa(X)^2\). In double precision (about 16 significant digits) a problem with \(\kappa(X) = 10^{6}\) loses about 6 digits through QR or SVD on \(X\), but 12 through the normal equations. That is why lstsq exists.
Cost. Normal equations: \(O(np^2 + p^3)\). QR: \(O(np^2)\). One gradient step: \(O(np)\); one SGD step on a batch of \(B\): \(O(Bp)\).
In practice¶
- Start here. For any numeric target, fit a linear model on sensible features first. It takes seconds, its errors are interpretable, and if a gradient-boosted tree or network cannot beat it by a clear margin on validation data, you have learned something important.
- Use
np.linalg.lstsqor scikit-learn'sLinearRegression, nevernp.linalg.inv(X.T @ X). - Standardise for gradient-based or penalised fits. The closed-form OLS answer is invariant to scaling (the weights rescale to compensate), but gradient descent speed and every penalty (ridge, lasso) are not.
- Plot residuals. Against the prediction (curvature means a missing transform, a funnel means variance grows with the mean: model \(\log y\) or use weighted least squares), against time (autocorrelation), against each feature.
- Skewed positive targets such as prices and incomes usually fit better as \(\log y\); remember the model then predicts the geometric mean, and exponentiating a mean of logs underestimates the arithmetic mean.
- Heavy outliers: Huber regression (
sklearn.linear_model.HuberRegressor) or quantile regression. - Many correlated features or \(p\) close to \(n\): go straight to ridge.
Common misconceptions¶
Linear regression can only fit straight lines
It fits hyperplanes in whatever feature space you give it. With polynomial, spline, log or interaction features it fits curves and surfaces; it stays "linear" because the prediction is linear in the weights, which is what keeps the loss a convex quadratic.
A bigger weight means a more important feature
Only if the features share units and scale, and only in the presence of the other features. Standardise first, and for importance prefer held-out measures such as permutation importance (features).
Least squares assumes the data are Gaussian
The fit assumes nothing: it is a projection, defined for any data. Gaussian noise is what makes it the maximum-likelihood estimator and gives exact confidence intervals. Unbiasedness only needs zero-mean errors; Gauss–Markov optimality needs equal, uncorrelated variances.
Build it¶
NumPy only. Three solvers on the same synthetic problem with features on wildly different scales, plus checks of the orthogonality property and \(R^2\).
import numpy as np
rng = np.random.default_rng(0)
n, d = 200, 3
X_raw = rng.normal(size=(n, d)) * [1.0, 10.0, 100.0] # features on very different scales
w_true, b_true = np.array([2.0, -0.5, 0.03]), 4.0
y = X_raw @ w_true + b_true + rng.normal(scale=1.0, size=n)
X = np.column_stack([np.ones(n), X_raw]) # prepend the bias column
# 1. Normal equations (fine for small, well-conditioned problems)
w_normal = np.linalg.solve(X.T @ X, X.T @ y)
# 2. Least squares via SVD (what you should use in practice)
w_lstsq, *_ = np.linalg.lstsq(X, y, rcond=None)
# 3. Batch gradient descent on standardised features
mu, sd = X_raw.mean(0), X_raw.std(0)
Z = np.column_stack([np.ones(n), (X_raw - mu) / sd])
H = Z.T @ Z / n # Hessian of the MSE/2 loss
lr = 1.0 / np.linalg.eigvalsh(H).max() # safe step: 1/L
w = np.zeros(d + 1)
for step in range(500):
grad = Z.T @ (Z @ w - y) / n
w -= lr * grad
# map standardised weights back to raw units
w_gd = np.r_[w[0] - (w[1:] * mu / sd).sum(), w[1:] / sd]
resid = y - X @ w_lstsq
r2 = 1 - resid @ resid / ((y - y.mean()) @ (y - y.mean()))
np.set_printoptions(precision=4, suppress=True)
print("true ", np.r_[b_true, w_true])
print("normal eq ", w_normal)
print("lstsq ", w_lstsq)
print("grad desc ", w_gd)
print("cond(XᵀX) raw = %.3g" % np.linalg.cond(X.T @ X))
print("cond(ZᵀZ) scaled = %.3g" % np.linalg.cond(Z.T @ Z))
print("residuals ⟂ columns:", np.abs(X.T @ resid).max() < 1e-8)
print("R² = %.4f, σ̂ = %.4f" % (r2, np.sqrt(resid @ resid / (n - d - 1))))
Output:
true [ 4. 2. -0.5 0.03]
normal eq [ 3.9639 1.91 -0.5096 0.0305]
lstsq [ 3.9639 1.91 -0.5096 0.0305]
grad desc [ 3.9639 1.91 -0.5096 0.0305]
cond(XᵀX) raw = 1.01e+04
cond(ZᵀZ) scaled = 1.22
residuals ⟂ columns: True
R² = 0.9747, σ̂ = 1.0102
All three solvers agree to four decimals, and none recovers the true weights exactly: with 200 noisy points, \(\hat{\mathbf{w}}\) is itself a random variable centred on the truth, with spread \(\sigma^2(X^\top X)^{-1}\). \(\hat\sigma \approx 1.01\) recovers the noise level we injected (1.0). Standardising took the condition number from about \(10^4\) to \(1.2\), which is why 500 plain gradient steps were plenty.
Things to try
- Run gradient descent on the raw
Xwith step1/λ_max(XᵀX/n)and count the steps until the weights matchlstsqto 4 decimals. Relate the count to \(\kappa\). - Append a column equal to
X_raw[:, 0] * 2 + 1e-6 * noise(near-duplicate feature). Watch the condition number, the two weights and their sum. Then refit 20 times on bootstrap resamples and look at the spread of each weight. - Compute the standard errors \(\sqrt{\operatorname{diag}(\hat\sigma^2 (X^\top X)^{-1})}\) and check that roughly 95% of 1,000 simulated refits land within ±1.96 standard errors of the truth.
- Replace one target with
y[0] += 500and compare least squares with a hand-written Huber loss minimised by gradient descent. - Implement mini-batch SGD with batch size 16 and a decaying step size; plot the loss curve against full-batch descent.
Check yourself¶
Why does the fitted line always pass through the point \((\bar x, \bar y)\)?
The first normal equation (from the ones column) is \(\sum_i (y_i - \hat w_0 - \hat w_1 x_i) = 0\); divide by \(n\): \(\bar y = \hat w_0 + \hat w_1\bar x\). Any model with an intercept fitted by least squares has residuals summing to zero and passes through the centroid.
You double every value of one feature. What happens to its OLS weight, the predictions and \(R^2\)? What changes if you are using ridge regression instead?
The OLS weight halves and everything else is identical: the column space of \(X\) is unchanged, so the projection is unchanged. With ridge, the penalty \(\lambda w_j^2\) now costs a quarter as much for the same contribution, so that feature is shrunk less and the fit changes. Penalised and gradient-based methods are not scale-invariant; plain OLS is.
Gradient descent on raw features diverges at a step size that works fine after standardising. Explain using eigenvalues.
Stability needs \(\eta < 2/\lambda_{\max}(H)\). Raw features with large scales (say a column in the hundreds) give \(H = X^\top X/n\) an enormous largest eigenvalue, so the safe step is tiny; standardising makes all diagonal entries 1 and \(\lambda_{\max}\) modest. Even below the stability limit, progress along the smallest-eigenvalue direction is governed by \(1-\eta\lambda_{\min}\), so convergence takes about \(\kappa\ln(1/\epsilon)\) steps.
Show that the residual vector is orthogonal to the fitted values.
\(\hat{\mathbf{y}}^\top\mathbf{r} = (X\hat{\mathbf{w}})^\top(\mathbf{y} - X\hat{\mathbf{w}}) = \hat{\mathbf{w}}^\top X^\top(\mathbf{y}-X\hat{\mathbf{w}}) = \hat{\mathbf{w}}^\top\mathbf{0} = 0\) by the normal equations. Consequently \(\lVert\mathbf{y}\rVert^2 = \lVert\hat{\mathbf{y}}\rVert^2 + \lVert\mathbf{r}\rVert^2\), and (with an intercept, after centring) total sum of squares = explained + residual, which is why \(R^2 \in [0,1]\) on training data.
You have 50 rows and 200 features. What does lstsq return, what is the training error, and should you trust it?
With \(p > n\) the system is underdetermined: (generically) infinitely many \(\mathbf{w}\) fit the training data exactly, so training error is zero. lstsq returns the minimum-norm one, \(X^+\mathbf{y}\). Zero training error says nothing about test error; you need a held-out estimate, and usually an explicit penalty (ridge/lasso) chosen by cross-validation. Whether the minimum-norm interpolator generalises depends on the spectrum of the features: this is the setting studied in the double-descent literature.
Why is \(\hat\sigma^2\) divided by \(n - p\) rather than \(n\)?
The residual \((I-P)\boldsymbol{\varepsilon}\) is the noise projected onto an \((n-p)\)-dimensional subspace, so \(\mathbb{E}\lVert\mathbf{r}\rVert^2 = \sigma^2\operatorname{tr}(I-P) = \sigma^2(n-p)\). The fit "uses up" \(p\) dimensions of the noise by bending towards it; dividing by \(n\) underestimates \(\sigma^2\), badly when \(p\) is close to \(n\).
Hard: least squares targets \(\mathbb{E}[y\mid\mathbf{x}]\). If the true conditional mean is not linear, what does OLS converge to as \(n\to\infty\)?
The best linear approximation to \(\mathbb{E}[y\mid\mathbf{x}]\) in mean-squared sense under the input distribution: \(\mathbf{w}^\ast = \mathbb{E}[\mathbf{x}\mathbf{x}^\top]^{-1}\mathbb{E}[\mathbf{x}y]\), the population normal equations. It depends on where the inputs are sampled; shift the input distribution (covariate shift) and the best linear fit moves, even though \(\mathbb{E}[y\mid\mathbf{x}]\) did not. The gap between this and the truth is the model's bias, the subject of bias, variance and regularisation.
Go deeper¶
Papers
- Gauss and the Invention of Least Squares — Stephen Stigler, Annals of Statistics, 1981. The priority dispute between Legendre and Gauss, and what each actually contributed; short and readable.
- Regression Towards Mediocrity in Hereditary Stature — Francis Galton, 1886. Where the word "regression" comes from; look at the height tables and the regression-to-the-mean argument.
- Ridge Regression: Biased Estimation for Nonorthogonal Problems — Hoerl and Kennard, 1970. The fix for collinearity; read it after this page and before the next.
- Surprises in High-Dimensional Ridgeless Least Squares Interpolation — Hastie, Montanari, Rosset and Tibshirani, 2019. What the minimum-norm solution does when p > n; the modern sequel to this page.
Videos and lectures
- Linear Regression and Gradient Descent, CS229 Lecture 2 — Andrew Ng, Stanford, 2018. The normal equations and gradient descent derived at the board.
- Projection matrices and least squares, 18.06 Lecture 16 — Gilbert Strang, MIT. The projection picture from the linear-algebra side; the best 50 minutes on why \(X^\top X\) appears.
- Lecture 03: The Linear Model I — Yaser Abu-Mostafa, Caltech. Linear regression as a learning algorithm, with the generalisation question in view.
- Linear Regression, Clearly Explained — StatQuest (Josh Starmer). Gentle visual intuition for least squares and \(R^2\).
Articles and blog posts
- Linear Regression (interactive) — Amazon MLU-Explain. Scroll-driven visual explainer of the fit, the loss and the metrics.
- Lecture 8: Linear Regression — Kilian Weinberger, Cornell CS4780. Compact notes deriving OLS as MLE and ridge as MAP.
Courses and books
- The Elements of Statistical Learning — Hastie, Tibshirani and Friedman (free PDF). Chapter 3: least squares, Gauss–Markov, QR, subset selection and shrinkage, all rigorous.
- An Introduction to Statistical Learning — James, Witten, Hastie, Tibshirani (free PDF, Python edition). Chapter 3 for the applied view: standard errors, interactions, diagnostics.
- Mathematics for Machine Learning — Deisenroth, Faisal and Ong (free PDF). Chapter 9 treats linear regression as MLE, MAP and Bayesian inference in one sweep.
- CS229 main notes — Stanford. Part I: LMS, the normal equations and the probabilistic interpretation.
Code
-
numpy.linalg.lstsq— NumPy docs. The SVD-based solver to use instead of inverting \(X^\top X\). - Linear models user guide — scikit-learn. OLS, ridge, lasso, Huber, quantile regression and their solvers.
Where this leads¶
- Logistic regression and classification — the same weighted sum, passed through a sigmoid and trained with cross-entropy.
- Bias, variance and regularisation — ridge and lasso, and why adding bias can lower test error.
- Metrics, validation and leakage — measuring how well a fit will do on data it has not seen.
- Optimisation: convex and not — conditioning, step sizes and convergence rates in general.
- Neurons, perceptrons and MLPs — stack non-linear features underneath and learn them too.