Search

Search papers and lessons

Linear Regression

Level 2 · 9 min read

Linear regression fits a straight line (or a flat plane in many dimensions) through data by choosing the weights that make the sum of squared errors as small as possible.

On this page

  • Colour = topic mix
  • Linear algebra
  • Probability
  • Classical models
  • Losses & regularization
  • Discrete math
  • Sign in to see your progress

TL;DR

Linear regression predicts a number as a weighted sum of input features, plus a constant. You pick the weights by finding the line, or flat plane in higher dimensions, that makes the squared gaps between predictions and true values as small as possible. That choice has a closed-form answer, so no iterative search is needed when the problem is small enough.

It is the simplest model that learns from data, and it is the template for most of the rest of machine learning. Almost every later model is a version of this idea with a more flexible function inside.

Where you'll see it: in forecasting sales from advertising spend, in calibrating lab instruments, in the least-squares fit that many data tools run by default, and as the baseline any new model must beat.

Intuition

Drawing the best line through a cloud

Plot the data as points. Hours of practice on the horizontal axis, exam score on the vertical axis. You can see a rising trend, but many lines could pass near the cloud. You need a rule for which line is best.

The usual rule is to measure each point's vertical gap from the line, which is called its residual, square those gaps so that signs do not cancel and big misses count more, and add them up. The best line is the one with the smallest total. The method is called least squares because it minimises the sum of squares.

01234560123456x (hours of practice)y (score)
  • best fit: y = 2.2 + 0.6x
Five data points and their least-squares line. Each point's residual is its vertical distance to the line.

A line compresses the whole cloud into two readable numbers: a slope (output change per unit of input) and an intercept (where the line starts).

The math

Definition: Linear regression model

Given an input vector x∈Rd\mathbf{x} \in \mathbb{R}^d, the model predicts y^=w⊤x+b\hat{y} = \mathbf{w}^\top \mathbf{x} + b, where w∈Rd\mathbf{w} \in \mathbb{R}^d is the weight vector (one weight per feature), bb is the intercept (also called the bias), and ⊤\top means transpose: it turns a column into a row so the product is a single number.

To remove the separate intercept, add a constant feature x0=1x_0 = 1 to every input and fold bb into the weights. The model becomes y^=w⊤x\hat{y} = \mathbf{w}^\top \mathbf{x}. Stack the nn training inputs as the rows of a matrix XX (size n×dn \times d), and stack the true targets as a column vector y\mathbf{y}.

The loss

We measure the fit with the mean squared error, the average of the squared residuals:

L(w)=1n∑i=1n(yi−w⊤xi)2=1n∥Xw−y∥2L(\mathbf{w}) = \frac{1}{n} \sum_{i=1}^{n} \left(y_i - \mathbf{w}^\top \mathbf{x}_i\right)^2 = \frac{1}{n} \left\| X\mathbf{w} - \mathbf{y} \right\|^2

Here yiy_i is the true output for example ii, xi\mathbf{x}_i is its input, and ∥⋅∥2\|\cdot\|^2 is the squared length of a vector, which is the sum of its squared entries. The second form is just the matrix version of the first. (See Mean Squared Error for the loss on its own.)

Finding the minimum

Expand the loss. Using (A−B)⊤(A−B)=A⊤A−2A⊤B+B⊤B(A - B)^\top (A - B) = A^\top A - 2A^\top B + B^\top B with A=XwA = X\mathbf{w} and B=yB = \mathbf{y}:

  1. L(w)=1n(w⊤X⊤Xw−2 w⊤X⊤y+y⊤y)L(\mathbf{w}) = \frac{1}{n}\left(\mathbf{w}^\top X^\top X \mathbf{w} - 2\,\mathbf{w}^\top X^\top \mathbf{y} + \mathbf{y}^\top \mathbf{y}\right).
  2. Take the gradient with respect to w\mathbf{w}, using the rules for Gradient of quadratic forms: ∇L(w)=2n(X⊤Xw−X⊤y)\nabla L(\mathbf{w}) = \frac{2}{n}\left(X^\top X \mathbf{w} - X^\top \mathbf{y}\right).
  3. At a minimum the gradient is zero, so X⊤Xw=X⊤yX^\top X \mathbf{w} = X^\top \mathbf{y}. These are the normal equations.
  4. If X⊤XX^\top X is invertible, solve for the weights:
w^=(X⊤X)−1X⊤y\hat{\mathbf{w}} = \left(X^\top X\right)^{-1} X^\top \mathbf{y}

