Regularization: L1, L2, and ElasticNet
After this lesson, you will be able to:
- Understand L2 regularization as putting a 'budget cap' on your model's weights — it cannot spend too much on any one feature
- Understand why L1 regularization sets useless features to exactly zero — automatic feature selection built into the math
- Pick the right regularization method (L1, L2, or both via ElasticNet) for your specific problem
- Tune the regularization strength (lambda) to find the sweet spot between underfitting and overfitting
Before you start
Don't worry if regularization feels abstract — the core idea is simple: it stops your model from going overboard. Think of it as a teacher saying "keep your answer simple" instead of letting you write a 50-page essay for a 5-point question!
Active recall
Before we go further, recall: in the bias-variance tradeoff lesson, what was the SIGNATURE of a high-variance (overfit) model — what specifically goes wrong on train vs test, and why? Write one sentence before reading on. (Forcing yourself to retrieve this now is more durable than re-reading it.)
Write your answer in your own words — don't look back at the lesson. This is the most effective way to remember what you just learned.
Type your explanation above
#War Story: The Perfect-Fit Model That Was Actually Broken
The coefficients of the "perfect" model:
w_1 = +7,213.4
w_2 = -41,827.9
w_3 = +89,104.2
w_4 = -78,910.6
w_5 = +34,521.3
The fix was literally two lines:
from sklearn.linear_model import Ridge
model = Ridge(alpha=1.0) # replaces LinearRegressionalpha.This lesson is about turning that knob deliberately.
#The Overfitting Problem
Overfitting happens when a model learns not just the true signal in the data, but also the random noise specific to the training set. The symptoms are clear:
- Training error: very low (model memorizes every training point)
- Test error: much higher (the memorized noise does not generalize)
- Model coefficients: large in magnitude, often with alternating signs that cancel each other out
w = [4200, -4198, 3.2] has almost certainly overfit. The first two weights nearly cancel — they are fitting noise. Regularization prevents this by penalizing large weight magnitudes directly in the loss function.You train a regression model and observe: training MSE = 0.02, test MSE = 4.50. Which is the BEST diagnosis?
#L2 Regularization (Ridge)
#The Loss Function
Ridge regression adds the sum of squared weights to the loss:
Try it! Open the Python REPL and type these lines yourself. Compare Ridge (L2) vs. plain regression:from sklearn.linear_model import LinearRegression, Ridge; import numpy as np; X = np.random.randn(20,5); y = np.random.randn(20); print("No regularization:", LinearRegression().fit(X,y).coef_.round(2)); print("With L2 (Ridge): ", Ridge(alpha=10).fit(X,y).coef_.round(2))— notice how Ridge shrinks all the weights!
#The Gradient
(1 - 2·α·λ) — a factor slightly less than 1. Every weight shrinks proportionally to its magnitude. This never forces weights to exactly zero; it just makes them smaller.Where does the gradient formula come from, and why does it turn into a decay? Open the derivation to follow every line.
#Geometric Intuition: The Sphere Constraint
Minimize MSE subject to||w||² ≤ t(budget constraint)
#The Unconstrained Solution
w*. The model can set weights to any values, and it will often choose large ones to chase noise in the training data.#Adding the L2 Constraint (Sphere)
||w||² ≤ t defines a sphere (circle in 2D) centered at the origin. The solution must live inside this sphere. As λ increases, t decreases — the sphere shrinks.#Where the Ellipses Touch the Sphere
The regularized solution is where the MSE loss contours first touch the sphere. Because a sphere has no corners, this contact point almost never lands exactly on an axis. Therefore, L2 regularization shrinks weights toward zero but rarely makes them exactly zero.
#The Result: Smooth Shrinkage
All weights are reduced proportionally. Features are all kept in the model — just with smaller influence. This is ideal when you believe all features contain some signal and you want to prevent any one feature from dominating.
The claim that a penalty is the same as a budget can be proved in a few lines. The derivation also shows why a bigger lambda means a smaller budget.
The L2 penalty has a second, hidden effect: it treats the directions in the data unequally. The next derivation finds a closed form and shows exactly how much each direction is shrunk. Two scale notes first. In this lesson the loss has a 1/n in front of the MSE, so the penalty weight that appears below is lambda-prime = n times lambda. That is why scikit-learn's Ridge(alpha) matches this lesson when alpha = n times lambda. Second, for Lasso scikit-learn divides the squared error by 2n, so its alpha equals lambda/2 in this lesson's loss.
Where does the L2 penalty come from if you think in probabilities? Putting a Gaussian prior on the weights and finding the most probable weights gives this same penalty. That is derived in the MLE, MAP & Fisher Information lesson, so it is not repeated here. The same lesson derives the matching fact that a Laplace prior gives the L1 penalty of the next section.
#L1 Regularization (Lasso)
#The Loss Function
#The Gradient (Subgradient)
λ·sign(w) — a constant push toward zero regardless of the weight's magnitude. For L2, the push is 2λ·w — proportional to the weight. With L2, as a weight approaches zero, the push weakens and never crosses zero. With L1, the push is always the same constant λ — small weights get pushed just as hard as large ones and cross zero, becoming exactly zero.#Geometric Intuition: The Diamond Constraint
Why can a weight land on exactly zero under L1 but not under L2? The next derivation turns the question into one inequality, and it explains the corners of the diamond below.
||w||₁ ≤ t (sum of absolute values) defines a diamond shape (L1 ball) in weight space:The next picture compares the three ways of measuring distance from the origin, so you can see for yourself that the set of points at distance 1 under the sum of absolute values is a diamond.
#The Unconstrained Solution
w* sits at the center of the MSE loss ellipses. It may have many non-zero components — all the noise-fitting coefficients that overfit the training data.#The L1 Constraint is a Diamond
{w : |w₁| + |w₂| ≤ t} forms a diamond (rotated square in 2D, a cross-polytope in higher dimensions). Its key geometric feature: pointed corners that align exactly with the coordinate axes — points where one weight is non-zero and all others are zero.#The Loss Contours Hit a Corner
#Sparsity: Some Features Become Exactly Zero
The diamond's corners are precisely why L1 produces sparse solutions. More corners → more opportunities to hit an axis → more zero weights. A sphere (L2) has no corners, so it almost never lands on an axis.
Now the exact answer for one clean case. When the features are uncorrelated and scaled the same, Lasso has a formula that you can read straight off the unregularised solution.
Move the least-squares value z and the strength lambda to watch the L1 answer stick at exactly 0 inside the dead zone while the L2 answer only shrinks; the picture's ridge penalty is (lambda/2) w^2 on top of 1/2 (w - z)^2, which gives z/(1 + lambda), and L1 minimises 1/2 (w - z)^2 + lambda |w|.
The L1 penalty is also a prior. A Laplace prior on the weights gives the sum of absolute values, which is derived in the same MLE, MAP & Fisher Information lesson as the Gaussian case, so there is nothing new to derive here.
Why does L1's diamond-shaped constraint region produce SPARSE solutions while L2's spherical region does not?
#Concrete example: L1 on 5 features
Suppose we fit Lasso to predict customer churn on 5 features. Here's what the coefficient vector looks like at three different λ values:
| Feature | λ = 0 (no reg) | λ = 0.1 | λ = 1.0 |
|---|---|---|---|
months_active | +0.84 | +0.71 | +0.42 |
last_login_days | -0.61 | -0.48 | -0.19 |
support_tickets | +0.33 | +0.12 | 0.00 |
random_uuid_hash | -0.21 | 0.00 | 0.00 |
mouse_x_avg_px | +0.14 | 0.00 | 0.00 |
random_uuid_hash, mouse_x_avg_px) are eliminated at moderate regularization (λ=0.1). The marginal feature (support_tickets) survives moderate regularization but is eliminated under strong regularization. This is what we mean by "automatic feature selection."Interactive Lab
Drag the lambda slider and see exactly which features survive Lasso and which die. Compare side-by-side with Ridge — same lambda, totally different behavior at the extremes.
λ grows. Watch how the Lasso path snaps individual weights to exactly zero, while the Ridge path slides them smoothly toward zero without ever crossing.You have 1000 features predicting house price. You suspect only about 50 actually matter. Which regularization should you use?
L1/Lasso is the right answer here. When you have 1000 features and expect only ~50 to matter, you want a method that zeros out the irrelevant 950. L1 does this automatically. L2 keeps all 1000 features with small weights — the model is harder to interpret and uses more memory at inference time. L1 effectively performs feature selection as part of training, giving you a sparse model that is both interpretable and efficient.
Your Ridge regression model has very low training error but much higher test error. You decide to increase λ. What happens to training error?
#ElasticNet: The Best of Both
When features are correlated, Lasso has a problem: it arbitrarily picks one feature from a correlated group and zeros out the others. This makes the solution unstable — small changes in data can cause it to pick a different feature. ElasticNet fixes this by combining L1 and L2:
ElasticNet has two hyperparameters:
- λ₁ (L1 ratio in sklearn): Controls sparsity. Higher → more zeros.
- λ₂ (alpha·(1 - l1_ratio) in sklearn): Controls weight shrinkage. Higher → smaller weights.
When to use ElasticNet
- Features are correlated and you want to select groups, not individuals
- You are unsure whether L1 or L2 is better (ElasticNet interpolates)
- The number of features is larger than the number of samples (p >> n)
- Genomics, text, and financial data with many correlated signals
Why does mixing in a little L2 fix Lasso's habit of picking one feature out of a correlated group? The extreme case of two identical features shows it with plain algebra.
Time to see all three penalties side by side. The cell below builds a 100-feature regression problem where only 10 features are truly informative, then fits Ridge, Lasso, and ElasticNet, so you can count exactly how many coefficients each one zeros out.
In the playground above (sparse problem with 10 of 100 features informative), which model do you expect to zero out the MOST coefficients?
#Beyond Penalties: Dropout and Early Stopping
Two other tricks act like regularizers without a visible penalty term. Dropout randomly switches features off during training, and early stopping simply stops training before the loss is at its lowest. For a linear model the first has an exact penalty form.
Early stopping works like L2 as well. Gradient descent that starts at zero and runs for time t moves along each SVD direction i by the fraction 1 - exp(-2 alpha t sigma_i squared / n) of the way to its least-squares value, while ridge applies the fraction sigma_i squared over (sigma_i squared + n lambda). Both are near 0 for directions with little variance and near 1 for strong ones, with stopping time t playing the role of 1/(2 alpha lambda). The shapes are similar but not identical, so this is a rule of thumb. Goodfellow et al, Deep Learning, section 7.8 works it out for a quadratic loss.
#Choosing λ: The Regularization Path
#Cross-Validation for Optimal λ
from sklearn.linear_model import RidgeCV, LassoCV
# RidgeCV automatically finds the best alpha via cross-validation
ridge_cv = RidgeCV(alphas=np.logspace(-3, 3, 100), cv=5)
ridge_cv.fit(X_scaled, y)
print(f"Best Ridge alpha: {ridge_cv.alpha_:.4f}")
# LassoCV does the same for Lasso
lasso_cv = LassoCV(alphas=np.logspace(-3, 3, 100), cv=5, max_iter=10000)
lasso_cv.fit(X_scaled, y)
print(f"Best Lasso alpha: {lasso_cv.alpha_:.4f}")
print(f"Lasso non-zero features: {np.sum(lasso_cv.coef_ != 0)}")#Comparison: When to Use Each
| L2 (Ridge) | L1 (Lasso) | ElasticNet | |
|---|---|---|---|
| Feature selection | No (keeps all) | Yes (zeros out noise) | Partial (group selection) |
| Correlated features | Handles well | Picks one, drops rest | Selects groups |
| Interpretability | Medium (all weights) | High (sparse model) | Medium |
| Computation | Fast (closed form) | Slower (iterative) | Slower (iterative) |
| When to use | All features matter | Most features are noise | Features are correlated |
| Production example | Neural net weight decay | Sparse recommendations | Genomics, text |
#The Bridge Forward: Which λ?
alpha beats grid search at the same compute, and TPE (Optuna) beats both, but only if you wrap the regularizer in a Pipeline with the scaler so the CV folds don't leak.#Key Takeaways
- Overfitting is the problem; regularization is the solution. Without regularization, models memorize training noise via large weights; regularization adds a tax on weight magnitude, forcing simpler solutions that generalize
- L2 (Ridge) shrinks all weights toward zero but never to exactly zero. The sphere constraint has no corners; all features are retained; best when all features contain some signal
- L1 (Lasso) makes some weights exactly zero. The diamond constraint has corners that align with axes; exact zeros emerge; best for automatic feature selection in high-dimensional sparse problems
- ElasticNet combines both penalties. Handles correlated features by selecting groups rather than individuals; the default choice when unsure
- Always scale features before regularizing. L1/L2 penalize weight magnitude uniformly; unscaled features with different units get unfair treatment
- λ controls the bias-variance tradeoff. Higher λ increases bias but reduces variance; find the sweet spot with cross-validation
#Quick Check
You are training a logistic regression model for cancer diagnosis with 5000 genomic features. Most features are likely uninformative SNPs. Which regularization should you use?
weight_decay in every modern neural network optimizer. Next up: Logistic Regression — bending a regularized linear model through a sigmoid to predict probabilities, the workhorse classifier behind spam filters, credit scoring, and click-through-rate models at every major tech company.