◆ AI All-in-One

Level 3 In-Depth AI · Classical Machine Learning

Linear Regression

The simplest learning algorithm that is genuinely useful. Predict a number as a weighted sum of the inputs, and choose the weights that make the squared errors as small as possible.

Level
●●●●● Easy
Reading
14 min
To learn it well
1 hour to read, an afternoon to practise
↗ Plan a path here

Read first

Supervised LearningGradient Descent

This leads to

Logistic RegressionLoss FunctionsRegularization: L1 and L2Time Series Forecasting
The full path from zero — 8 concepts before this one
  1. What Is AI?
  2. Derivatives and Slopes
  3. Vectors
  4. How Machines Learn
  5. Partial Derivatives and Gradients
  6. Supervised, Unsupervised and Reinforcement Learning
  7. Gradient Descent
  8. Supervised Learning
  9. Linear Regression

Read them roughly in this order. See it on the concept map →

Why it matters

Linear regression predicts a number by adding up the inputs, each multiplied by a weight. It is more than two hundred years old, and it is still everywhere. Economists use it to estimate how much an extra year of schooling adds to earnings. Engineers use it to calibrate sensors. Data scientists fit it first on every new regression problem, because it trains in milliseconds, its answers can be read and explained, and anything fancier has to beat it to justify itself.

It also matters because it is the seed of deep learning. A single artificial neuron in a neural network computes exactly a linear regression (a weighted sum plus a bias) and then bends the result with an activation function. The last layer of most networks is a linear regression on features that the earlier layers have learned. Understand the weighted sum, the squared-error loss and how to fit them, and you understand the core arithmetic of models with billions of parameters.

The intuition

Plot your data: one feature along the bottom, the label up the side, one dot per example. If the dots roughly follow a straight-line trend, you can summarise them with a line, and use that line to predict the label for any new xx.

But which line? You could draw many plausible ones by eye. Linear regression makes the choice precise. For every example, measure how far the line misses the dot vertically. That miss is called the residual. Square each residual, so that misses above and below both count as bad and big misses count for much more than small ones. Then pick the line that makes the sum of the squared residuals as small as possible. This is the method of least squares.

1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 feature x label y Data points the examples (xᵢ, yᵢ) Fitted line ŷ = 0.65x + 1.18 Residuals red lines: ŷᵢ − yᵢ the error on each example Squared errors shaded squares: area = error² least squares makes the total shaded area smallest
Fig. 1 A line fitted by least squares. The red vertical lines are the residuals, the gap between each data point and the line. The shaded squares have areas equal to the squared residuals; the fitted line is the one that makes their total area as small as possible.

Think of the dots as pegs and the line as a stiff rod, with a spring from each peg to the rod. Each spring pulls with a strength that grows with its stretch. The rod settles where the pulls balance. Least squares finds that balance point.

Key idea Linear regression predicts y^=w1x1+w2x2+⋯+b\hat{y} = w_1 x_1 + w_2 x_2 + \dots + b and chooses the weights that minimise the mean squared error on the training data. There is an exact formula for the best weights, and Gradient Descent reaches the same answer step by step.

How it works

One feature: a line

With one feature the model is a line:

y^=wx+b\hat{y} = w x + b

The weight ww is the slope: how much the prediction rises when xx increases by 1. The bias bb is the intercept: the prediction when x=0x = 0. (Statisticians call both the coefficients.)

The loss is the mean squared error (MSE), the average of the squared residuals over all NN training examples:

L(w,b)=1N∑i=1N(wxi+b−yi)2L(w, b) = \frac{1}{N} \sum_{i=1}^{N} \left( w x_i + b - y_i \right)^2

Here xix_i and yiy_i are the feature and label of example ii, and wxi+b−yiw x_i + b - y_i is its residual.

For a single feature, calculus gives the best line directly. Set both partial derivatives of LL to zero and solve, and you get:

w=∑i(xi−xˉ)(yi−yˉ)∑i(xi−xˉ)2,b=yˉ−wxˉw = \frac{\sum_i (x_i - \bar{x})(y_i - \bar{y})}{\sum_i (x_i - \bar{x})^2}, \qquad b = \bar{y} - w \bar{x}

The bar means "average": xˉ\bar{x} is the mean of the xx values. In words: the slope measures how much xx and yy move together, divided by how much xx moves on its own. The intercept then makes the line pass through the point of averages (xˉ,yˉ)(\bar{x}, \bar{y}).

A worked example by hand

Use the four students from Supervised Learning: hours of practice x=1,2,3,4x = 1, 2, 3, 4 and scores y=3,5,7,8y = 3, 5, 7, 8.

  1. Averages: xˉ=10/4=2.5\bar{x} = 10/4 = 2.5 and yˉ=23/4=5.75\bar{y} = 23/4 = 5.75.
  2. Deviations from the average: xi−xˉ=−1.5,−0.5,0.5,1.5x_i - \bar{x} = -1.5, -0.5, 0.5, 1.5 and yi−yˉ=−2.75,−0.75,1.25,2.25y_i - \bar{y} = -2.75, -0.75, 1.25, 2.25.
  3. Top of the fraction: (−1.5)(−2.75)+(−0.5)(−0.75)+(0.5)(1.25)+(1.5)(2.25)=4.125+0.375+0.625+3.375=8.5(-1.5)(-2.75) + (-0.5)(-0.75) + (0.5)(1.25) + (1.5)(2.25) = 4.125 + 0.375 + 0.625 + 3.375 = 8.5.
  4. Bottom: 2.25+0.25+0.25+2.25=52.25 + 0.25 + 0.25 + 2.25 = 5.
  5. So w=8.5/5=1.7w = 8.5 / 5 = 1.7 and b=5.75−1.7×2.5=1.5b = 5.75 - 1.7 \times 2.5 = 1.5.

The best line is y^=1.7x+1.5\hat{y} = 1.7x + 1.5, with MSE 0.075, exactly what brute-force search found in the previous chapter. Each extra hour of practice is worth about 1.7 points.

Many features: a plane and beyond

Real problems have many features. A house price might depend on floor area x1x_1, bedrooms x2x_2 and distance to the station x3x_3. Multiple linear regression gives each feature its own weight:

y^=w1x1+w2x2+⋯+wdxd+b=w⋅x+b\hat{y} = w_1 x_1 + w_2 x_2 + \dots + w_d x_d + b = \mathbf{w} \cdot \mathbf{x} + b

The dot means the dot product: multiply matching entries and add. With two features the model is a flat plane hovering over the (x1,x2)(x_1, x_2) floor. With more, it is a "hyperplane" you can't picture, but the arithmetic is identical.

A standard trick removes the separate bias. Add a feature that is always 1, call its weight bb, and the model becomes a single dot product. Stack all examples as rows of a matrix X\mathbf{X} (with that column of 1s, it is often called the design matrix) and all parameters into one vector θ\boldsymbol{\theta}. Then every prediction at once is a matrix–vector product:

y^=Xθ\hat{\mathbf{y}} = \mathbf{X} \boldsymbol{\theta}

The closed-form solution: the normal equation

Setting the gradient of the MSE to zero gives the normal equation:

X⊤X θ=X⊤y⟹θ=(X⊤X)−1X⊤y\mathbf{X}^\top \mathbf{X} \, \boldsymbol{\theta} = \mathbf{X}^\top \mathbf{y} \quad\Longrightarrow\quad \boldsymbol{\theta} = (\mathbf{X}^\top \mathbf{X})^{-1} \mathbf{X}^\top \mathbf{y}

X⊤\mathbf{X}^\top is the transpose of X\mathbf{X} (rows turned into columns), and the superscript −1-1 means the matrix inverse. Check it on the students. With a column of 1s first:

X=(11121314),X⊤X=(4101030),X⊤y=(2366)\mathbf{X} = \begin{pmatrix} 1 & 1 \\ 1 & 2 \\ 1 & 3 \\ 1 & 4 \end{pmatrix}, \quad \mathbf{X}^\top \mathbf{X} = \begin{pmatrix} 4 & 10 \\ 10 & 30 \end{pmatrix}, \quad \mathbf{X}^\top \mathbf{y} = \begin{pmatrix} 23 \\ 66 \end{pmatrix}

The entries are just sums: 4 examples, ∑x=10\sum x = 10, ∑x2=30\sum x^2 = 30, ∑y=23\sum y = 23, ∑xy=66\sum xy = 66. The inverse of a 2×2 matrix (abcd)\begin{pmatrix} a & b \\ c & d \end{pmatrix} is 1ad−bc(d−b−ca)\frac{1}{ad - bc}\begin{pmatrix} d & -b \\ -c & a \end{pmatrix}, so here 120(30−10−104)\frac{1}{20}\begin{pmatrix} 30 & -10 \\ -10 & 4 \end{pmatrix}. Multiply:

θ=120(30⋅23−10⋅66−10⋅23+4⋅66)=120(3034)=(1.51.7)\boldsymbol{\theta} = \frac{1}{20}\begin{pmatrix} 30 \cdot 23 - 10 \cdot 66 \\ -10 \cdot 23 + 4 \cdot 66 \end{pmatrix} = \frac{1}{20}\begin{pmatrix} 30 \\ 34 \end{pmatrix} = \begin{pmatrix} 1.5 \\ 1.7 \end{pmatrix}

Bias 1.5, weight 1.7: the same answer. In practice no one inverts the matrix explicitly. Libraries solve the system with stabler methods (QR or SVD decompositions, see Eigenvectors and SVD), but the result is the same. The cost grows roughly with the cube of the number of features, which is fine for hundreds or a few thousand features and too slow for millions.

The gradient-descent route

The MSE is a smooth bowl in parameter space, with one bottom and no local minima. Gradient Descent slides down it. The gradient of the MSE is:

∇L(θ)=2NX⊤(Xθ−y)\nabla L(\boldsymbol{\theta}) = \frac{2}{N} \mathbf{X}^\top (\mathbf{X}\boldsymbol{\theta} - \mathbf{y})

In words: take the vector of residuals, weight each feature column by them, and average. A feature whose values line up with big positive residuals gets a big positive gradient, so its weight is pushed down. The update is θ←θ−η∇L\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} - \eta \nabla L.

0 1 2 3 -2 -1 0 1 2 3 4 5 weight w (slope) bias b start (0, 0) Ellipses: equal loss each ring joins (w, b) pairs with the same mean squared error: 0.2, 0.6, 1.5, 3, 6, 12, 24 from inside out Minimum: w = 1.7, b = 1.5 MSE = 0.075, the best line Gradient descent, η = 0.05 dots after 0, 1, 2, 3, 5, 10, 20, 50, 100, 200 steps Why the path bends the bowl is steep across the valley and nearly flat along it: step 1 fixes w almost at once, then b crawls
Fig. 2 Contours of the mean squared error for the four students, as a function of slope w and bias b. Each ellipse joins parameter pairs with equal loss. Gradient descent from (0, 0) fixes the slope in one big step, then creeps along the flat valley floor to the minimum at w = 1.7, b = 1.5.

The picture shows why feature scaling matters. The bowl is a long, narrow valley, because the slope ww multiplies xx values of 1 to 4 while the bias multiplies a constant 1. Gradient descent zig-zags or crawls in such valleys. Standardising the features (subtract the mean, divide by the standard deviation; see Data Cleaning and Preparation) makes the bowl rounder and the descent fast.

Why bother with gradient descent when a formula exists? Because it scales to millions of features and billions of examples, it works on data streamed in mini-batches, and it carries over unchanged to models that have no formula, such as Logistic Regression and neural networks.

Interpreting the weights

Each weight answers: if this feature goes up by one unit and all other features stay the same, how much does the prediction change? If a house-price model has a weight of 2.1 on floor area in square metres (price in £1000s), each extra square metre adds about £2,100, holding bedrooms and location fixed.