The hat on w^\hat{\mathbf{w}} marks an estimate computed from data. Because LL is a sum of squares of linear functions, it is convex, so this stationary point is the global minimum.

The one-feature case

With a single input, the formula becomes two lines of arithmetic. Let xˉ\bar{x} and yˉ\bar{y} be the sample means:

β^1=∑i(xi−xˉ)(yi−yˉ)∑i(xi−xˉ)2,β^0=yˉ−β^1xˉ\hat{\beta}_1 = \frac{\sum_i (x_i - \bar{x})(y_i - \bar{y})}{\sum_i (x_i - \bar{x})^2}, \qquad \hat{\beta}_0 = \bar{y} - \hat{\beta}_1 \bar{x}

The slope is the covariance of xx and yy divided by the variance of xx. The intercept makes the line pass through the point (xˉ,yˉ)(\bar{x}, \bar{y}). A useful consequence: the residuals always sum to zero.

Worked examples

Example
A tiny dataset by hand

Use the five points from the plot: (x,y)=(1,2),(2,4),(3,5),(4,4),(5,5)(x, y) = (1, 2), (2, 4), (3, 5), (4, 4), (5, 5).

  1. Means: xˉ=3\bar{x} = 3 and yˉ=4\bar{y} = 4.
  2. Deviations from the mean: x−xˉ=−2,−1,0,1,2x - \bar{x} = -2, -1, 0, 1, 2 and y−yˉ=−2,0,1,0,1y - \bar{y} = -2, 0, 1, 0, 1.
  3. Numerator: (−2)(−2)+(−1)(0)+0⋅1+1⋅0+2⋅1=6(-2)(-2) + (-1)(0) + 0 \cdot 1 + 1 \cdot 0 + 2 \cdot 1 = 6.
  4. Denominator: 4+1+0+1+4=104 + 1 + 0 + 1 + 4 = 10.
  5. Slope β^1=6/10=0.6\hat{\beta}_1 = 6/10 = 0.6. Intercept β^0=4−0.6⋅3=2.2\hat{\beta}_0 = 4 - 0.6 \cdot 3 = 2.2.
  6. Predictions 2.2+0.6x2.2 + 0.6x at x=1,…,5x = 1, \dots, 5 are 2.8,3.4,4.0,4.6,5.22.8, 3.4, 4.0, 4.6, 5.2. Residuals y−y^y - \hat{y} are −0.8,0.6,1.0,−0.6,−0.2-0.8, 0.6, 1.0, -0.6, -0.2.
  7. The residuals sum to 00, as promised. The sum of squared residuals is 0.64+0.36+1.00+0.36+0.04=2.40.64 + 0.36 + 1.00 + 0.36 + 0.04 = 2.4, so the MSE is 2.4/5=0.482.4 / 5 = 0.48.
  8. Interpretation: each extra hour of practice is associated with about 0.6 more points, and no line does better on these five points.
Example
The same answer from the matrix formula

Build XX with a column of ones and a column of xx values, so w=(b,β)\mathbf{w} = (b, \beta).

  1. X⊤X=(5151555)X^\top X = \begin{pmatrix} 5 & 15 \\ 15 & 55 \end{pmatrix} and X⊤y=(2066)X^\top \mathbf{y} = \begin{pmatrix} 20 \\ 66 \end{pmatrix}. Here ∑xi=15\sum x_i = 15, ∑xi2=55\sum x_i^2 = 55, ∑yi=20\sum y_i = 20, and ∑xiyi=66\sum x_i y_i = 66.
  2. The determinant is 5⋅55−15⋅15=505 \cdot 55 - 15 \cdot 15 = 50, so the inverse is 150(55−15−155)\frac{1}{50}\begin{pmatrix} 55 & -15 \\ -15 & 5 \end{pmatrix}.
  3. Multiply: w^=150(55⋅20−15⋅66−15⋅20+5⋅66)=150(11030)=(2.20.6)\hat{\mathbf{w}} = \frac{1}{50}\begin{pmatrix} 55 \cdot 20 - 15 \cdot 66 \\ -15 \cdot 20 + 5 \cdot 66 \end{pmatrix} = \frac{1}{50}\begin{pmatrix} 110 \\ 30 \end{pmatrix} = \begin{pmatrix} 2.2 \\ 0.6 \end{pmatrix}.
  4. This matches the slope and intercept from the previous example, so the two routes agree.
Example
A realistic forecast, and where it breaks

