Linear Regression and the Normal Equation
A shop wants to predict weekly sales from its advertising spend and the price of a competitor. A hospital wants to predict a disease-progression score from blood measurements. When the target is a number and you need a fast, transparent first model, linear regression is where you start. It is also the base that ridge, lasso, logistic regression and even neural networks build on. The Machine Learning course shows it on one feature; here you derive and implement the general version.
The model
Each example has features . The prediction is a weighted sum plus an intercept:
Stacking the examples as rows, with a leading column of ones, gives the design matrix and all predictions at once, .
The loss and the normal equation
Least squares chooses the weights that minimise the mean squared error:
The loss is a convex quadratic in , so the minimum is where the gradient is zero:
The name comes from geometry: at the solution the residual is orthogonal (normal) to every column of , so is the orthogonal projection of onto the column space. The derivations are in Linear Regression and Least Squares, The Geometry of Least Squares and Least Squares and Curve Fitting; the gradient identities are in Gradients of Matrices.
From scratch
Data with a known answer is the best test: plus Gaussian noise with standard deviation 0.5.
import numpy as np
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(0)
n = 200
X = rng.normal(size=(n, 2)) # two features
y = 3.0 + 2.0 * X[:, 0] - 1.0 * X[:, 1] + rng.normal(scale=0.5, size=n)
Xb = np.column_stack([np.ones(n), X]) # a column of ones for the intercept
w_normal = np.linalg.solve(Xb.T @ Xb, Xb.T @ y) # normal equation: (X^T X) w = X^T y
w_lstsq = np.linalg.lstsq(Xb, y, rcond=None)[0] # the numerically safer route (SVD)
sk = LinearRegression().fit(X, y)
print("normal equation:", w_normal.round(4))
print("lstsq :", w_lstsq.round(4))
print("scikit-learn :", np.r_[sk.intercept_, sk.coef_].round(4))
resid = y - Xb @ w_normal
print("residuals orthogonal to every column:", np.allclose(Xb.T @ resid, 0))
print("training MSE:", round(np.mean(resid ** 2), 4))normal equation: [ 2.9986 1.9749 -0.9403]
lstsq : [ 2.9986 1.9749 -0.9403]
scikit-learn : [ 2.9986 1.9749 -0.9403]
residuals orthogonal to every column: True
training MSE: 0.2458
All three routes recover weights close to the true , and the training MSE of 0.2458 is close to the noise variance : the model has found the signal and what is left is noise. Note the code solves the linear system with np.linalg.solve and never forms the inverse; lstsq (via the SVD) is safer still when columns are nearly dependent. scikit-learn's LinearRegression uses the same least-squares solver.
On real data
The diabetes data (442 patients, 10 standardised features, a disease-progression score one year later) is a harder problem:
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score, mean_absolute_error
X, y = load_diabetes(return_X_y=True) # 442 patients, 10 features
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0)
Xb = np.column_stack([np.ones(len(X_tr)), X_tr])
w = np.linalg.lstsq(Xb, y_tr, rcond=None)[0]
pred_ours = np.column_stack([np.ones(len(X_te)), X_te]) @ w
sk = LinearRegression().fit(X_tr, y_tr)
pred_sk = sk.predict(X_te)
print("same coefficients as sklearn:", np.allclose(w[1:], sk.coef_), np.isclose(w[0], sk.intercept_))
print("test R^2 ours", round(r2_score(y_te, pred_ours), 3), " sklearn", round(r2_score(y_te, pred_sk), 3))
print("test MAE ours", round(mean_absolute_error(y_te, pred_ours), 1))
print("baseline (predict the training mean) R^2:", round(r2_score(y_te, np.full_like(y_te, y_tr.mean())), 3) + 0.0)
print("condition number of X^T X:", f"{np.linalg.cond(Xb.T @ Xb):.0f}")same coefficients as sklearn: True True
test R^2 ours 0.359 sklearn 0.359
test MAE ours 45.1
baseline (predict the training mean) R^2: 0.0
condition number of X^T X: 47316
The test set is a quarter of the data (111 patients), held out from fitting. The model explains about 36 % of the variance on it (, where 0 is the "always predict the mean" baseline and 1 is perfect), with a mean absolute error of 45.1 points. That is typical of this data set: the features carry real but partial information. The condition number of (about 47 000) measures how close the columns are to being dependent; several blood measurements in this data are strongly correlated, which makes individual coefficients unstable even when predictions are fine. Ridge regression is the remedy.
is defined as
and can be negative on test data when a model is worse than predicting the mean.
Hyperparameters
Plain least squares has none, which is part of its appeal. LinearRegression(fit_intercept=True) only asks whether to add the column of ones. Its regularised cousins add one strength parameter (Ridge, Lasso and Elastic Net).
Strengths, weaknesses, when to use it
| Strengths | Weaknesses |
|---|---|
| exact solution, trains in milliseconds | only straight-line (hyperplane) relationships unless you add features |
| coefficients are readable: effect of one unit of a feature, others fixed | coefficients become unstable when features are correlated |
| a strong baseline; hard to overfit when | sensitive to outliers (squared error punishes large residuals) |
| extrapolates smoothly | extrapolates linearly, even where the truth is not linear |
Use it as the first model for every regression problem, as the baseline that more complex models must beat, and whenever you need to explain the effect of each feature.
Pitfalls
- Reading coefficients of unscaled features. A coefficient's size depends on the feature's unit; compare effects only after standardising, and only when features are not strongly correlated.
- Inverting .
np.linalg.invamplifies rounding errors for ill-conditioned matrices. Usesolveorlstsq. - More features than examples. If , is singular and the solution is not unique;
lstsqreturns the minimum-norm one, but regularisation is the real fix. - Calling a linear fit "causal". A coefficient describes association in this data, not what would happen if you changed the feature.
Practice
- A design matrix has two identical columns. What happens to the normal equation, and what does
lstsqreturn?
Answer
is singular, so the normal equation has infinitely many solutions (any split of the weight between the two copies gives the same predictions) and solve fails or returns garbage. lstsq returns the minimum-norm solution, which splits the weight equally between the copies.
- In the first example, why is the training MSE (0.2458) slightly below the noise variance 0.25 rather than above it?
Answer
Least squares fits the training data as closely as it can, including a little of its noise: three parameters absorb part of it. In expectation the training MSE is , below . On new data the error would be slightly above 0.25.
Test yourself
What does the normal equation say about the residual ?
- It is zero
- It is orthogonal to every column of
- It has mean equal to the intercept
- It is parallel to
A model has test . What does that mean?
- It explains 20 % of the variance
- It is worse than always predicting the mean of the target
- The computation is wrong; cannot be negative
- It is overfitting by 20 %
Why prefer np.linalg.lstsq or solve to np.linalg.inv(X.T @ X) @ X.T @ y?
- They are shorter to type
- They avoid forming an inverse, which loses accuracy when is ill-conditioned
invdoes not work on square matrices- They return the intercept separately