Reading history

Regularization in Python: Ridge and Lasso Regression

5 min read 2 views

Learn Ridge and Lasso regularization in Python: L1 and L2 penalties, the alpha parameter, feature selection with Lasso, and RidgeCV and LassoCV.

An overfitted model memorises the noise in its training data, and in linear models this usually shows up as huge, wildly swinging coefficients. Regularization adds a penalty on the size of the coefficients to the training objective, so the model has to balance fitting the data against staying simple. Ridge regression shrinks all coefficients smoothly, while Lasso can push some exactly to zero, effectively selecting features for you.

In this lesson you will learn

  • Why large coefficients signal overfitting
  • Ridge (L2) and Lasso (L1) penalties
  • The alpha strength parameter
  • Feature selection with Lasso
  • Choosing alpha with RidgeCV and LassoCV

This lesson builds on linear regression and overfitting.

Taming an Overfitted Polynomial

import numpy as np
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler

# 15 noisy points from a gentle curve; a degree-12 polynomial will overfit
rng = np.random.default_rng(0)
x = np.sort(rng.uniform(0, 1, 15)).reshape(-1, 1)
y = np.sin(2 * np.pi * x).ravel() + rng.normal(0, 0.2, 15)
x_test = np.linspace(0, 1, 100).reshape(-1, 1)
y_test = np.sin(2 * np.pi * x_test).ravel()

def make(reg):
    return make_pipeline(PolynomialFeatures(12, include_bias=False), StandardScaler(), reg)

for name, reg in [("No regularisation", LinearRegression()),
                  ("Ridge alpha=0.01", Ridge(alpha=0.01)),
                  ("Lasso alpha=0.001", Lasso(alpha=0.001, max_iter=100000))]:
    model = make(reg).fit(x, y)
    coefs = model[-1].coef_
    test_err = np.mean((model.predict(x_test) - y_test) ** 2)
    print(f"{name:18s} test MSE={test_err:8.3f}  largest |coef|={np.abs(coefs).max():9.1f}  "
          f"zero coefs={np.sum(np.abs(coefs) < 1e-6)}")

Output

No regularisation  test MSE=   0.078  largest |coef|=     17.5  zero coefs=0
Ridge alpha=0.01   test MSE=   0.011  largest |coef|=      3.1  zero coefs=0
Lasso alpha=0.001  test MSE=   0.008  largest |coef|=      5.4  zero coefs=8
  • Fifteen noisy points from a sine curve are fitted with a degree-12 polynomial: 12 features for 15 points, a recipe for overfitting.
  • Plain linear regression fits the training points closely but bends wildly between them. Its largest coefficient is 17.5 and its error on the true curve is 0.078.
  • Ridge minimises error + alpha × (sum of squared coefficients). Even a small alpha shrinks the coefficients and cuts the test error to 0.011.
  • Lasso minimises error + alpha × (sum of absolute coefficients). That penalty sets 8 of the 12 coefficients exactly to zero, keeping a simpler curve with the lowest test error, 0.008.
  • The features are standardised first so the penalty treats them fairly. Without scaling, features with large values would be penalised less.

Lasso for Feature Selection

import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Lasso, LassoCV, RidgeCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

data = load_diabetes()
X, y, names = data.data, data.target, data.feature_names

# Lasso: as alpha grows, more coefficients become exactly zero
for alpha in [0.1, 1, 5, 10]:
    lasso = make_pipeline(StandardScaler(), Lasso(alpha=alpha)).fit(X, y)
    kept = [n for n, c in zip(names, lasso[-1].coef_) if abs(c) > 1e-6]
    print(f"alpha={alpha:<4} keeps {len(kept):2d} features: {kept}")

# Let cross-validation choose alpha
ridge = make_pipeline(StandardScaler(), RidgeCV(alphas=np.logspace(-3, 3, 13))).fit(X, y)
lasso = make_pipeline(StandardScaler(), LassoCV(cv=5, random_state=0)).fit(X, y)
print(f"\nRidgeCV chose alpha = {ridge[-1].alpha_:.3f}")
print(f"LassoCV chose alpha = {lasso[-1].alpha_:.3f}")

Output

alpha=0.1  keeps  9 features: ['age', 'sex', 'bmi', 'bp', 's1', 's2', 's4', 's5', 's6']
alpha=1    keeps  7 features: ['sex', 'bmi', 'bp', 's1', 's3', 's5', 's6']
alpha=5    keeps  5 features: ['sex', 'bmi', 'bp', 's3', 's5']
alpha=10   keeps  4 features: ['bmi', 'bp', 's3', 's5']

RidgeCV chose alpha = 1.000
LassoCV chose alpha = 0.079
  • As alpha increases, Lasso drops features one by one. At alpha = 10, only four of the ten diabetes features remain: BMI, blood pressure and two blood serum measurements. These are the most useful predictors.
  • RidgeCV tries each alpha in a list and keeps the one with the best cross-validated score. LassoCV builds its own range of alphas and does the same.
  • The best alphas here are moderate. Too small behaves like plain regression; too large removes useful information and underfits.

Ridge vs Lasso vs Elastic Net

Ridge (L2)Lasso (L1)Elastic Net
PenaltySum of squared coefficientsSum of absolute coefficientsMix of both
Zero coefficientsNo, only shrinksYes, selects featuresYes
Correlated featuresShares weight among themTends to keep one at randomKeeps groups together
Scikit-learn classRidge, RidgeCVLasso, LassoCVElasticNet, ElasticNetCV

The same idea appears elsewhere: LogisticRegression has an L2 penalty by default, controlled by C, which is the inverse of the strength (small C means strong regularization).

Common Mistakes

  1. Not scaling features before Ridge or Lasso.
  2. Confusing alpha and C: larger alpha means more regularization, but larger C means less.
  3. Choosing alpha on the test set; use RidgeCV, LassoCV or a grid search.
  4. Treating Lasso’s chosen features as the only true causes; with correlated features, a different but equally good set may be dropped.

Practice Exercises

Exercise 1. Fit ElasticNetCV on the diabetes data and print the chosen alpha and l1_ratio.

Show answer
from sklearn.linear_model import ElasticNetCV
enet = make_pipeline(StandardScaler(),
                     ElasticNetCV(l1_ratio=[0.1, 0.5, 0.9], cv=5, random_state=0)).fit(X, y)
print(enet[-1].alpha_, enet[-1].l1_ratio_)

Exercise 2. What happens to Ridge coefficients as alpha approaches 0, and as it becomes very large?

Show answer

Near 0, Ridge becomes ordinary linear regression. As alpha grows very large, all coefficients shrink towards zero and the model predicts close to the average of the target, which underfits.

Frequently Asked Questions

Why does the L1 penalty create exact zeros?

The absolute-value penalty has a sharp corner at zero, so for weak features the best compromise is often exactly zero. The squared penalty of Ridge is smooth there and only pushes coefficients towards zero.

Is regularization used in neural networks?

Yes. L2 regularization is called weight decay there, and other techniques such as dropout and early stopping serve the same purpose: preventing the model from memorising the training data.

Summary

  • Regularization penalises large coefficients to reduce overfitting.
  • Ridge shrinks all coefficients; Lasso can set some to zero.
  • Larger alpha means a stronger penalty; scale features first.
  • Pick alpha with cross-validation.

Next: DBSCAN and Hierarchical Clustering.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *