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
- Builds on
- 8 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 8 concepts before this one
- What Is AI?
- Derivatives and Slopes
- Vectors
- How Machines Learn
- Partial Derivatives and Gradients
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- 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 .
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.
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 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:
The weight is the slope: how much the prediction rises when increases by 1. The bias is the intercept: the prediction when . (Statisticians call both the coefficients.)
The loss is the mean squared error (MSE), the average of the squared residuals over all training examples:
Here and are the feature and label of example , and is its residual.
For a single feature, calculus gives the best line directly. Set both partial derivatives of to zero and solve, and you get:
The bar means "average": is the mean of the values. In words: the slope measures how much and move together, divided by how much moves on its own. The intercept then makes the line pass through the point of averages .
A worked example by hand
Use the four students from Supervised Learning: hours of practice and scores .
- Averages: and .
- Deviations from the average: and .
- Top of the fraction: .
- Bottom: .
- So and .
The best line is , 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 , bedrooms and distance to the station . Multiple linear regression gives each feature its own weight:
The dot means the dot product: multiply matching entries and add. With two features the model is a flat plane hovering over the 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 , and the model becomes a single dot product. Stack all examples as rows of a matrix (with that column of 1s, it is often called the design matrix) and all parameters into one vector . Then every prediction at once is a matrix–vector product:
The closed-form solution: the normal equation
Setting the gradient of the MSE to zero gives the normal equation:
is the transpose of (rows turned into columns), and the superscript means the matrix inverse. Check it on the students. With a column of 1s first:
The entries are just sums: 4 examples, , , , . The inverse of a 2×2 matrix is , so here . Multiply:
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:
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 .
The picture shows why feature scaling matters. The bowl is a long, narrow valley, because the slope multiplies 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 and and fit 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 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,
s1ands2(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
- Loss Functions asks why squared error, and what changes if you use absolute error or something else.
- Logistic Regression keeps the weighted sum but squashes it into a probability, for classification.
- Regularization: L1 and L2 adds a penalty on large weights (ridge, lasso) to fight overfitting and multicollinearity.
- Overfitting and the Bias–Variance Tradeoff uses polynomial regression to show what happens when a model is too flexible.
- Neural Networks stack many linear regressions with nonlinear functions in between.
- Time Series Forecasting forecasting often starts with linear regression on lagged values.
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
- Add a fifth student who practised 5 hours and scored 2 (perhaps they were ill). Recompute and by hand. How much does one outlier move the line?
- 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.)- Fit
LinearRegressionon the diabetes data using only thebmicolumn (X_tr[:, [2]]). What test do you get? What does that tell you about the other nine features?Hint for 1: the new averages are , . The slope collapses from 1.7 to 0.1.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
MLU-Explain: Linear Regression
A scrolling visual essay that builds linear regression from a scatter plot, with interactive fits and residuals.
An Introduction to Statistical Learning (with Python)
The friendliest rigorous introduction to classical ML, with Python labs. Free PDF.
Machine Learning Crash Course
Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.
StatQuest
Short, cheerful, very clear videos on statistics and nearly every ML algorithm.
scikit-learn: Linear Models
The user-guide chapter on ordinary least squares, ridge, lasso, elastic net and logistic regression, with the maths and runnable examples.
Stanford CS229: Machine Learning
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