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?
- The absolute-misses line
- The squared-misses line
- They move the same
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
- 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.
- Its gradient is \(\nabla L = -2X^\top (y - Xw)\) (chapter 2's chain rule on each square).
- Set it to zero: \(X^\top (y - Xw) = 0\), which rearranges to \(X^\top X w = X^\top y\).
- 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.
- 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?
- It sets weights to exactly zero, one after another
- It shrinks the weights
- It fits the training dots worse
Ridge shrinks all the weights a little; lasso turns the least useful ones off completely.
Why the absolute value makes exact zeros
- 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|\).
- 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.
- 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.
- 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.
- 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?
- The predictions get much worse
- Each copy gets half the old weight
- The predictions stay the same, but the two weights become huge and opposite
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
- Bends. A line can only add effects. If late trains depend on distance and hour together, a line can't see it unless you hand it a column that multiplies them. Trees (pages 5 to 7) find bends by themselves.
- Outliers. One typo (a day recorded as 30 million riders) pulls the line toward it, more the fewer rows you have. Fix the data, or use a loss that grows slower for big misses: absolute or Huber loss (
HuberRegressor). - Twins. With columns that nearly duplicate each other, \(X^\top X\) is almost singular (chapter L1), and the weights become noise even though the predictions are fine. Never read weights without ridge or without dropping one twin.
- Scale. Penalties compare weights, so columns must be on one scale first (
StandardScaler): otherwise a column in millimeters is penalized a thousand times less than one in meters. - Forever trends. \(w \cdot t\) keeps growing as \(t\) does. Past the training range, check whether the trend should still hold; often the answer is to predict a change, or cap it.
6. The knobs that matter
| Knob | In scikit-learn | What it does |
|---|---|---|
| The features | your columns | The real knob: a line is only as good as the columns you give it (products, squares, logs, one-hot categories). |
| Penalty price λ | alpha | Small: 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 values | Ridge, Lasso, ElasticNet(l1_ratio) | Ridge keeps every column and splits credit among twins; lasso picks a few columns; elastic net mixes the two. |
| Scaling | StandardScaler in a pipeline | Required for any penalty to be fair across columns. |
| Loss | HuberRegressor, QuantileRegressor | Squared 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