AI from scratch · Model zoo 1 of 10 · Linear regression, ridge and lasso

Linear regression, ridge and lasso

The oldest model in the zoo, and still the first one to fit: predict a number as a weighted sum of the columns. This page is the first of ten, one per popular model, all built the same way: the idea in one picture, how it learns, the algorithm in about 30 lines of NumPy next to the library call, where it shines and where it breaks (measured, on the course's data), and the knobs that matter. Chapter 2 and chapter 11 met lines already; here you see why they behave as they do.

1. The idea in one picture: the least total area of squares

Drag the dots. The line is the one that makes the total area of the yellow squares as small as possible: each square's side is a dot's vertical miss (its residual), so its area is the residual squared. That's all "least squares" means.

Predict, then try it: press add an outlier (one dot far above the rest). Which line moves more toward it?

A miss of 3 costs 9 squared but only 3 absolute. Least squares will make every other dot a little worse to shrink the outlier's huge square, so one bad row drags the whole line. The absolute line only cares about how many dots sit above or below it (it's a median), so it shrugs the outlier off.

Linear regression picks the weights that make the total of the squared misses as small as possible, and squaring makes big misses dominate.

2. How it learns: one equation, no loop

Put the inputs in a matrix \(X\) (a row per example, a column per feature, plus a column of ones for the intercept) and the targets in \(y\). The prediction is \(Xw\). Most models need gradient descent; this one has a closed form, the normal equation:

\[ \text{minimize } \lVert y - Xw \rVert^2 \quad\Longrightarrow\quad X^\top X\, w = X^\top y \]

It's a square system of equations (one equation per weight), which chapter L1 taught you to solve: np.linalg.solve(X.T @ X, X.T @ y). On subway ridership (2021 to 2023, by weekday plus a yearly trend) it gives 0.57 million more riders per day each year, Saturdays 0.73 million below Mondays and Sundays 1.15 million below: each weight reads as "this column, all else equal".

Why the normal equation is the minimum
  1. The loss \(L(w) = \lVert y - Xw \rVert^2\) is a sum of squares of things linear in \(w\): a bowl (calculus 5: a convex function), so wherever its gradient is zero is the bottom.
  2. Its gradient is \(\nabla L = -2X^\top (y - Xw)\) (chapter 2's chain rule on each square).
  3. Set it to zero: \(X^\top (y - Xw) = 0\), which rearranges to \(X^\top X w = X^\top y\).
  4. Read \(X^\top (y - Xw) = 0\) in words: the residuals are perpendicular to every column of \(X\). If they leaned toward some column, adding a bit more of that column would shrink them.
  5. So the prediction \(Xw\) is the shadow (projection) of \(y\) onto the space the columns can reach: the closest point, in plain distance, that a weighted sum of the columns can make.

3. Ridge and lasso: a price on big weights

Ten dots from a gentle curve, and a polynomial of degree 9 (nine weights, for \(x\) to \(x^9\)). Unpenalized, it threads every dot with wild swings and huge weights (chapter 11's overfitting). A penalty adds a price on the weights to the loss, and the slider sets the price \(\lambda\):

\[ \text{ridge: } \lVert y - Xw \rVert^2 + \lambda \textstyle\sum_j w_j^2 \]

\[ \text{lasso: } \tfrac{1}{2}\lVert y - Xw \rVert^2 + \lambda \textstyle\sum_j |w_j| \]

Slide λ up slowly with lasso, then with ridge, and watch the bars. What does lasso do that ridge doesn't?

Ridge shrinks every weight smoothly toward zero but almost never reaches it. Lasso drops whole features: at a high enough price, a weight's small help isn't worth any of its cost, so it sits at exactly 0. That's why lasso doubles as feature selection.

Ridge shrinks all the weights a little; lasso turns the least useful ones off completely.

Why the absolute value makes exact zeros
  1. Look at one weight \(w\) with everything else fixed. Its part of the lasso loss is a parabola \(\tfrac{a}{2}(w - z)^2\) (where \(z\) is the weight it would like without a penalty) plus \(\lambda |w|\).
  2. Away from 0, \(\lambda |w|\) has slope \(\pm\lambda\): a constant pull toward zero, however small \(w\) is. Ridge's \(\lambda w^2\) has slope \(2\lambda w\), which fades as \(w\) shrinks, so it never quite gets there.
  3. At \(w = 0\) the absolute value has a corner. Zero is the minimum whenever the parabola's slope there, \(a z\), is smaller than \(\lambda\) in size: the pull of the data can't beat the constant pull of the penalty.
  4. Solving gives the soft threshold: \(w = \operatorname{sign}(z)\max(|z| - \lambda / a, 0)\). Shrink by a fixed amount, and anything that would cross zero stops at zero.
  5. Lasso fits by applying that to one weight at a time, over and over (coordinate descent): the code below does exactly that. Calculus 5 shows the same thing as a diamond's corners touching the loss's ellipses.

4. Build it: the normal equation, ridge and lasso in NumPy

On subway ridership from 2021 to 2023: the columns are a yearly trend and one column per weekday. Each method is a few lines; scikit-learn's versions should match to the third decimal.

5. Where it shines, where it breaks

Shines: it trains in a millisecond, needs few rows, can't overfit much with few columns, and every weight is a sentence you can say out loud. It's the baseline every other model on these pages has to beat, and on the bank-call data from the features lesson, logistic regression (page 2, the same idea for yes/no) ties or beats every boosted-tree library. It's also the only model in the zoo that extrapolates: it keeps going past the data instead of going flat.

That last strength is also a weakness. Trained on 2021 to 2023, when ridership was recovering fast, the line predicts 2024 by continuing the climb; ridership leveled off. Its error on 2024 was 0.56 million riders a day, while boosted trees (which go flat past the data) missed by 0.34 million.

Add an exact copy of the trend column (plus a little noise) and refit. What happens to the predictions and the two weights?

Measured: 3.52 and −2.95 (the old weight was 0.57), and across 20 bootstrap resamples the trend weight swung from −28 to +27, with the same test error each time. Any split of the work between twins predicts the same, so the tiny noise decides. Ridge's price on big weights picks the even split: 0.28 each, between 0.27 and 0.30 on every resample.

A line is fast, readable and extrapolates; it breaks on bends it wasn't given features for, on outliers, and on near-duplicate columns.

Where it breaks, and what people do

6. The knobs that matter

KnobIn scikit-learnWhat it does
The featuresyour columnsThe real knob: a line is only as good as the columns you give it (products, squares, logs, one-hot categories).
Penalty price λalphaSmall: fits the training data closely. Large: smaller weights, a smoother, more stable model. Choose it on validation data (RidgeCV, LassoCV), on a log scale.
Squares or absolute valuesRidge, Lasso, ElasticNet(l1_ratio)Ridge keeps every column and splits credit among twins; lasso picks a few columns; elastic net mixes the two.
ScalingStandardScaler in a pipelineRequired for any penalty to be fair across columns.
LossHuberRegressor, QuantileRegressorSquared loss chases outliers; Huber treats big misses as absolute; quantile loss predicts a median or a 90th percentile.

Next in the zoo: the same weighted sum, squashed into a probability, for yes/no questions.

All chapters: AI from scratch. Ridership: MTA daily ridership, data.ny.gov.

Last updated