Overview
Plot house size against price and the points form a rough upward cloud. Linear regression draws the one straight line through that cloud for which the vertical gaps between line and points, squared and added up, are smallest. With several features the line becomes a flat plane, but the idea is the same. Each weight says how much the prediction moves when one feature rises by one unit and the others stay fixed. Ridge regression adds a small penalty on large weights, which steadies the answer when features overlap.
A short history
Adrien-Marie Legendre published the method of least squares in 1805, and Carl Friedrich Gauss, who published it in 1809, said he had used it earlier; both applied it to orbits in astronomy. Francis Galton introduced the word regression in the 1880s when studying how children's heights relate to their parents'. It remains the first model to try for a numeric target because it is fast, has an exact solution and gives weights that can be read directly.
How it works
- Subtract the feature means from and the target mean from . This removes the bias from the problem, and it is recovered at the end.
- With solver set to normal, solve the least-squares problem in closed form. If the template solves the ridge system, otherwise it calls a least-squares routine that also copes with a singular .
- With solver set to gd, start from zero weights and repeat full-batch gradient steps of size for the given number of epochs, recording the loss in loss_history_.
- Recover the bias as , so the fitted plane passes through the mean point.
- Predict with , and judge the fit with from the score method.
Watch out for
- Gradient descent diverges when is too large for the scale of the features, because the step overshoots the minimum each time. Standardise the features or lower lr.
- When two features are nearly copies of each other, is close to singular and the weights become huge and unstable. A small l2 fixes this.
- Squared error punishes large misses heavily, so a few outliers can drag the whole line toward them.
- A high on the training data does not show that the model is right. A curved relationship can still score well while the residuals show a clear pattern.
Use cases
When to use it
Predicting a continuous quantity when the relationship is roughly linear, and as the first baseline before any more complex regressor. It is also the right tool when you need weights you can read and explain.
In industry
- Real estate
- Estimating a sale price from floor area, location and age, with each weight read as the value of one more unit.
- Marketing
- Estimating how sales respond to spending in each channel, as a first step in media mix analysis.
- Science and engineering
- Calibration: fitting a straight line that converts an instrument reading into a physical quantity.
Choosing it: what must hold
- A numeric target, such as a price, a quantity or a duration.
- A relationship that is roughly linear in the features, or in transformed features you supply.
- More rows than features, and features that are not near copies of one another.
- Few extreme outliers, since squared error gives them large influence.
When to choose something else
| If | Use instead |
|---|---|
| The target is a class, not a number | Logistic regression |
| The relationship is clearly non-linear or has many interactions | A random forest or gradient boosted trees |
| There are many correlated features | Ridge or lasso regression, or PCA before fitting |
Math foundations
The model
The prediction is a weighted sum of the features plus a bias. Everything that follows is about choosing and .
The objective
The sum of squared errors, plus a ridge penalty when . The bias is not penalised. With this is ordinary least squares.
The closed-form solution
Setting the gradient of to zero gives the normal equations. and are the centered data. The template solves the linear system rather than forming the inverse.
The bias
Once the weights are known, the bias is whatever makes the plane pass through the mean of the data.
The gradient step
The gd solver minimises . Each step moves the weights against the gradient. It reaches the same answer as the closed form when is small enough and the epochs are enough.
Goodness of fit
The share of the target's variation that the model explains. It is 1 for a perfect fit and 0 for a model no better than always predicting the mean.
Symbols
- feature vector of row i
- target of row i
- the model's prediction for row i
- weight vector, one weight per feature
- bias (intercept)
- features and targets after subtracting their means
- mean feature vector and mean target
- ridge strength, the l2 parameter
- step size, the lr parameter
- number of rows
Worked by hand
Fit a line to three points , , with no ridge penalty. The means are and , so the centered values are and .
The line is . It predicts 1.17, 2.67 and 4.17, and the residuals , , add up to zero, as they always do when a bias is fitted.
Visual example
Loading the example.
Try this
- Click to add a point far from the others: the line swings toward it.
- The grey bars are the errors the line is minimising.
Code sample
import numpy as np
from impl import LinRegression
from config import LinRegressionConfig
X = np.array([[0.0], [1.0], [2.0], [3.0]])
y = np.array([1.0, 3.0, 5.0, 7.0]) # y = 2 x + 1
model = LinRegression(LinRegressionConfig()).fit(X, y)
print(model.coef_, model.intercept_) # [2.] 1.0
print(model.predict(np.array([[4.0]]))) # [9.]
print(model.score(X, y)) # R^2 = 1.0Read the implementation (85 lines)
"""Linear regression: ordinary least squares and ridge, by closed form or by gradient descent.
NumPy only. The model is y = X w + b. The objective is
||X w + b - y||^2 + l2 * ||w||^2
where the bias b is not penalised.
"""
from __future__ import annotations
import numpy as np
try:
from .config import LinRegressionConfig
except ImportError: # run from the template's own folder
from config import LinRegressionConfig
class LinRegression:
"""Least-squares linear model. After `fit`: `coef_` (d,) or (d, k), `intercept_` scalar or (k,)."""
def __init__(self, config: LinRegressionConfig | None = None) -> None:
self.config = config or LinRegressionConfig()
self.coef_: np.ndarray | None = None
self.intercept_: np.ndarray | float = 0.0
self.loss_history_: list[float] = []
def fit(self, X: np.ndarray, y: np.ndarray) -> "LinRegression":
"""Fit the model.
X: features, shape (n, d). y: targets, shape (n,) for one target or (n, k) for k targets.
"""
X = np.asarray(X, dtype=float)
y = np.asarray(y, dtype=float)
if X.ndim != 2 or len(X) != len(y):
raise ValueError("X must have shape (n, d) and y must have n rows")
single = y.ndim == 1
Y = y.reshape(len(y), -1)
if self.config.fit_intercept:
x_mean, y_mean = X.mean(axis=0), Y.mean(axis=0)
else:
x_mean, y_mean = np.zeros(X.shape[1]), np.zeros(Y.shape[1])
# Centering removes the bias from the problem; it is recovered from the means afterwards.
Xc, Yc = X - x_mean, Y - y_mean
if self.config.solver == "normal":
W = self._solve_normal(Xc, Yc)
else:
W = self._solve_gd(Xc, Yc)
b = y_mean - x_mean @ W
self.coef_ = W[:, 0] if single else W
self.intercept_ = float(b[0]) if single else b
return self
def _solve_normal(self, Xc: np.ndarray, Yc: np.ndarray) -> np.ndarray:
"""Closed form. Xc (n, d) and Yc (n, k) are centered. Returns W of shape (d, k)."""
if self.config.l2 > 0:
d = Xc.shape[1]
return np.linalg.solve(Xc.T @ Xc + self.config.l2 * np.eye(d), Xc.T @ Yc)
# lstsq gives the minimum-norm solution when X^T X is singular.
return np.linalg.lstsq(Xc, Yc, rcond=None)[0]
def _solve_gd(self, Xc: np.ndarray, Yc: np.ndarray) -> np.ndarray:
"""Full-batch gradient descent on the objective divided by 2n. Returns W of shape (d, k)."""
n, d = Xc.shape
W = np.zeros((d, Yc.shape[1]))
self.loss_history_ = []
for _ in range(self.config.epochs):
residual = Xc @ W - Yc
loss = (np.sum(residual**2) + self.config.l2 * np.sum(W**2)) / (2 * n)
self.loss_history_.append(float(loss))
W -= self.config.lr * (Xc.T @ residual + self.config.l2 * W) / n
return W
def predict(self, X: np.ndarray) -> np.ndarray:
"""Predict targets. X: shape (n, d). Returns shape (n,) or (n, k)."""
if self.coef_ is None:
raise RuntimeError("call fit before predict")
return np.asarray(X, dtype=float) @ self.coef_ + self.intercept_
def score(self, X: np.ndarray, y: np.ndarray) -> float:
"""Coefficient of determination R^2 = 1 - SS_res / SS_tot (1.0 is a perfect fit)."""
y = np.asarray(y, dtype=float)
ss_res = np.sum((y - self.predict(X)) ** 2)
ss_tot = np.sum((y - y.mean(axis=0)) ** 2)
return float(1.0 - ss_res / ss_tot)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Create data with a known rule, for example y equal to 3 times the first feature minus 2 times the second plus 1 plus small noise. Fit LinRegression with LinRegressionConfig solver set to normal, then again with solver set to gd. Compare coef_ and intercept_ from the two fits, and plot loss_history_ for lr values 0.01, 0.1 and 1.0 to see where gradient descent stops converging.
Check on learning
- The closed form gives the exact minimum in one step. Why would anyone use gradient descent for linear regression?
A way to think about it
Count the cost of solving a system when is very large, and think about data that does not fit in memory. Then ask what gradient descent needs per step.
- You add a ridge penalty and the training error goes up. Under what conditions would the test error go down?
A way to think about it
Think about what happens to the weights when two features are almost identical, and how a small change in the training rows would change them with and without the penalty.
- Why does the template center the data instead of adding a column of ones to X?
A way to think about it
Look at which parameters the penalty should touch. Ask what would happen to the bias if it sat inside the same penalised system.
- Gradient descent converges on your raw data only with a very small lr, but quickly after you standardise the features. What changed?
A way to think about it
Picture the loss surface as a bowl. Features on very different scales stretch the bowl into a long narrow valley. Consider how the largest safe step relates to the steepest direction.