L1 vs. L2 Regularization: Which Should You Use?
When training machine learning algorithms, complex models frequently fit training data too closely, learning random noise rather than true structural patterns. This manifests as high variance and poor generalization on unseen validation data.
To prevent overfitting without sacrificing expressive capacity, machine learning relies on regularization—a mathematical technique that penalizes overly large or complex model parameters.
The two foundational techniques are L1 Regularization (Lasso) and L2 Regularization (Ridge). Understanding how their penalty mechanics differ is critical for feature selection, model interpretability, and robust performance.
In this guide, we will explore their mathematical foundations, geometric intuition, practical differences, Python implementations, and how to select the right regularization technique for your machine learning project.
1. The Cost of Complexity: Why Regularize?
In standard linear models (like Ordinary Least Squares regression), the algorithm minimizes a loss function—such as Mean Squared Error (MSE):
\[ \text{Loss}_{\text{standard}} = \sum_{i=1}^{n}(y_i-\hat{y}_i)^2 \]
When features are correlated, redundant, or outnumber training samples (\(p > n\)), the optimization algorithm may produce unstable or excessively large coefficients.
While this can yield very low training error, small fluctuations in input data may cause erratic predictions.
Regularization addresses this by augmenting the loss function with an explicit complexity penalty:
\[ \text{Objective Loss} = \text{Data Loss (MSE)} + \lambda \cdot \Omega(\mathbf{w}) \]
Where:
- Data Loss: Measures the difference between actual and predicted values.
- λ (Lambda): Controls the strength of regularization.
- Ω(w): Represents the penalty applied to model coefficients.
- w: Represents the model's feature coefficients.
The regularization parameter \(\lambda\) (also commonly called alpha in Scikit-learn) acts as a tuning knob:
- λ = 0: Standard unpenalized model.
- Low λ: Mild coefficient shrinkage.
- High λ: Stronger parameter shrinkage, potentially causing underfitting.
- Optimal λ: A value that provides a suitable balance between model complexity and generalization.
Important: Regularization typically penalizes feature coefficients but does not penalize the intercept by default in common Scikit-learn implementations of Lasso and Ridge.
2. L1 Regularization (Lasso Regression)
L1 regularization, also known as Least Absolute Shrinkage and Selection Operator (Lasso), penalizes the model based on the sum of the absolute values of its feature coefficients.
Mathematical Formulation
\[ \text{Loss}_{L1} = \text{MSE} + \lambda \sum_{j=1}^{p}|w_j| \]
Where:
- \(w_j\) = Coefficient of the jth feature.
- \(p\) = Total number of features.
- \(\lambda\) = Regularization strength.
Key Characteristic: Feature Sparsity
The primary distinguishing feature of L1 is that it can drive unimportant feature coefficients completely to zero.
Because coefficients can become exactly zero, Lasso performs automatic feature selection.
For example, imagine a dataset containing 500 input features.
After applying L1 regularization, the model might retain only 40 nonzero coefficients and eliminate the remaining 460.
This creates a sparse model that depends on a smaller subset of predictors.
The actual number of selected features depends on the dataset, regularization strength, and relationships between features.
When to Use L1
- You have high-dimensional datasets with many potentially irrelevant features.
- Feature selection is important.
- Model interpretability and compactness are priorities.
- You suspect that only a relatively small subset of features contains useful predictive information.
Advantages of L1
- Performs automatic feature selection.
- Produces sparse models.
- Can improve interpretability.
- Reduces the influence of irrelevant predictors.
- Can be useful when the number of features is very large.
Limitations of L1
- May arbitrarily select one feature from a group of highly correlated features.
- Feature selection can become unstable when predictors are strongly correlated.
- May remove useful features when regularization is too strong.
- Requires appropriate regularization tuning.
3. L2 Regularization (Ridge Regression)
L2 regularization, also known as Ridge Regression or Tikhonov regularization, penalizes the model based on the sum of the squared values of its feature coefficients.
Mathematical Formulation
\[ \text{Loss}_{L2} = \text{MSE} + \lambda \sum_{j=1}^{p}w_j^2 \]
Where:
- \(w_j\) = Coefficient of the jth feature.
- \(p\) = Total number of features.
- \(\lambda\) = Regularization strength.
Key Characteristic: Proportional Weight Shrinkage
L2 penalizes large weights more strongly because the penalty grows quadratically with coefficient magnitude.
As a result, it pulls coefficients toward zero smoothly.
Unlike L1, L2 generally does not force coefficients to exactly zero for finite regularization strengths.
All original features therefore usually remain in the model, although their individual influence may be reduced.
Example
Suppose a linear regression model produces these coefficients:
Feature A = 120
Feature B = 85
Feature C = 12
Feature D = 3
After applying L2 regularization, the coefficients might become:
Feature A = 65
Feature B = 48
Feature C = 8
Feature D = 2
These values are illustrative rather than guaranteed results.
The objective is to reduce excessively large coefficients while retaining the contribution of the available predictors.
When to Use L2
- You have many correlated or highly related features.
- Most features are believed to contain useful information.
- You want to reduce coefficient magnitudes without performing aggressive feature elimination.
- Predictive stability is more important than obtaining a sparse model.
Advantages of L2
- Reduces the impact of large coefficients.
- Helps control overfitting.
- Handles multicollinearity more effectively.
- Produces smoother and more stable coefficient estimates.
- Retains all predictors in the model under ordinary finite regularization strengths.
Limitations of L2
- Does not generally perform automatic feature elimination.
- All features remain represented in the model.
- Can introduce bias when regularization is too strong.
- Requires hyperparameter tuning.
4. Geometric Intuition: Why L1 Yields Sparsity
The mathematical reason L1 forces weights to zero while L2 generally only shrinks them lies in the geometric shape of their constraint regions.
L1 (Lasso): Diamond Constraint
The L1 constraint is represented by:
\[ |w_1|+|w_2|\leq t \]
Its geometric shape is a diamond in two dimensions.
The sharp corners of the diamond lie directly on the coordinate axes. Optimization solutions frequently occur at these corners, where one or more coefficients are exactly zero.
L2 (Ridge): Circular Constraint
The L2 constraint is represented by:
\[ w_1^2+w_2^2\leq t \]
Its geometric shape is a circle in two dimensions.
Because the boundary is smooth, solutions generally shrink coefficients toward zero without making them exactly zero.
Visual Interpretation
L1 (Lasso): Diamond Constraint
w2
^
|
/ \
/ \
/ \
--------+-------+--------> w1
\ /
\ /
\ /
Sharp corners touch the axes
L2 (Ridge): Circular Constraint
w2
^
|
.-------.
/ \
| o |
-----+---------------+----> w1
| |
\ /
'---------'
Smooth circular boundary
The interaction between the loss contours and these constraint regions explains why L1 encourages sparse solutions while L2 generally produces nonzero coefficients.
5. L1 vs. L2: Key Differences
Understanding the practical differences helps determine which regularization technique is appropriate for a particular machine learning problem.
| Parameter | L1 Regularization | L2 Regularization |
|---|---|---|
| Common Name | Lasso | Ridge |
| Penalty | Absolute values | Squared values |
| Mathematical Form | \(\lambda\sum | w_j |
| Coefficients | Can become exactly zero | Usually remain nonzero |
| Feature Selection | Yes, implicit | No, generally |
| Model Sparsity | High | Low |
| Correlated Features | May select one arbitrarily | Often distributes weights |
| Interpretability | Often easier with fewer features | Retains all features |
| Main Benefit | Feature selection | Coefficient shrinkage |
| Typical Use | Sparse datasets | Multicollinearity |
Which Is Better?
Neither technique is universally better.
Choose based on:
- The number of available features.
- The relationship between predictors.
- Whether automatic feature selection is required.
- Whether model interpretability is important.
- Validation performance.
6. Understanding the Regularization Parameter (Lambda)
The regularization parameter controls how strongly the model penalizes large coefficients.
Its value directly affects model complexity and prediction performance.
Low Regularization Strength
When \(\lambda\) is close to zero:
- The penalty has little influence.
- Coefficients can become relatively large.
- The model behaves more like ordinary linear regression.
- Overfitting may occur when the data contains noise or correlated predictors.
High Regularization Strength
When \(\lambda\) is very large:
- Coefficients are pushed strongly toward zero.
- The model becomes less flexible.
- Important relationships may be suppressed.
- Underfitting may occur.
Finding the Optimal Lambda
The goal is to select a regularization strength that minimizes validation error.
For example:
| Lambda | Training MSE | Validation MSE |
|---|---|---|
| 0.001 | 5.2 | 12.8 |
| 0.01 | 5.8 | 10.4 |
| 0.1 | 7.1 | 8.2 |
| 1 | 9.5 | 9.1 |
| 10 | 18.7 | 19.4 |
These are illustrative values.
In this example, \(\lambda=0.1\) provides the lowest validation MSE.
This suggests that it offers a better balance between fitting the training data and generalizing to unseen observations.
7. Elastic Net: Combining L1 and L2
What happens when you want the feature-selection ability of L1 and the coefficient stability of L2?
Elastic Net Regularization combines both penalties into a single objective function.
It is particularly useful when datasets contain many correlated features.
Mathematical Formulation
\[ \text{Loss}_{ElasticNet} = \text{MSE} + \lambda \left[ \alpha\sum_{j=1}^{p}|w_j| + \frac{1-\alpha}{2}\sum_{j=1}^{p}w_j^2 \right] \]
Here:
- \(\lambda\) controls the overall regularization strength.
- \(\alpha\) controls the balance between L1 and L2 penalties.
In this convention:
- \(\alpha=1\): Pure L1 regularization.
- \(\alpha=0\): Pure L2 regularization.
Note: This mathematical convention uses alpha for the L1/L2 mixture. In Scikit-learn's ElasticNet implementation, the parameters are named alpha for overall regularization strength and l1_ratio for the L1/L2 mixture.
When to Use Elastic Net
- You have many correlated predictors.
- You want feature selection without relying entirely on L1.
- You need a balance between sparsity and coefficient stability.
- You are working with high-dimensional datasets.
Python Implementation
from sklearn.linear_model import ElasticNet
model = ElasticNet(
alpha=0.1,
l1_ratio=0.5,
max_iter=10000
)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print("Elastic Net Coefficients:")
print(model.coef_)
8. Feature Scaling: Why Standardization Matters
Regularization penalizes coefficient magnitudes.
However, features may have completely different numerical scales.
For example:
- Age: 18–70.
- Salary: 20,000–200,000.
- Experience: 0–30.
- Account Balance: 1,000–1,000,000.
Without scaling, coefficient penalties may affect the model unevenly because the coefficients depend on the units in which features are expressed.
Standardization transforms features so that they have approximately zero mean and unit variance.
Mathematical Formula
\[ z=\frac{x-\mu}{\sigma} \]
Where:
- \(x\) = Original feature value.
- \(\mu\) = Training-set mean.
- \(\sigma\) = Training-set standard deviation.
- \(z\) = Standardized feature value.
Python Implementation
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.linear_model import Ridge
model = Pipeline([
("scaler", StandardScaler()),
("ridge", Ridge(alpha=1.0))
])
model.fit(X_train, y_train)
predictions = model.predict(X_test)
The pipeline ensures that the scaler is fitted using training data and then applied to the test data.
Important: Feature scaling is particularly important for L1 and L2 regularization. The intercept is generally not penalized in Scikit-learn's Ridge and Lasso estimators when the default intercept behavior is used.
9. Practical Python Implementation: L1 vs. L2
Let's compare Lasso and Ridge Regression using a sample regression dataset.
We will use Scikit-learn to:
- Generate a sample dataset.
- Divide it into training and testing subsets.
- Standardize the features.
- Train Lasso and Ridge models.
- Compare their coefficients.
- Evaluate their prediction performance.
Complete Python Code
import numpy as np
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.linear_model import Lasso, Ridge
from sklearn.metrics import mean_squared_error, r2_score
# Generate sample regression data
X, y = make_regression(
n_samples=500,
n_features=20,
n_informative=8,
noise=15,
random_state=42
)
# Split the dataset
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.20,
random_state=42
)
# L1 Regularization
lasso_model = Pipeline([
("scaler", StandardScaler()),
("model", Lasso(alpha=1.0, max_iter=10000))
])
# L2 Regularization
ridge_model = Pipeline([
("scaler", StandardScaler()),
("model", Ridge(alpha=1.0))
])
# Train models
lasso_model.fit(X_train, y_train)
ridge_model.fit(X_train, y_train)
# Predictions
lasso_predictions = lasso_model.predict(X_test)
ridge_predictions = ridge_model.predict(X_test)
# Evaluation function
def evaluate_model(name, actual, predicted, coefficients):
mse = mean_squared_error(actual, predicted)
r2 = r2_score(actual, predicted)
print(f"\n{name}")
print("MSE:", round(mse, 2))
print("R2 Score:", round(r2, 4))
print("Non-zero Coefficients:",
np.count_nonzero(coefficients))
# Extract coefficients
lasso_coefficients = lasso_model.named_steps["model"].coef_
ridge_coefficients = ridge_model.named_steps["model"].coef_
# Compare results
evaluate_model(
"Lasso Regression",
y_test,
lasso_predictions,
lasso_coefficients
)
evaluate_model(
"Ridge Regression",
y_test,
ridge_predictions,
ridge_coefficients
)
Understanding the Results
The output will show:
- Mean Squared Error (MSE).
- R² score.
- Number of nonzero coefficients.
Lasso may set some coefficients exactly to zero, while Ridge generally retains all feature coefficients.
The model with the lowest test error is not necessarily the model with the fewest features.
Key Learning: L1 focuses on sparsity, while L2 focuses on smooth coefficient shrinkage. Compare both using appropriate validation procedures rather than assuming one will always perform better.
10. Selecting the Best Regularization Strength Using Cross-Validation
Choosing lambda manually is not always reliable.
A better approach is to evaluate multiple regularization strengths using cross-validation.
Scikit-learn provides LassoCV and RidgeCV for this purpose.
LassoCV Example
from sklearn.linear_model import LassoCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
lasso_cv = Pipeline([
("scaler", StandardScaler()),
("model", LassoCV(
alphas=[0.001, 0.01, 0.1, 1, 10],
cv=5,
max_iter=10000
))
])
lasso_cv.fit(X_train, y_train)
best_alpha = lasso_cv.named_steps["model"].alpha_
print("Best Lasso Alpha:", best_alpha)
RidgeCV Example
from sklearn.linear_model import RidgeCV
ridge_cv = Pipeline([
("scaler", StandardScaler()),
("model", RidgeCV(
alphas=[0.001, 0.01, 0.1, 1, 10],
cv=5
))
])
ridge_cv.fit(X_train, y_train)
best_alpha = ridge_cv.named_steps["model"].alpha_
print("Best Ridge Alpha:", best_alpha)
The cross-validation process helps identify a regularization strength that performs well across different training and validation folds.
The final test dataset should remain untouched until model selection is complete.
11. Real-World Applications of L1 and L2 Regularization
Regularization is widely used across machine learning applications.
1. Healthcare
Predicting disease risks using patient information such as age, blood pressure, glucose levels, and medical history.
- L1 can help identify a smaller set of predictive features.
- L2 can stabilize coefficients when medical measurements are correlated.
2. Banking and Finance
Predicting loan defaults and credit risk using financial information.
- L1 can remove less useful predictors.
- L2 can reduce the effect of correlated financial variables.
3. E-commerce
Predicting product demand and customer purchasing behavior.
- L1 can help identify important customer and product features.
- L2 can control excessively large coefficients across many predictors.
4. Marketing Analytics
Predicting sales using advertising expenditure across different platforms.
- L1 can select the most useful advertising variables.
- L2 can help stabilize estimates when advertising channels are correlated.
5. Text Classification
Text datasets can contain thousands of features generated through Bag-of-Words or TF-IDF representations.
- L1 can produce sparse models by eliminating many feature coefficients.
- L2 can shrink coefficients across a large vocabulary and often provides stable predictive performance.
12. Common Mistakes When Using Regularization
Understanding regularization also means knowing when it can produce misleading or ineffective results.
Mistake 1: Ignoring Feature Scaling
Regularization penalizes coefficient magnitudes, so different feature scales can distort the penalty.
Solution: Standardize numerical features within a leakage-safe pipeline.
Mistake 2: Choosing Lambda Without Validation
A very large lambda may remove useful information, while a very small lambda may fail to control overfitting.
Solution: Use cross-validation to select the regularization strength.
Mistake 3: Assuming L1 Is Always Better for Feature Selection
L1 can select features, but correlated predictors may lead to unstable selection.
Solution: Consider Elastic Net when correlated features are common.
Mistake 4: Assuming L2 Removes Unimportant Features
L2 generally shrinks coefficients without setting them exactly to zero.
Solution: Use L1 or Elastic Net when sparse feature selection is required.
Mistake 5: Evaluating Only Training Performance
A regularized model can still underfit or overfit depending on the selected penalty.
Solution: Compare training and validation performance, then evaluate the final model on untouched test data.
13. Best Practices for Choosing L1, L2, or Elastic Net
| Situation | Recommended Technique |
|---|---|
| Many irrelevant features | L1 |
| Need automatic feature selection | L1 |
| Many correlated predictors | L2 |
| Most features contain useful signal | L2 |
| Need sparsity with correlated features | Elastic Net |
| Need stable coefficient estimates | L2 |
| High-dimensional text classification | L1 or L2, depending on validation performance |
Practical Decision Framework
Choose L1 (Lasso) when:
- You want a smaller feature set.
- You expect many predictors to be irrelevant.
- Model simplicity is important.
Choose L2 (Ridge) when:
- Most predictors may contain useful information.
- Features are strongly correlated.
- You want to shrink coefficients without eliminating predictors.
Choose Elastic Net when:
- You want a combination of feature selection and coefficient shrinkage.
- You have groups of correlated predictors.
- Pure L1 produces unstable feature selection.
Ultimately, compare the techniques using cross-validation and select the model that generalizes best.
14. Conclusion
L1 and L2 regularization are two fundamental techniques for controlling model complexity and reducing overfitting in machine learning.
L1 Regularization (Lasso) encourages sparsity by driving some coefficients completely to zero, making it useful for automatic feature selection and simpler models.
L2 Regularization (Ridge) shrinks coefficient magnitudes smoothly, helping stabilize predictions and manage multicollinearity while generally retaining all predictors.
Elastic Net combines the strengths of both approaches and can be particularly effective when dealing with high-dimensional datasets containing correlated features.
The right choice depends on your dataset, feature relationships, model requirements, and validation performance.
Ultimately, regularization is not about making every coefficient as small as possible. It is about finding the right balance between model complexity, predictive accuracy, and generalization to unseen data.