Skip to content

Elastic net in practice

Ridge, lasso or a mix, chosen by cross-validation. Use the elastic net when features pile up, and know what a selected feature does and doesn't mean.

Applied ~10 min8 steps

What runs in CodeSplash

You will be able to

  • Choose the penalty and mixture with cross-validation
  • Decide when an elastic net will beat an unpenalized model
  • Avoid over-reading the features a lasso selects

Read first

01

Two settings

Read

Elastic net has two hyperparameters: Penalty (λ), how much you charge for size, and L1 share (ρ), which mixes lasso and ridge.

A sensible order: start at ρ=0.5\rho = 0.5, search λ\lambda on a log scale across several orders of magnitude, then try ρ\rho near 0 and 1. It's the fastest serious learner in the gallery, so you can afford a wide search.

02

When it pays

Predict

Predict first

Ozone has 4 features and chick weights 5 design columns, against hundreds of rows at most. You swap an unpenalized linear model for an elastic net on each. What happens to RMSE?

A clear win on bothA small change on bothA big win on chick weights only
Reveal

A small change on both. Ozone: 22.9 to 22.8. Chick weights, with whole birds held out: 39.9 to 39.1. Few features for this many rows leave little variance to remove. The win comes when columns are many or correlated.

03

Feel the mixture

Explore

Set Correlation between predictors high. Now switch Penalty between the three settings, and roll Data several times. Does the lasso keep the same columns?

DExplorable · Regularization paths

What happens to each coefficient as the penalty gets stronger?

Three of the eight predictors really matter. How many coefficients will be exactly zero at this penalty?

4
How sure?

Penalty

−0.50
0.90
60
2.0
this penaltybest

Blue paths are the three predictors that matter; gray are the five that don't. Below, training error (orange) and new-data error (blue).

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Ridge spreads weight over correlated columns. The lasso tends to pick one and can change its mind with new data. The elastic net tends to keep correlated groups.

04

Selected isn't the same as true

Read

A coefficient of zero means: at this penalty, on these rows, this column wasn't needed given the others. It doesn't mean that the column has no relationship with the target.

If you want to report which features matter with uncertainty, use Penalized regression in Analyze, or check stability across seeds. Predict's job here is prediction.

05

Beyond numbers

Read

The same penalty works for classes. On penguins, a lasso on 9 design columns has a cross-validated log loss of 0.0619. A ridge model with balanced class weights on Pima, on 4 features, has an AUC of 0.855, against 0.858 for the elastic net on all seven.

The three features left out carried little. That's the kind of question the penalty lets you ask cheaply.

06

Check your understanding

Checkpoint

Check yourself

What scale should you search Penalty (λ) on?

Show the answer

Answer: a

A change from 0.001 to 0.01 matters as much as one from 0.1 to 1. The app's tune space for this option is on a log scale.

Check yourself

Which situation most favors an elastic net over plain logistic regression?

Show the answer

Answer: b

With many correlated columns per row, the unpenalized fit is unstable or undefined, and the penalty makes it usable.

Check yourself

A lasso zeroes income but keeps education, and the two are highly correlated. Which is the best reading?

Show the answer

Answer: c

Choosing between correlated columns is close to arbitrary. Check by re-fitting across seeds or bootstrap samples.

07

Search it

In the app

In the Learners step, select Elastic net and press Tune…. Keep Bayesian (TPE) and the Quick preset to start. In Explanations, SHAP (linear) gives exact contributions, and this learner exports to native, ONNX and SQL.

Python
import pandas as pd
from sklearn.linear_model import ElasticNetCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

df = pd.read_csv("airquality.csv").dropna()
X, y = df[["Solar.R", "Wind", "Temp", "Month", "Day"]], df["Ozone"]
m = make_pipeline(StandardScaler(), ElasticNetCV(l1_ratio=[0.1, 0.5, 0.9, 1.0], cv=5, random_state=1))
m.fit(X, y)
print(m[-1].alpha_, m[-1].l1_ratio_, m[-1].coef_.round(2))
R
library(glmnet)
df <- na.omit(airquality)
X <- as.matrix(df[, c("Solar.R", "Wind", "Temp", "Month", "Day")])
set.seed(1)
foldid <- sample(rep(1:5, length.out = nrow(X)))
fits <- lapply(c(0.1, 0.5, 0.9, 1), function(a) cv.glmnet(X, df$Ozone, alpha = a, foldid = foldid))
best <- which.min(sapply(fits, function(f) min(f$cvm)))
coef(fits[[best]], s = "lambda.min")
08

Recap

Recap
  • Search λ\lambda on a log scale, then try the mixture.
  • Penalties earn their keep when columns are many or correlated.
  • A selected feature was useful for this fit. It wasn't shown to be the true cause.

Concepts in this lesson