Deep Learning · Foundations: the linear model · Linear Regression · Interactive sheet

The
Linear Regression
Blueprint

Linear regression predicts a number as a weighted sum of the inputs plus a bias, ŷ = Xw + b: exactly one dense neuron with no activation. Its weights are the ones that make the squared prediction errors smallest, found in one shot by least squares or step by step by gradient descent.

Before you start: how to multiply a matrix by a vector (row times column), the derivative of x² (it is 2x), and what a mean (average) is.

Every number on this page is clickable. Every underlined term has a definition.

(n × d) · (d × 1) + b → (n × 1)
shape path
d + 1
parameters
n × d
multiply-adds per batch
20,640 × 8
benchmark data set
w = (XᵀX)⁻¹ Xᵀy
closed-form fit
01

Fitting a line to data: the oldest problem in machine learning

Given inputs and the numbers we want to predict, find the straight line (or flat plane) that misses the data by the least, where "miss" is measured by the squared error.

Which line is best? Score each candidate

mean squared error
–
this line
–

Orange sticks are the residuals: the vertical distance from each point to the line.

20,640 × 8
California Housing
ŷ = Xw + b
the whole model
1
layer
928 children, 205 families
Galton, 1886

Why it still matters

Least squares was invented to predict where comets would be. Two centuries later the same weighted sum sits at the end of almost every deep network, the same squared error is the default loss for predicting numbers, and the same gradient descent trains models with billions of weights.

timeline · click a chip
1805 1809 1886 1958 1960 1997
02

Walk one input through the model: features × weights + bias = prediction

Each bead is one step of the computation, from the design matrix to the weight update; scrub, click a bead (or use the arrow keys) or press play, and watch the shape of every tensor.
ŷ = Xw + b
input weights bias loss & gradient
California Housing100%
step scrubberX
Forward: multiply, add the bias, compare. Backward: one gradient, one update.
X
parameters so far
0
multiply-adds so far
0
A batch of 100 houses, each described by 5 features, goes through the model. How many multiply-adds does the prediction ŷ = Xw + b need?
Every row is a dot product of 5 features with 5 weights: 5 multiply-adds. 100 rows × 5 = 500, which is the n × d rule. The bias adds 100 plain additions on top.
03

The ideas that made it work: squared error, the gradient and the normal equation

Three ideas turn "draw a good line" into an exact procedure: square the misses, follow the slope of the loss downhill, or solve the slope = 0 equations in one go.
Idea 1 · squared error

Square the misses

residual r = y − ŷ1.5
red: r² (squared) · violet dashed: |r| (absolute)
L(w) = (1/n) Σ (yᵢ − ŷᵢ)²
Idea 2 · the gradient

Follow the slope downhill

weight w0.5
learning rate η0.05
Idea 3 · the normal equation

Solve slope = 0 in one go

correlation ρ of two features0.50
XᵀX / n =
(XᵀX)⁻¹ · n =
determinant 1 − ρ²
w = (XᵀX)⁻¹ Xᵀy

Setting the gradient ∇L = (2/n) Xᵀ(Xw − y) to zero gives XᵀXw = Xᵀy, the normal equation. When XᵀX is singular (two features carry the same information, or there are more features than rows) there is no unique answer, and gradient descent or ridge regularisation is the way out.

At the current weight the derivative ∂L/∂w is +3. Which way should gradient descent move w?
A positive slope means the loss goes up when w goes up, so we step the other way: w ← w − η · 3. Gradient descent always moves against the gradient.
04

The least-squares rule: minimise the sum of squared residuals

Drag the slope and intercept, switch between squared and absolute error, add an outlier, and compare the least-squares line with its alternative, the least-absolute-deviations line.
residual squares (L2) or residual sticks (L1)100%
slope w0.50
intercept b3.00
MSE (yours)
–
MAE (yours)
–
L2: L(w) = (1/n) Σ (yᵢ − ŷᵢ)²
L1: (1/n) Σ |yᵢ − ŷᵢ|
slope* = Σ(xᵢ − x̄)(yᵢ − ȳ) ÷ Σ(xᵢ − x̄)²

Why squares won. Squared error is smooth, so its minimum is where the gradient is zero, a linear equation solved in closed form. Gauss added that it is the most likely line when the noise is Gaussian. The price: one far-away point can drag the whole line. Toggle the outlier and compare how far each line moves.

A line leaves residuals 1, −2 and 1 on three points. What is its mean squared error?
Square first, then average: (1² + (−2)² + 1²) ÷ 3 = (1 + 4 + 1) ÷ 3 = 2. Averaging the raw residuals would give 0, which is why the signs must be removed first; 6 is the sum, not the mean.
05

Shapes by hand and by eye: X is n × d, w is d × 1, ŷ is n × 1

