What is regularization?
Regularization is any technique that constrains a model's effective capacity or training dynamics to prevent overfitting and improve generalization on unseen data. Most classically, it adds a complexity penalty such as L1 (Lasso) or L2 (Ridge) weight norms to the empirical training loss, trading a small increase in bias for a larger reduction in variance. Beyond explicit parameter penalties, regularization encompasses dropout, early stopping, data augmentation, and architectural constraints.
Study Card: What is Regularization?
Direct Answer
Regularization is a broad set of techniques used in machine learning to prevent overfitting and improve generalization to unseen test data by discouraging overly complex solutions. In its canonical explicit form, regularization augments the empirical loss with a penalty term weighted by a strength hyperparameter :
The two most common parameter penalties (typically applied to weights and not the bias/intercept) are:
- L2 regularization (Ridge / weight decay): , which shrinks all weights smoothly toward zero and stabilizes collinear features.
- L1 regularization (Lasso): , which induces exact sparsity by driving irrelevant feature weights to zero.
Implicit and structural forms—such as dropout, early stopping, batch/layer normalization, weight sharing, and data augmentation—also act as regularizers.
Key Terms
- Overfitting: Fitting noise and idiosyncrasies in the training sample, yielding low training error but high generalization error.
- Penalty Term (): Extra objective cost penalizing large or numerous parameters; controls the bias–variance tradeoff.
- L1 Regularization (Lasso): Adds , performing automatic feature selection via sparse solutions.
- L2 Regularization (Ridge): Adds , shrinking correlated weights together without exact zeroing.
- Generalization: Predictive accuracy on held-out data drawn from the same underlying distribution.
Example
Suppose you fit an 8th-degree polynomial to 30 noisy observations from a smooth quadratic trend. An unregularized linear regression assigns huge oscillating weights (such as and ) to high-degree terms so the curve passes close to every training point, producing severe test error on new samples. Adding L2 regularization penalizes those large weights, damping high-frequency oscillations back into a smooth curve; adding L1 regularization can zero out unused high-degree polynomial terms altogether.
Code Implementation
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import Lasso, LinearRegression, Ridge
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
# Generate noisy nonlinear data where high-degree polynomials overfit
rng = np.random.default_rng(42)
X = np.sort(rng.uniform(-3, 3, size=(40, 1)), axis=0)
y = 0.5 * X[:, 0] ** 2 + X[:, 0] + 1.0 + rng.normal(0, 1.2, size=len(X))
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
models = {
"Unregularized (deg=8)": make_pipeline(PolynomialFeatures(8, include_bias=False), StandardScaler(), LinearRegression()),
"Ridge L2 (alpha=10.0)": make_pipeline(PolynomialFeatures(8, include_bias=False), StandardScaler(), Ridge(alpha=10.0)),
"Lasso L1 (alpha=0.2)": make_pipeline(PolynomialFeatures(8, include_bias=False), StandardScaler(), Lasso(alpha=0.2, max_iter=10000)),
}
X_plot = np.linspace(-3, 3, 200).reshape(-1, 1)
plt.figure(figsize=(9, 5))
plt.scatter(X_train, y_train, color="steelblue", label="Train data")
plt.scatter(X_test, y_test, color="green", marker="^", label="Test data")
for name, pipe in models.items():
pipe.fit(X_train, y_train)
train_mse = mean_squared_error(y_train, pipe.predict(X_train))
test_mse = mean_squared_error(y_test, pipe.predict(X_test))
coef = pipe.steps[-1][1].coef_
print(f"{name:22s} | Train MSE: {train_mse:.3f} | Test MSE: {test_mse:.3f} | Non-zero coefs: {np.sum(np.abs(coef) > 1e-4)}/8")
plt.plot(X_plot, pipe.predict(X_plot), lw=2, label=f"{name} (Test MSE={test_mse:.2f})")
plt.ylim(-3, 10)
plt.xlabel("X")
plt.ylabel("y")
plt.title("Regularization Curbs High-Degree Polynomial Overfitting")
plt.legend()
plt.grid(True)
plt.show()
Related Concepts
- Bias–Variance Tradeoff: Stronger regularization increases bias slightly while sharply lowering variance until an optimal validation sweet spot is reached.
- Cross-Validation: Standard method for tuning (
alphain scikit-learn) without leaking test-set information. - Elastic Net: Combines L1 and L2 penalties () to achieve sparsity while stabilizing grouped correlated features.
- Weight Decay vs. L2 in Adaptive Optimizers (AdamW): While L2 penalties and decoupled weight decay are identical under plain SGD, they differ under Adam; decoupled weight decay (AdamW) is standard for modern deep networks and LLMs.
- Early Stopping & Dropout: Algorithmic and stochastic regularizers that restrict effective capacity without adding explicit norm terms to the loss.