Ridge, Lasso and Elastic Net
Two problems from the last lessons share one cure. When features are strongly correlated, least-squares coefficients become huge and unstable; when a model has many features (a degree-2 expansion of 10 inputs already has 65), it overfits. Regularisation adds a penalty on the size of the weights to the loss, trading a little bias for a large drop in variance. The Machine Learning course introduces Ridge and Lasso with scikit-learn; here you implement both.
Three penalties
scikit-learn's objectives (the intercept is not penalised):
sets the strength and (l1_ratio) the mix. Note the different scaling: Ridge's is not divided by , Lasso's is, so the same number means different strengths in the two classes.
Ridge keeps a closed form. Setting the gradient to zero gives
and adding to every eigenvalue of makes the system well conditioned however correlated the features are. Ridge shrinks all coefficients towards zero but rarely makes one exactly zero. In Bayesian terms it is the MAP estimate under a Gaussian prior on the weights (MAP Estimation and Regularization).
Lasso has no closed form because has a corner at 0. Coordinate descent solves it one weight at a time: with the others fixed, the best is a soft-thresholded correlation,
Whenever the weight is set to exactly zero, which is why the lasso selects features. The corner is explained with subgradients in Subgradients, the algorithm in Coordinate Descent and The Lasso with ISTA and FISTA.
From scratch
Eight features, only three of which matter, and feature 1 is a near-copy of feature 0:
import numpy as np
from sklearn.linear_model import Ridge, Lasso
rng = np.random.default_rng(0)
n, p = 50, 8
X = rng.normal(size=(n, p))
X[:, 1] = X[:, 0] + rng.normal(scale=0.05, size=n) # feature 1 is almost a copy of feature 0
w_true = np.array([2.0, 0.0, 0.0, -1.5, 0.0, 0.0, 1.0, 0.0])
y = X @ w_true + rng.normal(scale=0.5, size=n)
Xc, yc = X - X.mean(axis=0), y - y.mean() # centre, so the intercept drops out
def ridge(Xc, yc, alpha):
return np.linalg.solve(Xc.T @ Xc + alpha * np.eye(Xc.shape[1]), Xc.T @ yc)
def lasso_cd(Xc, yc, alpha, sweeps=500):
"""Coordinate descent for (1/2n)||y - Xw||^2 + alpha ||w||_1 (scikit-learn's objective)."""
n = len(yc)
w = np.zeros(Xc.shape[1])
col_sq = (Xc ** 2).sum(axis=0) / n
for _ in range(sweeps):
for j in range(len(w)):
r_j = yc - Xc @ w + Xc[:, j] * w[j] # residual without feature j
rho = Xc[:, j] @ r_j / n
w[j] = np.sign(rho) * max(abs(rho) - alpha, 0) / col_sq[j] # soft-thresholding
return w
ols = np.linalg.lstsq(Xc, yc, rcond=None)[0]
print("true ", w_true.round(2))
print("OLS ", ols.round(2))
w_r = ridge(Xc, yc, 10.0)
print("ridge 10 ", w_r.round(2), " sklearn match:", np.allclose(w_r, Ridge(alpha=10.0).fit(X, y).coef_))
w_l = lasso_cd(Xc, yc, 0.1)
print("lasso 0.1 ", w_l.round(2), " sklearn match:", np.allclose(w_l, Lasso(alpha=0.1).fit(X, y).coef_, atol=1e-4))true [ 2. 0. 0. -1.5 0. 0. 1. 0. ]
OLS [ 4.17 -2.05 -0.03 -1.49 0.01 -0.04 1.03 0.06]
ridge 10 [ 0.92 0.89 0.04 -1.27 0.01 0.08 0.82 0.08] sklearn match: True
lasso 0.1 [ 1.96 0. 0. -1.4 0. 0. 0.92 0.01] sklearn match: True
Three different answers to the twin features:
- OLS gives them and . Their sum, about 2.1, is right (only the sum is identified when two columns are nearly equal), but each one alone is meaningless and would flip with a little more noise.
- Ridge splits the effect evenly (0.92 and 0.89) and shrinks every weight a little.
- Lasso keeps one twin (1.96), sets the other to exactly 0, and zeroes four of the five useless features. The price is some shrinkage of the true effects ( instead of ).
Both from-scratch versions match scikit-learn. Centring and first is what makes the unpenalised intercept drop out.
Choosing alpha by cross-validation
RidgeCV and LassoCV try a grid of strengths and keep the best by cross-validation. On the diabetes data, a degree-2 expansion overfits plain least squares; regularisation recovers it:
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.linear_model import RidgeCV, LassoCV, LinearRegression
from sklearn.model_selection import cross_val_score, KFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
X, y = load_diabetes(return_X_y=True)
cv = KFold(5, shuffle=True, random_state=0)
models = {
"OLS, 10 features": make_pipeline(StandardScaler(), LinearRegression()),
"OLS, 65 features (deg 2)": make_pipeline(PolynomialFeatures(2, include_bias=False), StandardScaler(), LinearRegression()),
"RidgeCV, 65 features": make_pipeline(PolynomialFeatures(2, include_bias=False), StandardScaler(), RidgeCV(alphas=np.logspace(-2, 3, 30))),
"LassoCV, 65 features": make_pipeline(PolynomialFeatures(2, include_bias=False), StandardScaler(), LassoCV(cv=5, random_state=0, max_iter=5000)),
}
for name, m in models.items():
print(f"{name:26s} CV R^2 {cross_val_score(m, X, y, cv=cv).mean():.3f}")
lasso = models["LassoCV, 65 features"].fit(X, y)[-1]
print("lasso alpha:", round(lasso.alpha_, 3), " non-zero coefficients:", int((lasso.coef_ != 0).sum()), "of 65")OLS, 10 features CV R^2 0.489
OLS, 65 features (deg 2) CV R^2 0.412
RidgeCV, 65 features CV R^2 0.475
LassoCV, 65 features CV R^2 0.489
lasso alpha: 2.971 non-zero coefficients: 16 of 65
The 65 squared and product features drop plain least squares from 0.489 to 0.412 (5-fold CV ). Ridge recovers most of that and the lasso all of it, keeping 16 of the 65 features. The inner RidgeCV/LassoCV search runs inside each outer fold, so the outer score is honest; the alpha printed at the end is from a final fit on all the data. On this data the interactions add little: the plain 10-feature model is just as good, a useful reminder that more features is not automatically better.
Strengths, weaknesses, when to use
| Ridge | Lasso | Elastic net | |
|---|---|---|---|
| effect | shrinks all weights | sets some weights to exactly 0 | both |
| correlated features | shares the weight | picks one, arbitrarily | groups them |
| solution | closed form | iterative (coordinate descent) | iterative |
| use when | many small effects, collinearity | you expect few relevant features, want selection | correlated groups of relevant features |
Always standardise before regularising: the penalty treats all weights alike, so a feature measured in grams would be penalised differently from the same feature in kilograms.
Pitfalls
- Forgetting to scale. The penalty's effect then depends on arbitrary units.
- Reading lasso's choice among twins as importance. Which of two correlated features survives can flip with a small change in data.
- Comparing alphas across classes. Ridge's and Lasso's are on different scales.
Practice
- Show that ridge's matrix is invertible for every .
Answer
is positive semidefinite, so its eigenvalues are . Adding shifts each to , so all eigenvalues are positive and the matrix is invertible (Positive Definite Matrices).
- In
lasso_cd, what happens to every weight when is larger than ?
Answer
Starting from , each has , so every update gives 0 and the solution stays at zero. This is where LassoCV starts its grid.
Test yourself
Which penalty can set coefficients exactly to zero?
- L2 (ridge)
- L1 (lasso)
- neither
- only an L2 penalty with a huge
Two features are almost identical. What does ridge regression do with them?
- Drops one
- Gives them roughly equal weights that sum to the shared effect
- Gives them huge opposite weights
- Raises an error
Why standardise features before ridge or lasso?
- The solvers need it to converge
- The penalty treats all weights equally, so their scale must be comparable
- It removes outliers
- It makes the model nonlinear