MLDay 11 of 50Supervised and Unsupervised Learning
Regularize with Ridge and Lasso
A degree-12 curve threads every training point, then misses new points badly.
A degree-12 curve threads every training point, then misses new points badly. You could drop back to a simpler curve, but then you lose shapes you might need. Regularization keeps the flexible model and charges it for big weights.
The idea
A wild, wiggly curve needs huge weights that cancel each other out. A smooth curve gets by with small ones. So add a penalty to the loss that grows with the size of the weights. Training now balances two goals: fit the training rows, and keep the weights small.
The penalty strength is called α (alpha). At α = 0 you get the plain, wiggly fit. As α grows, the curve calms down. It fits the training rows a little worse, which adds a little bias (error from a model too stiff to follow the data). But it swings far less from one sample to the next, which cuts variance (error from chasing noise). Day 10 introduced both. Push α too far and the curve goes flat: now bias wins.
There are two common penalties:
- Ridge (L2) charges the square of each weight. It shrinks every weight, but rarely to exactly 0.
- Lasso (L1) charges the absolute value. Its pull doesn't fade as a weight gets small, so it pushes unhelpful weights all the way to 0. That drops those features from the model.
The penalty treats every weight alike, so the features must share one scale first. A feature measured in large units gets a small weight and would barely be penalized. Standardize them, as in Day 9.
A tiny example
Two models fit the same training points:
| Model | Weights | Training MSE | Ridge penalty, α = 0.01 | Total |
|---|---|---|---|---|
| A (wiggly) | (8, −6) | 0.05 | 0.01 × (64 + 36) = 1.00 | 1.05 |
| B (smooth) | (2, −1) | 0.20 | 0.01 × (4 + 1) = 0.05 | 0.25 |
On training error alone, A wins (0.05 beats 0.20). With the penalty, B wins easily. Ridge accepts a slightly worse fit in exchange for much smaller weights.
The formula
Each loss is the usual mean squared error (MSE) plus a penalty on the weights:
| Symbol | Meaning |
|---|---|
| the loss that training makes small | |
| MSE | the mean of the squared residuals on the training rows |
| the penalty strength; 0 means no penalty | |
| the -th weight; the intercept is not penalized | |
| add up over every weight |
Worked: and give a ridge penalty of and a lasso penalty of .
Classifiers such as LogisticRegression use C instead, where C is 1 / strength. A smaller C means a
stronger penalty.
Try it
These are the tomato plants from Day 10, fitted at degree 12.
Tame the degree-12 wiggles
Round dots are the training points (the fit sees them); squares are validation points (held back). Raise the degree and watch both errors.
degree 12train RMSE 0.02validation RMSE 2.04weights' size ‖w‖ 3918.04
Fitted by least squares, with x rescaled to −1…1 first; ‖w‖ leaves out the intercept.
At α = 0 the curve hugs the 14 training plants and swings wildly in the gaps, so the validation error (on the 6 held-back plants) is large. Leave the degree at 12 and nudge α up a little: the swings flatten, the weights shrink, and the validation error drops. Then drag α to 10: the curve stiffens, training error rises to 0.73 and validation error climbs back to 0.48.
In code
A Pipeline chains steps into one model: here, make the powers to , standardize them, then fit.
Calling fit runs every step in order. Cross-validation refits the whole chain inside each fold, so the
scaler only ever sees that fold's training rows. That avoids the leakage from
Day 6.
# script_id: day_011_ridge_and_lasso/tame
import numpy as np
from sklearn.linear_model import Lasso, LinearRegression, Ridge
from sklearn.metrics import root_mean_squared_error
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
rng = np.random.default_rng(0) # Day 10's 20 tomato plants
litres = rng.uniform(0, 10, size=(20, 1))
kg = 1 + 1.2 * litres[:, 0] - 0.1 * litres[:, 0] ** 2 + rng.normal(0, 0.4, 20)
X = (litres - 5) / 5 # rescale to -1..1
def degree12(model): # x, x², …, x¹², scaled, then the model
return make_pipeline(PolynomialFeatures(12, include_bias=False), StandardScaler(), model)
for name, model in [("plain", LinearRegression()), ("ridge", Ridge()), # Ridge: alpha=1.0
("lasso", Lasso(alpha=0.01, max_iter=100_000))]:
pipe = degree12(model)
cv = -cross_val_score(pipe, X, kg, scoring="neg_root_mean_squared_error").mean()
train = root_mean_squared_error(kg, pipe.fit(X, kg).predict(X))
w = pipe[-1].coef_ # the last step's 12 weights
print(f"{name:5} train {train:.2f} CV {cv:.2f} largest |w| {abs(w).max():5.1f} zeros {(w == 0).sum()}")
print("powers lasso kept:", (np.flatnonzero(w) + 1).tolist())
plain train 0.17 CV 1.52 largest |w| 176.3 zeros 0
ridge train 0.23 CV 0.28 largest |w| 0.5 zeros 0
lasso train 0.22 CV 0.26 largest |w| 0.8 zeros 9
powers lasso kept: [1, 2, 3]
The plain fit is Day 10's degree-12 model; the extra scaling step moves its CV score only from 1.53 to 1.52. The penalty raised the training error by 0.06 but cut the cross-validated error from 1.52 to 0.28. The largest weight fell from 176 to 0.5. Lasso dropped 9 of the 12 powers and kept , and : the degree-3 shape Day 10 found by trying every degree.
Which α is best? Don't guess: let cross-validation choose. GridSearchCV runs 5-fold CV for each value in a
list, then refits the best one on all the rows. A setting inside a pipeline is named <step>__<parameter>,
and make_pipeline names each step after its class in lower case.
# script_id: day_011_ridge_and_lasso/tame
from sklearn.model_selection import GridSearchCV
grid = {"ridge__alpha": [1e-6, 1e-4, 1e-3, 1e-2, 0.1, 1, 10, 100]}
search = GridSearchCV(degree12(Ridge()), grid, scoring="neg_root_mean_squared_error")
search.fit(X, kg) # 5-fold CV per α, then a refit on all rows
for a, s in zip(grid["ridge__alpha"], search.cv_results_["mean_test_score"]):
print(f"α = {a:<6g} CV RMSE {-s:.2f}")
print("best α:", search.best_params_["ridge__alpha"])
α = 1e-06 CV RMSE 0.59
α = 0.0001 CV RMSE 0.44
α = 0.001 CV RMSE 0.34
α = 0.01 CV RMSE 0.29
α = 0.1 CV RMSE 0.30
α = 1 CV RMSE 0.28
α = 10 CV RMSE 0.38
α = 100 CV RMSE 0.60
best α: 1
The error falls from 0.59 to a low of 0.28 at α = 1, then climbs to 0.60 as the penalty flattens the curve.
Here the default, alpha=1.0, happens to win, but you only know that because CV checked.
search is now a fitted model, and search.predict uses the winner.
Quick check
Quick check
1. The weights are w = (3, 0) and α = 0.1. What is the ridge penalty?
2. You have 200 features and want a model that uses only the useful few. Which penalty fits?
3. Why put StandardScaler inside the Pipeline instead of scaling all the rows first?
Next
Day 12: Logistic Regression turns a weighted sum into a
probability for yes/no questions, with this same penalty set by C.