Worked Example: Taming a Polynomial Fit with Ridge, Lasso and Elastic Net
Take an overfitting degree-12 polynomial and regularise it with Ridge, Lasso and Elastic Net: sweep the strength on a log scale, read what each penalty does to the coefficients, check how stable Lasso selection is, and choose by cross-validation before testing once.
Contentsand lesson path
On this page
- The problem
- Step 1: The unregularised fit
- Step 2: Ridge, with alpha on a log scale
- Step 3: Lasso sets coefficients to zero
- Step 4: Selection stability with Elastic Net
- Step 5: Choose by cross-validation, then test once
- Check your understanding
- Apply it
- Review prompt
Lessons of Machine Learning Fundamentals
- From Business Question to Learning Task Concept · 20 min
- The Estimator Contract: fit, predict, score Concept · 15 min
- Lab: Baselines First with Dummy, Linear and Neighbour Models Lab · 30 min
- Underfitting, Overfitting and Learning Curves Concept · 20 min
- Worked Example: Taming a Polynomial Fit with Ridge, Lasso and Elastic Net Worked example · 25 min
- Check: Framing, Baselines and Generalization Knowledge check · 8 questions
What you will learn
- Diagnose underfitting and overfitting from training versus validation error and learning curves, and explain the bias-variance trade-off.
- Apply L1 (Lasso), L2 (Ridge) and Elastic Net regularization to a linear model with polynomial features, select its strength on validation data, and explain its effect on model coefficients.
Prerequisites: Data Handling
01. The problem
In the previous lesson a high-degree polynomial overfitted a noisy sine wave. Suppose you cannot collect more data. Can you keep the flexible model and still stop it from fitting noise? Regularisation does this: it adds a penalty on the size of the coefficients to the loss, so the model only uses large coefficients when the data clearly supports them. The penalty strength is a hyperparameter called alpha in scikit-learn.
There are three common penalties for linear models:
- Ridge (L2) adds alpha times the sum of squared coefficients.
- Lasso (L1) adds alpha times the sum of absolute coefficients.
- Elastic Net mixes the two;
l1_ratiosets the share of L1 (1.0 is pure Lasso).
The data: 40 training rows of y = sin(2πx) plus noise (standard deviation 0.3, so the best possible MSE is about 0.09), plus separate validation and test sets of 200 rows. The model: polynomial features up to x¹², scaled, then a linear model. Tested with Python 3.12 and scikit-learn 1.9.
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
def make_data(n, seed):
rng = np.random.default_rng(seed)
x = rng.uniform(0, 1, n)
y = np.sin(2 * np.pi * x) + rng.normal(0, 0.3, n)
return x.reshape(-1, 1), y
X_train, y_train = make_data(40, seed=10)
X_val, y_val = make_data(200, seed=11)
X_test, y_test = make_data(200, seed=12)
def poly(model, degree=12):
# scale AFTER expanding, so every power of x is penalised on the same scale
return make_pipeline(
PolynomialFeatures(degree, include_bias=False), StandardScaler(), model
)The order of steps matters. A penalty compares coefficients with each other, so the features must be on the same scale; otherwise a feature measured in small units needs a large coefficient and is punished more for no good reason. include_bias=False leaves out a column of ones, because the linear model fits its own intercept, which scikit-learn does not penalise.
02. Step 1: The unregularised fit
Start with plain least squares, to have something to compare against.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error as mse
from setup import X_train, X_val, poly, y_train, y_val
model = poly(LinearRegression()).fit(X_train, y_train)
coef = model[-1].coef_
print("train MSE", round(mse(y_train, model.predict(X_train)), 3),
"| val MSE", round(mse(y_val, model.predict(X_val)), 3))
print("largest |coefficient|:", f"{np.abs(coef).max():,.0f}")train MSE 0.047 | val MSE 1.114
largest |coefficient|: 778Training MSE 0.047 is below the noise level and validation MSE 1.114 is more than ten times the noise: textbook overfitting. The coefficients explain why. The powers of x are strongly correlated with each other (x¹¹ and x¹² look almost the same on [0, 1]), so the fit can add a huge positive multiple of one and a huge negative multiple of the other. The two almost cancel on the training points and swing wildly between them.
03. Step 2: Ridge, with alpha on a log scale
The useful values of alpha span many orders of magnitude, and what matters is the ratio between two values, not their difference: going from 0.001 to 0.01 changes the model about as much as going from 1 to 10. So search on a log scale with np.logspace, which here gives nine values from 10⁻⁶ to 10². Score each on the validation set, never on the test set.
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error as mse
from setup import X_train, X_val, poly, y_train, y_val
print(" alpha train MSE val MSE largest |coef|")
for alpha in np.logspace(-6, 2, 9): # 1e-6, 1e-5, ..., 1e2
model = poly(Ridge(alpha=alpha)).fit(X_train, y_train)
coef = model[-1].coef_
print(f"{alpha:8.0e} {mse(y_train, model.predict(X_train)):10.3f} "
f"{mse(y_val, model.predict(X_val)):8.3f} {np.abs(coef).max():15.2f}") alpha train MSE val MSE largest |coef|
1e-06 0.048 0.129 28.98
1e-05 0.049 0.139 14.31
1e-04 0.049 0.123 7.95
1e-03 0.051 0.126 3.42
1e-02 0.053 0.131 2.88
1e-01 0.073 0.165 1.48
1e+00 0.112 0.231 0.53
1e+01 0.150 0.225 0.36
1e+02 0.352 0.382 0.12Even alpha = 10⁻⁶ cuts validation MSE from 1.114 to 0.129: the cancelling giant coefficients rested on directions the data barely determined, and a tiny penalty is enough to remove them. As alpha grows, training error rises steadily, because the model is allowed less freedom, and the largest coefficient shrinks smoothly. Validation error is lowest around 10⁻⁴ to 10⁻³ and then rises: from alpha = 0.1 onwards the penalty is so strong that the model underfits, and at 100 both errors are high and close, the signature of high bias. Ridge shrinks every coefficient but does not set any of them exactly to zero.
04. Step 3: Lasso sets coefficients to zero
The L1 penalty behaves differently. Its slope does not shrink near zero the way the squared penalty does, so for a feature that helps only a little, the cheapest option is to drop it entirely. Lasso therefore performs feature selection: as alpha grows, more coefficients become exactly zero. max_iter is raised because Lasso is solved by coordinate descent, which needs many passes when features are correlated.
import numpy as np
from sklearn.linear_model import Lasso
from sklearn.metrics import mean_squared_error as mse
from setup import X_train, X_val, poly, y_train, y_val
print(" alpha val MSE non-zero coefficients (of 12)")
for alpha in np.logspace(-4, 0, 5):
model = poly(Lasso(alpha=alpha, max_iter=200_000)).fit(X_train, y_train)
kept = np.flatnonzero(model[-1].coef_) + 1 # which powers of x survive
print(f"{alpha:8.0e} {mse(y_val, model.predict(X_val)):8.3f} "
f"{len(kept):2d} powers {kept.tolist()}") alpha val MSE non-zero coefficients (of 12)
1e-04 0.127 6 powers [1, 2, 3, 5, 6, 11]
1e-03 0.123 5 powers [1, 2, 6, 7, 12]
1e-02 0.202 3 powers [1, 2, 7]
1e-01 0.293 2 powers [1, 12]
1e+00 0.673 0 powers []At alpha = 0.001 Lasso matches the best Ridge score with only 5 of the 12 powers. At alpha = 1 every coefficient is zero and the model predicts the intercept, the mean of the training targets, everywhere. Look at which powers survive: [1, 2, 3, 5, 6, 11], then [1, 2, 6, 7, 12]. A small change in alpha swaps x¹¹ for x¹² and x³ for x⁷, and drops x⁵. Do not read the Lasso's choice as "x⁷ matters and x³ does not"; when features are this correlated, which one it keeps is close to arbitrary.
05. Step 4: Selection stability with Elastic Net
Measure that instability. Draw 30 bootstrap resamples of the training rows (sample 40 rows with replacement, so each resample is a slightly different dataset), fit Lasso and Elastic Net with l1_ratio=0.5 on each, and count how often each power is kept.
import numpy as np
from sklearn.linear_model import ElasticNet, Lasso
from setup import X_train, poly, y_train
rng = np.random.default_rng(0)
models = {"lasso": Lasso(alpha=0.01, max_iter=200_000),
"elastic net": ElasticNet(alpha=0.01, l1_ratio=0.5, max_iter=200_000)}
chosen = {name: np.zeros(12, dtype=int) for name in models}
for _ in range(30): # 30 bootstrap resamples
rows = rng.integers(0, len(y_train), len(y_train))
for name, model in models.items():
fitted = poly(model).fit(X_train[rows], y_train[rows])
chosen[name] += fitted[-1].coef_ != 0
for name, counts in chosen.items():
print(f"{name:<12} times each power x^1..x^12 was kept (of 30):")
print(" ", counts.tolist())lasso times each power x^1..x^12 was kept (of 30):
[18, 27, 0, 0, 0, 5, 20, 12, 2, 2, 0, 0]
elastic net times each power x^1..x^12 was kept (of 30):
[28, 30, 17, 0, 8, 26, 30, 27, 13, 4, 1, 4]Lasso keeps x⁸ in 12 of 30 resamples and x⁶ in 5: the set of selected features changes from one sample to the next. Elastic Net keeps more features, and keeps them more consistently: x¹, x², x⁶, x⁷ and x⁸ appear in 26 or more resamples. The L2 part of its penalty prefers to spread weight over a group of correlated features instead of betting on one, while the L1 part still removes features that do not help (x⁴ never survives). When you want a sparse model whose selected features you can report with some confidence, Elastic Net is usually the safer choice on correlated data.
06. Step 5: Choose by cross-validation, then test once
With only 40 training rows, one validation split is a noisy judge. A sturdier way to choose alpha is k-fold cross-validation: split the development data (training plus validation rows) into 5 folds, train on 4 and score on the fifth, rotate, and average. GridSearchCV does this for every value in a grid and then refits the best setting on all development data. Because the pipeline is the estimator, the scaler is refitted inside every fold. Parameter names use the step name, two underscores and the parameter, as in ridge__alpha.
import numpy as np
from sklearn.linear_model import ElasticNet, Lasso, Ridge
from sklearn.metrics import mean_squared_error as mse
from sklearn.model_selection import GridSearchCV, KFold
from setup import X_test, X_train, X_val, poly, y_test, y_train, y_val
X_dev, y_dev = np.vstack([X_train, X_val]), np.concatenate([y_train, y_val])
cv = KFold(5, shuffle=True, random_state=0)
alphas = np.logspace(-4, 1, 11) # 1e-4 ... 1e1, evenly on a log scale
searches = {
"ridge": (Ridge(), {"ridge__alpha": alphas}),
"lasso": (Lasso(max_iter=200_000), {"lasso__alpha": alphas}),
"elastic net": (
ElasticNet(max_iter=200_000),
{"elasticnet__alpha": alphas, "elasticnet__l1_ratio": [0.2, 0.5, 0.8]},
),
}
for name, (model, grid) in searches.items():
search = GridSearchCV(poly(model), grid, cv=cv, scoring="neg_mean_squared_error")
search.fit(X_dev, y_dev)
best = {k.split("__")[1]: round(float(v), 5)
for k, v in search.best_params_.items()}
kept = int(np.count_nonzero(search.best_estimator_[-1].coef_))
test = mse(y_test, search.predict(X_test))
print(f"{name:<12} best {best} non-zero {kept:2d} test MSE {test:.3f}")ridge best {'alpha': 0.01} non-zero 12 test MSE 0.099
lasso best {'alpha': 0.00032} non-zero 4 test MSE 0.098
elastic net best {'alpha': 0.0001, 'l1_ratio': 0.8} non-zero 8 test MSE 0.098All three regularised models land at a test MSE of about 0.098, close to the noise floor of 0.09, against 1.114 without regularisation. Here they predict equally well, so choose on other grounds: Lasso uses 4 features, Ridge keeps all 12 small, and Elastic Net sits in between. Note that the best Elastic Net alpha is the smallest value in the grid. When the winner sits at the edge of the grid, the true best value may lie beyond it; extend the grid in that direction and search again (here smaller values trigger convergence warnings, which is itself a hint that very weak L1 penalties are hard to solve on such correlated features).
07. Check your understanding
08. Apply it
For the practice project, add a regularised model to your comparison. On your practice dataset (or load_diabetes), build a pipeline of PolynomialFeatures(2), StandardScaler and ElasticNet, search alpha on np.logspace(-4, 1, 11) and l1_ratio in [0.2, 0.5, 0.8] with 5-fold cross-validation, and report: the best setting, how many coefficients are non-zero, the cross-validated score next to your unregularised model, and one sentence on whether the best alpha lies at the edge of your grid.
09. Review prompt
Without looking back, explain: what Ridge and Lasso each do to coefficients as alpha grows; why alpha is searched on a log scale and chosen on validation data or by cross-validation; why features must be scaled before a penalty; and why Elastic Net gives more stable feature selection than Lasso when features are correlated.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.