Two cautions. First, weights depend on units. Measure area in square feet and the weight shrinks by a factor of about 10.8. To compare features' importance, standardise them first, so each weight means "per standard deviation". Second, a weight describes association in this data, not cause and effect. More on both below.

Curves with a linear model

"Linear" refers to the parameters, not the shape. You can add new features such as x2x^2 and x3x^3 and fit y^=w1x+w2x2+w3x3+b\hat{y} = w_1 x + w_2 x^2 + w_3 x^3 + b with exactly the same machinery. This is polynomial regression. It bends to fit curved data, and with too many powers it bends too much, which is the story of Overfitting and the Bias–Variance Tradeoff.

In code

From scratch with NumPy, on the diabetes dataset that ships with scikit-learn (442 patients, 10 measurements such as age, BMI and blood pressure, and a measure of disease progression one year later). We fit it both ways and check they agree.

import numpy as np
from sklearn.datasets import load_diabetes

X, y = load_diabetes(return_X_y=True)        # 442 patients, 10 features
X = (X - X.mean(axis=0)) / X.std(axis=0)     # standardise each feature
X1 = np.column_stack([np.ones(len(X)), X])  # column of 1s for the bias

# 1) Closed form (normal equation): solve (X^T X) theta = X^T y
theta = np.linalg.solve(X1.T @ X1, X1.T @ y)

# 2) Gradient descent on the same mean squared error
theta_gd = np.zeros(X1.shape[1])
lr = 0.1
for step in range(5001):
    err = X1 @ theta_gd - y
    grad = 2 / len(y) * X1.T @ err           # gradient of the MSE
    theta_gd -= lr * grad
    if step in (0, 100, 1000, 5000):
        print(f"step {step:4d}  MSE {np.mean(err**2):8.1f}")

print("closed form  b, w_bmi:", theta[0].round(2), theta[3].round(2))
print("grad descent b, w_bmi:", theta_gd[0].round(2), theta_gd[3].round(2))
# step    0  MSE  29074.5
# step  100  MSE   2875.6
# step 1000  MSE   2860.4
# step 5000  MSE   2859.7
# closed form  b, w_bmi: 152.13 24.73
# grad descent b, w_bmi: 152.13 24.73

Because the features are standardised, the BMI weight reads: one standard deviation more BMI goes with a disease score about 24.7 points higher, other measurements held fixed. The bias, 152.13, is simply the average label, since every feature has mean zero.

With scikit-learn it is one line to fit. We hold out a test set to see how well it does on new patients:

from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score

data = load_diabetes()
X_tr, X_te, y_tr, y_te = train_test_split(data.data, data.target, random_state=0)

model = LinearRegression().fit(X_tr, y_tr)
for name, w in zip(data.feature_names, model.coef_):
    print(f"{name:>4}: {w:8.1f}")
print("bias:", round(model.intercept_, 1))

pred = model.predict(X_te)
print("test RMSE:", round(mean_squared_error(y_te, pred) ** 0.5, 1))
print("test R^2: ", round(r2_score(y_te, pred), 3))
print("label std:", round(y_te.std(), 1))
#  age:    -43.3
#  sex:   -208.7
#  bmi:    593.4
#   bp:    302.9
#   s1:   -560.2
#   s2:    261.4
#   s3:     -8.9
#   s4:    135.9
#   s5:    703.2
#   s6:     28.3
# bias: 153.1
# test RMSE: 56.4
# test R^2:  0.359
# label std: 70.5

