Skip to content

Regularization: paying for complexity

A penalty makes large coefficients expensive. Trace ridge, lasso and elastic-net paths, and find the same idea inside trees, boosters and networks.

Applied ~12 min8 steps

What runs in CodeSplash

You will be able to

  • Write down a penalized loss and say what the penalty trades
  • Tell ridge from lasso by what happens to coefficients
  • Find the regularization knobs in non-linear learners

Read first

01

A price on size

Read

Ordinary least squares picks coefficients that fit the training rows best, however large they get. RegularizationRegularizationShrinks coefficients towards zero to reduce overfitting; lasso can drop predictors entirely. adds a price:

min⁡β  12n∑i(yi−xi⊤β)2+λ[ρ ∥β∥1+1−ρ2∥β∥22]\min_\beta \;\frac{1}{2n}\sum_i (y_i - x_i^\top\beta)^2 + \lambda\Big[\rho\,\lVert\beta\rVert_1 + \frac{1-\rho}{2}\lVert\beta\rVert_2^2\Big]

λ\lambda sets the price. ρ\rho mixes the two kinds: ρ=1\rho = 1 is the lassoLassoPenalized regression that shrinks coefficients by their absolute size, setting some exactly to zero., ρ=0\rho = 0 is ridgeRidge regressionPenalized regression that shrinks coefficients by their squared size. It keeps every predictor and handles overlap well., and anything in between is the elastic netElastic netPenalized regression that mixes the lasso and ridge penalties, so groups of correlated predictors tend to stay together.. Standardize first, so the price treats all columns alike.

02

Trace the paths

Explore

Move Penalty strength log10 λ and watch the coefficients shrink. Compare Training MSE with New-data MSE, and switch Penalty between Lasso (L1) and Ridge (L2).

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.30
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.

Try the two checks: keep exactly the three predictors that matter, then find a penalty within 1% of the best on the path.

03

Duplicates

Predict

Predict first

Two columns are nearly copies of each other, and both predict the target. What do the two penalties do?

Lasso splits the effect evenlyRidge splits it, and lasso tends to pick oneBoth drop the two columns
Reveal

Ridge splits the effect, and lasso tends to keep one. The lasso's choice between near-copies is close to arbitrary and can flip with a new sample, so don't read a dropped column as "doesn't matter". Press nearly duplicate predictors and roll new data to watch it happen. The elastic net sits between them and tends to keep correlated groups together.

04

Does a penalty pay off here?

Read

Not always. With 426 rows and 7 features, there's little overfitting to cure: Pima's unpenalized logistic model scores 0.857 and the elastic net 0.858, and on test rows 0.810 and 0.814.

Penalties earn their keep when features outnumber what the rows can support, or are heavily correlated. There they can be the difference between a useful model and a useless one.

05

Every model has a brake

Read
LearnerIts regularization
TreeDepth, rows per leaf, Pruning strength (α)
ForestRows per leaf, features per split
BoostingLearning rate, rounds, row and column subsampling, L1 and L2 penalties
Neural networkL2 penalty, early stopping
SVMCost (C)
06

Check your understanding

Checkpoint

Check yourself

Which penalty can set coefficients exactly to zero?

Show the answer

Answer: a

Ridge only shrinks, however strong the penalty. That's why the lasso selects features and ridge doesn't.

Check yourself

Why must you standardize before applying a penalty?

Show the answer

Answer: b

A column in grams needs a tiny coefficient, while the same column in kilograms needs a large one. Standardizing makes the price fair. The elastic net's model card shows standardizes inputs.

Check yourself

In the app's elastic net, what value of L1 share (ρ) gives the pure lasso?

Show the answer

Answer: 1

ρ=1\rho = 1 puts all the penalty on the L1 term. ρ=0\rho = 0 is pure ridge.

07

Set a penalty

In the app

In the Learners step, select Elastic net and open Hyperparameters. Penalty (λ) and L1 share (ρ) are both tunable, so Tune… can search them for you. After training, the importance table in Overview lists coefficient sizes.

Python
import pandas as pd
from sklearn.linear_model import ElasticNet
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"]
for lam in [0.01, 0.1, 1, 10]:
    m = make_pipeline(StandardScaler(), ElasticNet(alpha=lam, l1_ratio=1.0)).fit(X, y)
    print(lam, m[-1].coef_.round(2))
R
library(glmnet)
df <- na.omit(airquality)
X <- as.matrix(df[, c("Solar.R", "Wind", "Temp", "Month", "Day")])
fit <- glmnet(X, df$Ozone, alpha = 1, lambda = c(10, 1, 0.1, 0.01))
round(as.matrix(coef(fit))[-1, ], 2)

Each library applies the penalty on its own scale, so check that you've matched them before comparing λ\lambda across tools. The app matches the objective between engines.

08

Recap

Recap
  • A penalty charges for size, trading a little bias for less variance.
  • Lasso zeroes coefficients, ridge shrinks them, and the elastic net mixes both.
  • Every flexible learner has its own brake. Know which one you're pressing.

Concepts in this lesson