Fix Overfitting with Regularization

machine-learning
sklearn
tutorial
A deep dive into Ridge, Lasso, and ElasticNet regression
Author

WillzWayn

Published

February 28, 2026

The Problem: When Models Memorize Instead of Learn

Imagine you have a dataset with 150 training samples but 264 features (including polynomial interactions and 100 columns of pure random noise). This is a recipe for disaster: with more features than samples, a model can perfectly memorize the training data, including the noise.

A naive LinearRegression() will achieve: - Train R² = 1.0 (perfect fit on training data!) - Val R² = -3.9 (worse than just predicting the mean!)

This is overfitting - the model has learned the training data too well, including its noise, and fails to generalize to new data.

The Solution: Regularization

Regularization adds a penalty term to the loss function that discourages large weights. The key insight is: by penalizing complexity, we force the model to focus on only the features that actually matter.

The general form is:

Loss = Data Loss + α × Penalty(weights)

Where α (alpha) controls how much we penalize complexity.

Comparing Regularization Methods

I tested all major sklearn regularized regression models on this challenge. Here are the results:

Model Train R² Val R² Notes
LinearRegression (baseline) 1.0000 -3.9017 Catastrophic overfitting
Ridge (α=5000) 0.5668 0.0245 Best performer!
RidgeCV 0.7650 -0.0582 Auto-tuned but missed optimal α
Lasso (α=1.0) 0.3627 -0.2459 Strong feature selection
LassoCV 0.3627 -0.2459 Kept only 4 features
ElasticNetCV 0.9999 -2.6223 Too much L2, not enough regularization
SelectKBest(k=20)+Ridge 0.8234 -0.2854 Manual feature selection

Key Insight: The Best Model is Ridge with α=5000

Ridge regression achieved the only positive validation R² (0.0245), turning a -3.9 disaster into a working model.

Understanding Each Method

1. Ridge Regression (L2 Penalty)

Penalty: Sum of squared weights

Penalty = Σ(weights²)

Ridge shrinks all weights toward zero but never sets them exactly to zero. This means all features remain in the model, just with reduced influence.

from sklearn.linear_model import Ridge

# Higher alpha = more regularization
model = Ridge(alpha=5000)
model.fit(X_train, y_train)

When to use: When you suspect most features are somewhat relevant, or when you want stable predictions.

2. Lasso Regression (L1 Penalty)

Penalty: Sum of absolute weights

Penalty = Σ|weights|

Lasso can set weights exactly to zero, effectively removing features from the model. This is automatic feature selection!

from sklearn.linear_model import Lasso

model = Lasso(alpha=1.0, max_iter=10000)
model.fit(X_train, y_train)

# See which features survived
active_features = np.sum(model.coef_ != 0)  # Only 4/264 features!

When to use: When you suspect many features are irrelevant (like our noise columns).

3. ElasticNet (L1 + L2 Combined)

Combines both penalties with a mixing parameter l1_ratio: - l1_ratio=0 → pure Ridge - l1_ratio=1 → pure Lasso

from sklearn.linear_model import ElasticNet

model = ElasticNet(alpha=0.1, l1_ratio=0.5, max_iter=10000)

When to use: When you want the benefits of both methods, especially when features are correlated.

Automatic Tuning with Cross-Validation

Instead of manually trying alpha values, use sklearn’s CV variants:

from sklearn.linear_model import RidgeCV, LassoCV, ElasticNetCV

# Automatically selects best alpha from provided range
ridge_cv = RidgeCV(alphas=[0.1, 1.0, 10.0, 100.0, 1000.0])
ridge_cv.fit(X_train, y_train)
print(f"Best alpha: {ridge_cv.alpha_}")

Note: In our experiment, RidgeCV selected α=1000, but the optimal was actually α=5000. This happens when the search range doesn’t include the optimal value.

Feature Selection Approaches

Option 1: Lasso’s Built-in Selection

Lasso naturally selects features by setting irrelevant weights to zero:

lasso = Lasso(alpha=1.0)
lasso.fit(X_train, y_train)
relevant = X_train.columns[lasso.coef_ != 0]

Option 2: SelectKBest + Model Pipeline

Manually select top-k features before fitting:

from sklearn.pipeline import Pipeline
from sklearn.feature_selection import SelectKBest, f_regression

pipeline = Pipeline([
    ('select', SelectKBest(f_regression, k=20)),
    ('ridge', Ridge(alpha=1.0))
])
pipeline.fit(X_train, y_train)

The Winning Solution

Here’s the train function that passes this challenge:

import numpy as np
from sklearn.linear_model import Ridge

def train(X_train, y_train, X_val, y_val):
    """
    Train a regularized model that generalizes despite
    more features than samples.
    """
    model = Ridge(alpha=5000)
    model.fit(X_train, y_train)

    def predict(X):
        return model.predict(X)

    return predict

Key Takeaways

  1. More features than samples = danger zone - expect severe overfitting without regularization

  2. Ridge is robust - it works well even when many features are noisy

  3. Alpha matters enormously - the difference between α=1000 and α=5000 was the difference between negative and positive R²

  4. Auto-tuning isn’t magic - CV models can miss optimal values if your search range is wrong

  5. Lasso’s feature selection is powerful - but too aggressive here (only 4 features kept)

  6. Always validate - always check performance on held-out data, not just training data

Files