(The weights are large because this dataset's features come pre-scaled to tiny values.) The root mean squared error of 56.4 is the typical size of a miss. Compare it with 70.5, the spread of the labels: always predicting the average would miss by about 70, so the model helps, but modestly. The R2R^2 of 0.36 says the same thing: it explains about 36% of the variation. See Evaluation Metrics.

Common pitfalls

  • Unscaled features with gradient descent. If one feature is in the thousands and another in fractions, the loss valley becomes long and thin, and gradient descent needs a tiny learning rate and a huge number of steps. Standardise first. (The closed-form solution doesn't care.)
  • Outliers. Squaring makes one wild point count enormously: a residual of 10 weighs as much as a hundred residuals of 1. A single data-entry error can tilt the whole line. Plot your data, and consider a robust loss such as Huber or absolute error (Loss Functions).
  • Correlated features (multicollinearity). In the diabetes output, s1 and s2 (two cholesterol measurements that move together) get large weights of opposite sign, −560 and +261. When features are near-duplicates, the data can't tell them apart, so their individual weights become unstable and hard to interpret, even if predictions are fine. Ridge regression calms this.
  • A curved relationship. If the truth bends, a straight line will be systematically wrong in places. Plot the residuals against each feature: a pattern (a U-shape, a fan) means the model is missing something. Add polynomial or other engineered features, or use a more flexible model.
  • Extrapolation. The line is only supported where you have data. Predicting far outside that range is guesswork.

Watch out A weight is not a causal effect. Ice-cream sales predict drowning deaths well, because both rise in summer. A regression weight tells you how the prediction moves with a feature in this data; whether changing the feature in the world would change the outcome is a separate question that needs experiments or causal methods.

Where it leads

A bit of history

Adrien-Marie Legendre published the method of least squares in 1805, in a work on computing comet orbits. Carl Friedrich Gauss published it in 1809, claimed he had used it since 1795, and connected it to the normal distribution of measurement errors, which explains why squared error is natural when errors are bell-shaped (see Maximum Likelihood Estimation). The word "regression" comes from Francis Galton, who in the 1880s studied the heights of parents and children and saw that children of very tall parents tend to be tall, but closer to average: "regression towards mediocrity". The name stuck to the fitting method. Through the 20th century linear regression became the workhorse of statistics, economics and the sciences, and it remains the first model taught in every machine-learning course.

Try it

  1. Add a fifth student who practised 5 hours and scored 2 (perhaps they were ill). Recompute ww and bb by hand. How much does one outlier move the line?
  2. In the NumPy code, remove the standardisation line and run gradient descent again with lr = 0.1. Does the MSE still reach 2859.7 after 5,000 steps? Why not? (This dataset ships with every feature already shrunk to a spread of about 0.05.)
  3. Fit LinearRegression on the diabetes data using only the bmi column (X_tr[:, [2]]). What test R2R^2 do you get? What does that tell you about the other nine features?

Hint for 1: the new averages are xˉ=3\bar{x} = 3, yˉ=5\bar{y} = 5. The slope collapses from 1.7 to 0.1.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Linear regression fits the line that minimises the sum of squared residuals. What is a residual?

  2. A house-price model (price in £1000s) has a weight of 2.1 on floor area in m². What does that mean?

  3. Gradient descent on unstandardised features (one in the thousands, one in fractions) crawls along. Why?

  4. Two cholesterol measurements that move together get large weights of opposite sign (−560 and +261). What is this called?

  5. You fit ŷ = w₁x + w₂x² + w₃x³ + b. Is this still linear regression?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Interactive

MLU-Explain: Linear Regression

Amazon Machine Learning University (MLU-Explain) · Beginner · Free

A scrolling visual essay that builds linear regression from a scatter plot, with interactive fits and residuals.

Course

Machine Learning Crash Course

Google · Beginner · Free

Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.

Video

StatQuest

Josh Starmer · Beginner · Free

Short, cheerful, very clear videos on statistics and nearly every ML algorithm.

Docs

scikit-learn: Linear Models

scikit-learn · Intermediate · Free

The user-guide chapter on ordinary least squares, ridge, lasso, elastic net and logistic regression, with the maths and runnable examples.

Course

Stanford CS229: Machine Learning

Stanford University · Advanced · Free

The classic mathematically rigorous ML course. Lecture notes and recorded lectures are free online.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/linear-regression.md