An ice-cream shop fits daily sales (in units) against the day's high temperature tt in degrees Celsius, using 60 days of data between 18 and 30 degrees. The fitted model is sales=12+3.1 t\text{sales} = 12 + 3.1\,t.

  1. At t=25t = 25: 12+3.1⋅25=12+77.5=89.512 + 3.1 \cdot 25 = 12 + 77.5 = 89.5 units. This is inside the range of the data, so it is a reasonable forecast.
  2. At t=40t = 40: 12+3.1⋅40=12+124=13612 + 3.1 \cdot 40 = 12 + 124 = 136 units. This is outside the range of the data.
  3. The arithmetic is fine, but the number is not trustworthy. A straight line says sales rise forever. In reality the shop runs out of stock, or customers leave the city in the heat, and the trend flattens or reverses.

Tradeoffs and failure modes

Linear regression is fast, has a closed-form answer, and its weights are interpretable. It is also rigid, and most of its failures come from that rigidity or from the squared loss.

SituationProblemBetter choice
Relationship is curvedA straight line misses the pattern, and residuals show a systematic arcAdd transformed features (such as x2x^2), or use a nonlinear model
Outliers in the dataSquaring makes one far-off point dominate the fitHuber loss, or least absolute deviations
Features are strongly correlatedX⊤XX^\top X is nearly singular, so the weights swing wildly with small data changesRidge regression (L2 Regularization)
More features than examples (d>nd \gt n)X⊤XX^\top X is not invertible, so there are infinitely many exact fitsRidge regression, or a regularised solver
Very many featuresInverting a d×dd \times d matrix costs roughly d3d^3 operationsGradient Descent on the loss
Errors have different variancesEvery point is weighted equally, even noisy onesWeighted least squares
Prediction far outside the dataThe line extrapolates with no checkCollect data in that range, or use domain knowledge to bound the forecast

A common mistake is to read the weights as causes. A large weight means the feature predicts the output well, given the other features. It does not prove the feature causes the output.

History

The method of least squares was published by Adrien-Marie Legendre in 1805, as a way to fit the orbits of comets to noisy observations. Carl Friedrich Gauss said he had been using it since the 1790s, and in 1809 he tied it to the bell-shaped error distribution. That link is why least squares is the right answer under Gaussian noise, a point we return to through Maximum Likelihood Estimation.

The word regression came later. In the 1880s Francis Galton studied how the heights of children relate to their parents' heights, and found that extreme parents tend to have children closer to average. He called this regression toward mediocrity. Karl Pearson and George Udny Yule then built the general framework of correlation and multiple regression around 1900, and the name stuck even though the subject had nothing to do with going backwards.

Check yourself

QuestionIn one sentence, what does 'least squares' minimise?Show answer

The sum of the squared residuals, meaning the squared vertical distances between each observed yiy_i and the prediction y^i\hat{y}_i. Squaring stops positive and negative errors cancelling and makes large misses count more.

QuestionFit a line to the points (0,1),(1,3),(2,4)(0, 1), (1, 3), (2, 4). What is the prediction at x=3x = 3?Show answer

The means are xˉ=1\bar{x} = 1 and yˉ=8/3\bar{y} = 8/3. The numerator is (−1)(1−8/3)+0+(1)(4−8/3)=5/3+4/3=3(-1)(1 - 8/3) + 0 + (1)(4 - 8/3) = 5/3 + 4/3 = 3, and the denominator is 22, so the slope is 1.51.5. The intercept is 8/3−1.5⋅1=7/68/3 - 1.5 \cdot 1 = 7/6. At x=3x = 3 the prediction is 7/6+4.5=34/6≈5.677/6 + 4.5 = 34/6 \approx 5.67.

QuestionWhy does the matrix formula need X⊤XX^\top X to be invertible, and what goes wrong if two features are exact copies of each other?Show answer

The formula multiplies by (X⊤X)−1(X^\top X)^{-1}, which exists only when the columns of XX are linearly independent. If two features are identical, the columns are dependent, X⊤XX^\top X is singular, and there are infinitely many weight vectors that give the same predictions. The solver cannot pick one. Ridge regression fixes this by adding a small λI\lambda I to X⊤XX^\top X, which makes it invertible.

QuestionA model fitted on temperatures between 20 and 30 degrees is used to forecast sales at 45 degrees. What is the main risk, and why is the linear formula not the problem?Show answer

The main risk is extrapolation: the model has never seen data near 45 degrees, and the real relationship may bend or flatten there. The linear formula itself is computed correctly. The problem is assuming the fitted pattern still holds outside the range where it was measured.

Sources