Sub topic 15
Elastic net: mixing L1 and L2
This chapter assumes you know ridge (L2) and lasso (L1) regression, how to use cross_val_score or a *CV estimator, and why penalised models need scaled features. Elastic net combines both penalties in one model. It keeps lasso's ability to zero out coefficients and adds ridge's stability when features are correlated.
Why lasso alone is not always enough
Lasso has two weaknesses that elastic net addresses.
- Correlated features. If three features carry nearly the same signal, lasso tends to keep one and set the others to zero. Which one it keeps can change with a different sample or a different cross-validation fold. The model is sparse, but the choice is unstable.
- More features than samples. When there are more features than rows (p > n), lasso can select at most n features. If more than n features really matter, it must drop some of them.
Ridge handles correlated features well because it spreads weight across them. But it never sets a coefficient to exactly zero, so it gives no feature selection. Elastic net sits between the two.
The elastic net objective
Scikit-learn minimises this loss for ElasticNet:
- Loss =
(1 / (2n)) * ||y - Xw||²+alpha * l1_ratio * ||w||₁+0.5 * alpha * (1 - l1_ratio) * ||w||²
There are two hyperparameters.
alphasets the overall penalty strength, as in ridge and lasso.l1_ratiosets the mix, from 0 (pure L2) to 1 (pure L1).
At l1_ratio=1 you get lasso. As l1_ratio falls toward 0, the model behaves more like ridge.
What the mix does to coefficients
The L1 part pushes small coefficients to exactly zero, which gives sparsity. The L2 part makes the loss strictly convex in the weights and penalises large weights. For a group of highly correlated features, this encourages the model to give them similar coefficients instead of picking one. This is often called the grouping effect.
| `l1_ratio` | Behaviour | Typical use |
|---|---|---|
| Close to 0 | Mostly ridge. Few exact zeros. | Many correlated features, selection not needed |
| Around 0.5 | Balanced mix | Default starting point when unsure |
| Close to 1 | Mostly lasso. Many exact zeros. | Features are mostly independent, a sparse model is the goal |
| Exactly 1 | Lasso | Use `Lasso` or `LassoCV` directly |
Worked example: correlated features
The next script builds three noisy copies of one underlying signal plus seven pure-noise features. It then fits LassoCV and ElasticNetCV and prints the coefficients. Scaling sits inside the pipeline, so each fit of the model learns its scaling from training data only.
import numpy as np
from sklearn.linear_model import ElasticNetCV, LassoCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
n = 100
base = rng.normal(size=n)
# Three noisy copies of the same signal, then seven irrelevant features.
X_corr = np.column_stack([base + rng.normal(0, 0.1, size=n) for _ in range(3)])
X_noise = rng.normal(size=(n, 7))
X = np.hstack([X_corr, X_noise])
y = 3 * base + rng.normal(0, 0.5, size=n)
lasso = make_pipeline(StandardScaler(), LassoCV(cv=5, random_state=0))
enet = make_pipeline(
StandardScaler(),
ElasticNetCV(l1_ratio=[0.2, 0.5, 0.8, 0.95], cv=5, random_state=0),
)
lasso.fit(X, y)
enet.fit(X, y)
print("lasso coef:", np.round(lasso[-1].coef_, 2))
print("enet coef:", np.round(enet[-1].coef_, 2))
print("lasso alpha:", round(lasso[-1].alpha_, 4))
print("enet alpha:", round(enet[-1].alpha_, 4), "l1_ratio:", enet[-1].l1_ratio_)When you run it, look at the first three coefficients, which belong to the correlated group. Lasso usually concentrates weight on one or two of them. Elastic net usually shares the weight more evenly. The seven noise features should be at or near zero in both models. The exact numbers depend on the random seed, so compare the pattern, not the digits.
Tuning two hyperparameters
You now tune alpha and l1_ratio together. The tools differ in how much they do for you.
ElasticNetCVtakes a list ofl1_ratiovalues. For each one it builds a path ofalphavalues automatically and picks the best pair by cross-validation. This is the fastest route.GridSearchCVoverElasticNetworks too. Use it when you want a custom scoring metric or a shared pipeline.- Search
alphaon a log scale, and put morel1_ratiocandidates near 1. Values close to 1 behave similarly to each other at the low end but differ more near lasso. Scikit-learn's docs suggest lists such as[.1, .5, .7, .9, .95, .99, 1].
As in earlier chapters, tune on training folds only. The test set is used once, at the end.
Gotchas
- Scale first. Both penalties act on coefficient size, so features on large scales get penalised less than features on small scales. Use
StandardScalerinside the pipeline. l1_ratio=0is not recommended. Scikit-learn warns thatElasticNetis numerically unreliable at very smalll1_ratiovalues. If you want pure L2, useRidge.- Extra shrinkage. Applying both penalties shrinks coefficients more than either alone would at the same
alpha. The original elastic net paper (Zou and Hastie, 2005) discusses this "double shrinkage". In practice the CV-chosenalphacompensates, but coefficients are biased toward zero and should not be read as unbiased effect sizes. - Cost. Searching two hyperparameters multiplies the number of fits. With 5 folds and 4
l1_ratiovalues,ElasticNetCVfits the wholealphapath 20 times. - Classification.
LogisticRegressionoffers the same penalty withpenalty="elasticnet",solver="saga", and anl1_ratiovalue. In that class, strength is controlled byC, which is the inverse of regularisation strength. - Do not expect large gains for free. If your features are nearly independent, elastic net and lasso perform about the same. The benefit shows up with correlated groups and p > n.
When to choose it
- Start with ridge if you do not need feature selection.
- Use lasso if you need a sparse model and your features are mostly independent.
- Use elastic net if you need sparsity and you know or suspect groups of correlated features, or if lasso's selected set changes a lot between folds.
A quick check for instability is to fit lasso on several bootstrap samples or CV folds and see whether the nonzero set stays the same. If it changes a lot, try elastic net.
Exercise
You fit a lasso model on gene-expression data with 50 samples and 2,000 features. Many features are strongly correlated. The model keeps at most 50 features, and the chosen set changes from fold to fold. Which model would you try next, and which two hyperparameters would you tune?
Show answer
Try elastic net. Lasso can select at most n = 50 features and picks arbitrarily among correlated ones, while the L2 term in elastic net removes that limit and shares weight across correlated features, which stabilises the selected set. Tune alpha (overall strength) and l1_ratio (the L1/L2 mix), for example with ElasticNetCV inside a pipeline that scales the features, using cross-validation on training data only.
Exercise
Why does elastic net still produce exact zeros even though it includes an L2 term?
Show answer
The L1 term has a constant-size gradient pull toward zero (the penalty has a corner at zero), so any coefficient whose pull from the data loss is smaller than the L1 penalty is set exactly to zero. The L2 term only adds a smooth shrinkage, which does not remove this corner. Elastic net therefore keeps sparsity as long as l1_ratio is greater than 0.