Sign in

Linear regression

Linear regression (ordinary least squares)

A model that predicts a number as a weighted sum of the input features plus a bias, with the weights chosen to make the squared errors as small as possible.

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

  1. Subtract the feature means from XX and the target mean from yy. This removes the bias from the problem, and it is recovered at the end.
  2. With solver set to normal, solve the least-squares problem in closed form. If λ>0\lambda > 0 the template solves the ridge system, otherwise it calls a least-squares routine that also copes with a singular X⊤XX^\top X.
  3. With solver set to gd, start from zero weights and repeat full-batch gradient steps of size η\eta for the given number of epochs, recording the loss in loss_history_.
  4. Recover the bias as b=yˉ−xˉ⊤wb = \bar{y} - \bar{\mathbf{x}}^\top \mathbf{w}, so the fitted plane passes through the mean point.
  5. Predict with y^=w⊤x+b\hat{y} = \mathbf{w}^\top \mathbf{x} + b, and judge the fit with R2R^2 from the score method.

Watch out for

  • Gradient descent diverges when η\eta 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, X⊤XX^\top X 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 R2R^2 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

IfUse instead
The target is a class, not a numberLogistic regression
The relationship is clearly non-linear or has many interactionsA random forest or gradient boosted trees
There are many correlated featuresRidge or lasso regression, or PCA before fitting

Math foundations

  1. The model

    y^=w⊤x+b\hat{y} = \mathbf{w}^\top \mathbf{x} + b

    The prediction is a weighted sum of the features plus a bias. Everything that follows is about choosing w\mathbf{w} and bb.

  2. The objective

    J(w,b)=∑i=1n(w⊤xi+b−yi)2+λ∥w∥2J(\mathbf{w}, b) = \sum_{i=1}^{n} \left(\mathbf{w}^\top \mathbf{x}_i + b - y_i\right)^2 + \lambda \lVert \mathbf{w} \rVert^2

    The sum of squared errors, plus a ridge penalty when λ>0\lambda > 0. The bias is not penalised. With λ=0\lambda = 0 this is ordinary least squares.

  3. The closed-form solution

    w=(Xc⊤Xc+λI)−1Xc⊤yc\mathbf{w} = \left(X_c^\top X_c + \lambda I\right)^{-1} X_c^\top \mathbf{y}_c

    Setting the gradient of JJ to zero gives the normal equations. XcX_c and yc\mathbf{y}_c are the centered data. The template solves the linear system rather than forming the inverse.

  4. The bias

    b=yˉ−xˉ⊤wb = \bar{y} - \bar{\mathbf{x}}^\top \mathbf{w}

    Once the weights are known, the bias is whatever makes the plane pass through the mean of the data.

  5. The gradient step

    w←w−ηn[Xc⊤(Xcw−yc)+λw]\mathbf{w} \leftarrow \mathbf{w} - \frac{\eta}{n}\left[X_c^\top \left(X_c \mathbf{w} - \mathbf{y}_c\right) + \lambda \mathbf{w}\right]

    The gd solver minimises J/(2n)J / (2n). Each step moves the weights against the gradient. It reaches the same answer as the closed form when η\eta is small enough and the epochs are enough.

  6. Goodness of fit

    R2=1−∑i(yi−y^i)2∑i(yi−yˉ)2R^2 = 1 - \frac{\sum_i (y_i - \hat{y}_i)^2}{\sum_i (y_i - \bar{y})^2}

    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

xi\mathbf{x}_i
feature vector of row i
yiy_i
target of row i
y^i\hat{y}_i
the model's prediction for row i
w\mathbf{w}
weight vector, one weight per feature
bb
bias (intercept)
Xc,ycX_c, \mathbf{y}_c
features and targets after subtracting their means
xˉ,yˉ\bar{\mathbf{x}}, \bar{y}
mean feature vector and mean target
λ\lambda
ridge strength, the l2 parameter
η\eta
step size, the lr parameter
nn
number of rows

Worked by hand

Fit a line to three points (1,1)(1, 1), (2,3)(2, 3), (3,4)(3, 4) with no ridge penalty. The means are xˉ=2\bar{x} = 2 and yˉ=8/3\bar{y} = 8/3, so the centered values are xc=(−1,0,1)x_c = (-1, 0, 1) and yc=(−5/3,1/3,4/3)y_c = (-5/3, 1/3, 4/3).

∑xc2=1+0+1=2\sum x_c^2 = 1 + 0 + 1 = 2
∑xcyc=53+0+43=3\sum x_c y_c = \tfrac{5}{3} + 0 + \tfrac{4}{3} = 3
w=32=1.5w = \frac{3}{2} = 1.5
b=83−2×1.5=−13b = \tfrac{8}{3} - 2 \times 1.5 = -\tfrac{1}{3}

The line is y^=1.5x−1/3\hat{y} = 1.5x - 1/3. It predicts 1.17, 2.67 and 4.17, and the residuals −0.17-0.17, 0.330.33, −0.17-0.17 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.0
Read 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

  1. 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 d×dd \times d system when dd is very large, and think about data that does not fit in memory. Then ask what gradient descent needs per step.

  2. 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.

  3. 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 λ∥w∥2\lambda \lVert \mathbf{w} \rVert^2 should touch. Ask what would happen to the bias if it sat inside the same penalised system.

  4. 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.