Do one tiny example on paper first, then let the calculator check any shape: the inner dimensions must match, and the outer ones give the result.

Worked example by hand: 3 houses, 2 features

Write the pieces and check the shapes: X = [[1, 2], [3, 1], [0, 4]], w = [2, −1]ᵀ, b = 0.5, targets y = [1, 5, −3]ᵀ
X is 3 × 2, w is 2 × 1: inner sizes 2 = 2 ✓ → Xw is 3 × 1
Row 1 · w, then add the bias
1·2 + 2·(−1) = 2 − 2 = 0 → 0 + 0.5 = 0.5
Row 2 · w, then add the bias
3·2 + 1·(−1) = 6 − 1 = 5 → 5 + 0.5 = 5.5
Row 3 · w, then add the bias: the prediction vector is complete
0·2 + 4·(−1) = −4 → −4 + 0.5 = −3.5 → ŷ = [0.5, 5.5, −3.5]ᵀ, 3 × 1
Residuals and the mean squared error
ŷ − y = [−0.5, 0.5, −0.5] → MSE = (0.25 + 0.25 + 0.25) ÷ 3 = 0.25
Gradient (2/n) Xᵀ(Xw + b − y): Xᵀ is 2 × 3, the residuals 3 × 1
Xᵀr = [1·(−0.5) + 3·0.5 + 0·(−0.5), 2·(−0.5) + 1·0.5 + 4·(−0.5)] = [1, −2.5] → × 2/3 = [0.667, −1.667]ᵀ, 2 × 1 like w
One gradient step with η = 0.1 (bias gradient (2/3)·(−0.5) = −0.333)
w = [2 − 0.067, −1 + 0.167] = [1.933, −0.833]ᵀ · b = 0.5 + 0.033 = 0.533

Redo it on paper before you reveal each line. Every prediction needs d = 2 multiply-adds, so the batch needs n × d = 3 × 2 = 6.

The shape calculator

(n × d) · (d × k) + b → (n × k) · with k = 1: (n × d) · (d × 1) + b → (n × 1)
outputs k1
prediction shape
20,640 × 1
one row of X times w gives one prediction · click to pause100%
X is 50 × 4. What is the shape of XᵀX, the matrix the normal equation inverts?
Xᵀ is 4 × 50 and X is 50 × 4; the inner 50s cancel and leave 4 × 4, one row and column per feature. That is why the closed form gets expensive with many features (d), not with many rows.
06

Where the parameters live: d weights and one bias

Every bar is computed from a small layer specification (inputs × outputs weights + outputs biases); click a bar for its arithmetic and compare the single linear layer with wider models.
100%
weightsbiases
click a bar

The arithmetic for that layer appears here.

Weights vs biases

Rule of thumb

d + 1

The 9 parameters of a California Housing model · click one

Each weight answers one question: how much does the prediction change when this feature grows by one unit and every other feature stays fixed?
A model has 20 features. You then collect ten times as many rows. How many parameters does the linear regression have now?
Parameters count features, not rows: d + 1 = 20 + 1 = 21, whether there are 1,000 rows or 10,000. More rows only make the estimates of those 21 numbers more reliable.
07

The family: multiple, polynomial, ridge, lasso and logistic regression

All variants keep the weighted sum; they change the features, the penalty or the output, and the table fits each one live on the same small synthetic data set.
variantfeatureslosslayersparameterstest scoreclosed form?
fit on 15 training points (filled), scored on 60 test points (hollow)100%
penalty strength λ (ridge, lasso)0.01

What to notice. Degree 9 on 15 points chases the noise (low training error, high test error). Ridge shrinks all weights a little; lasso sets some exactly to zero. Raise λ and watch the test score improve, then worsen again when the penalty is too strong.

Ridge regression adds λ‖w‖² to the loss. What happens to the normal equation?
Differentiating λ‖w‖² adds 2λw to the gradient, so the equation becomes (XᵀX + λI)w = Xᵀy. Adding λ to the diagonal makes the matrix invertible even when features are collinear. Lasso's |w| penalty is the one without a closed form.
08

The cost: closed form O(nd² + d³) against gradient descent O(nd) per step

Set the data size, the hardware speed and the batch size, and see when the exact one-shot solution beats thousands of cheap gradient steps, and when it becomes hopeless.
examples n20,640
features d8
throughput (TFLOPS)1
mini-batch size B256
gradient steps K1,000
one input
one full-batch step · O(nd)
one epoch, mini-batch
closed form · O(nd² + d³)
the full fit: K gradient steps vs one exact solve
operations to fit, as the number of features d grows (log–log, n fixed)100%
n = 1,000,000 rows and d = 100,000 features. Which fitting method is realistic?
The closed form needs n·d² + d³ ≈ 10¹⁶ + 10¹⁵ operations and a 100,000 × 100,000 matrix (80 GB in float64). One gradient step costs about 2·n·d = 2 × 10¹¹, so even 1,000 steps are 50 times cheaper.
09

Reuse and transfer: the linear layer inside every neural network and the linear probe

Every network ends in ŷ = Xw + b applied to learned features, so you can freeze a pretrained network and train only that last linear layer; click the blocks to choose what trains.

Choose a recipe

outputs k1

        

The dense layer is linear regression

A dense layer with one output and no activation computes ŷ = Xw + b, with d + 1 parameters and n × d multiply-adds per batch. Give it k outputs and it becomes k regressions side by side (d·k + k parameters); put a sigmoid after it and it is logistic regression; stack several with non-linear activations in between and you have a deep network.

A linear probe sits on 768-dimensional frozen features and predicts 3 classes. How many parameters does it train?
A d × k weight matrix plus k biases: 768 × 3 + 3 = 2,304 + 3 = 2,307. The frozen backbone contributes zero trainable parameters, which is why probes train in seconds.
10

History: Legendre, Gauss, Galton and the road to the perceptron

Click a point on the timeline for its story, then reproduce Galton's discovery: tall parents have children who are, on average, less extreme than themselves.
from least squares to the trainable neuron, 1795–2000100%
click a point

Galton's regression towards the mean

205 synthetic families shaped like Galton's table (not his raw data)100%
slope of the line through the means1.00
MSE (in²)
–
least-squares slope
–

Galton measured 928 children, 205 families. Children's deviations from the mean were about ≈ 2/3 of the mid-parent deviation, not 1: he called it "regression towards mediocrity". Slope 1 (dashed) would mean children are exactly as extreme as their parents.

With Galton's slope of about 2/3, a couple whose mid-parent height is 6 inches above average have children who are expected to be…
Prediction = mean + slope × deviation = mean + (2/3) × 6 = mean + 4 inches. Still tall, but closer to the mean: that pull towards the average is what "regression" originally meant.
11

Where it is used today: forecasting, baselines, econometrics and the final layer of deep nets

Linear regression rarely wins benchmarks on its own, but it is the first model anyone should fit, the tool economists trust for interpretable effects, and the last layer of most deep networks.
Sales, energy load and traffic forecasts often start as a linear regression on lagged values, calendar features (weekday, holiday) and prices. It trains in milliseconds, is easy to retrain every night and its errors are easy to explain to planners.
Before training a deep network on tabular data, fit a linear model on the same split. If the network cannot beat it clearly, the extra complexity is not paying off. On California Housing a linear baseline is the reference point that tree ensembles and networks are compared with.
Ordinary least squares with standard errors is the workhorse for estimating effects ("how much does one more year of schooling change wages, holding other factors fixed?"). Interpretation needs care: a weight measures association given the other features, not cause, unless the study design supports it.
Classifiers end in a dense layer (logits = hW + b) followed by softmax; regressors such as bounding-box heads or value functions end in a dense layer with no activation, trained with squared error. That last layer is exactly the model on this page, applied to learned features h.
To ask "does this layer of a language or vision model encode property X?", researchers freeze the model and fit a linear regression or logistic regression on the layer's activations. High probe accuracy means the information is linearly readable at that layer.

Successors · tap a card to flip

Why fit a linear regression before training a deep network on the same tabular data?
A baseline tells you what "good" means for this data. If a network with thousands of parameters only matches a model with d + 1 parameters, choose the simpler, more interpretable one.
12

Key takeaways

Eight sentences to remember; click each one for the evidence and the section where it is shown.
A single linear layer with identity activation; the shape path is (n × d) · (d × 1) + b → (n × 1). Section 02.
One weight per feature plus one bias: 9 for California Housing's 8 features. More data improves the estimates, not the count. Section 06.
Squaring removes signs and punishes big misses most; it is the maximum-likelihood choice under Gaussian noise, but sensitive to outliers. Sections 03 and 04.
Move against the gradient with a learning rate small enough to converge; too large and every step overshoots. Sections 03 and 05.
Collinear features or d > n make XᵀX singular; ridge (adding λI) or gradient descent are the fixes. Section 03.
Exact solve for few features, (mini-batch) gradient descent for many features or streaming data. Section 08.
"Linear" means linear in the weights. Section 07.
Legendre (1805) and Gauss (1809) gave us least squares; Galton (1886) the name; Rosenblatt and Widrow turned it into the trainable neuron. Sections 09 and 10.
13

Check your understanding

Five questions with instant feedback and an explanation for every answer; score 4 or more and the stamp is yours.
0 / 5
■ STAMPED · LINEAR REGRESSION BLUEPRINT · APPROVED
14

Glossary

Every term used on this page; type to filter and click a term to open its definition.