Comparison
L1 vs L2 Regularization: Lasso vs Ridge Explained
Use L1 (lasso) when you suspect many features are useless and want the model to drop them: it drives some weights to exactly zero. Use L2 (ridge, or weight decay) when most features carry some signal and you want to keep them all but stop any weight growing large. L2 is the usual default in deep learning.
Last updated · By Rohit Ghumare
L1 vs L2 regularization at a glance
| L1 | L2 | |
|---|---|---|
| Penalty added to the loss | \lambda \sum \lvert w_i \rvert | \lambda \sum w_i^2 |
| Name in linear regression | Lasso | Ridge |
| Pull on each weight (gradient of the penalty) | Constant size: \lambda \cdot \text{sign}(w_i) | Proportional to the weight: 2 \lambda w_i |
| Effect on weights | Some become exactly zero | All shrink; they rarely reach zero |
| Resulting model | Sparse: fewer features in use | Dense: every feature kept, with small weights |
| Feature selection | Yes, built in | No |
| Shape of the constraint region | Diamond, with corners on the axes | Circle |
| How it is solved | No one-step formula; the penalty has a kink at zero, so use soft-thresholding or coordinate descent | A one-step formula exists for ridge regression; plain gradient descent also works |
| In neural networks | Uncommon | Standard, as weight decay |
| Related norm | L1 norm (Manhattan distance) | L2 norm (Euclidean distance) |
Both penalties are convex, so adding either to a convex loss such as mean squared error keeps the problem convex.
When to choose each
Choose L1 when
- You have many features and expect only some to matter, as with wide tabular data or bag-of-words text features.
- You want a smaller model that is easier to explain: the features with zero weight are simply out.
- You need feature selection to happen during training, without a separate selection step.
Choose L2 when
- Most features contribute a little, and dropping any would lose information.
- You are training a neural network. Weight decay is the standard form; with Adam, use AdamW so the decay is applied separately from the gradient update.
- You want a penalty that is smooth everywhere, so ordinary gradient descent works unchanged.
- The model overfits by giving a few weights very large values. L2 penalizes large weights most.
Use both when
Elastic net adds both penalties. It keeps L1's ability to zero out features while L2 keeps the remaining weights stable. Reach for it when plain L1 gives a different set of selected features every time you resample the data.
Code: one example per side
Both scripts use only the Python standard library and the same data: four features, of which only the first two affect the target (y = 3x_1 - 2x_2 plus noise). Both use lam = 0.5.
L2. This script uses the common convention of a penalty of (\lambda/2) \sum w_i^2, whose gradient is lam * wi, added to each step. With the table's \lambda \sum w_i^2 the gradient would be 2 * lam * wi and the shrinkage twice as strong.
import random
random.seed(0)
X = [[random.gauss(0, 1) for _ in range(4)] for _ in range(200)]
y = [3 * row[0] - 2 * row[1] + random.gauss(0, 0.5) for row in X]
def gradient(w):
errors = [sum(wi * xi for wi, xi in zip(w, row)) - target for row, target in zip(X, y)]
return [sum(e * row[j] for e, row in zip(errors, X)) / len(X) for j in range(4)]
lam, lr = 0.5, 0.1
w = [0.0] * 4
for _ in range(500):
w = [wi - lr * (g + lam * wi) for wi, g in zip(w, gradient(w))]
print([round(wi, 3) for wi in w])[1.997, -1.333, -0.004, -0.026]L1. After each gradient step, soft-thresholding moves every weight toward zero by a fixed amount and clips it at zero.
import random
random.seed(0)
X = [[random.gauss(0, 1) for _ in range(4)] for _ in range(200)]
y = [3 * row[0] - 2 * row[1] + random.gauss(0, 0.5) for row in X]
def gradient(w):
errors = [sum(wi * xi for wi, xi in zip(w, row)) - target for row, target in zip(X, y)]
return [sum(e * row[j] for e, row in zip(errors, X)) / len(X) for j in range(4)]
def soft_threshold(value, amount):
if value > amount:
return value - amount
if value < -amount:
return value + amount
return 0.0
lam, lr = 0.5, 0.1
w = [0.0] * 4
for _ in range(500):
w = [soft_threshold(wi - lr * g, lr * lam) for wi, g in zip(w, gradient(w))]
print([round(wi, 3) for wi in w])[2.536, -1.465, 0.0, 0.0]Read the two outputs side by side. L2 shrank the two real weights and left the two useless features with small non-zero values. L1 set the two useless features to exactly zero. Both pulled the real weights below their true values of 3 and -2; that bias is the price of regularization, and it grows with the penalty strength.
Common mistakes
- Not scaling features first. The penalty acts on the size of each weight, and a weight's size depends on its feature's units. Standardize features so the penalty treats them equally.
- Penalizing the bias term. Regularize the weights, not the intercept.
- Using one fixed strength. The right value depends on the data. Tune it with cross-validation.
- Reading L1's zeros as proof a feature is irrelevant. A zero means the model did not need that feature given the others, at that penalty strength.
- Confusing the penalty with the loss. L1 loss (mean absolute error) and L2 loss (mean squared error) measure prediction error. L1 and L2 regularization penalize weights. They are independent choices.
- Using L2-in-the-loss with Adam. With Adam, L2 added to the loss is not the same as weight decay. Use AdamW.
- Regularizing an underfit model. If training error is already high, a penalty makes it worse. Regularization is a fix for overfitting only.
- Expecting plain gradient descent to give exact zeros with L1. Without the thresholding step, weights hover near zero instead of landing on it.
Frequently asked questions
What is the difference between L1 and L2 regularization?
Both add a penalty on the weights to the loss. L1 adds the sum of their absolute values and pushes some weights to exactly zero, which removes those features. L2 adds the sum of their squares and shrinks every weight toward zero but rarely to exactly zero. L1 selects; L2 smooths.
Are lasso and ridge the same as L1 and L2?
Yes, in the setting of linear regression. Lasso regression is linear regression with an L1 penalty, and ridge regression is linear regression with an L2 penalty. The names L1 and L2 are more general, because the same penalties can be added to logistic regression, neural networks and other models.
Why does L1 produce sparse weights and L2 does not?
L1's pull toward zero has the same strength however small the weight is, so a weak weight reaches zero and stays there. L2's pull is proportional to the weight, so it fades as the weight shrinks. Geometrically, L1's constraint region is a diamond with corners on the axes.
Is weight decay the same as L2 regularization?
With plain stochastic gradient descent they are equivalent: adding the L2 penalty to the loss shrinks each weight by a fixed fraction every step. With Adam they are not, because Adam rescales the penalty's gradient. That is why AdamW applies the decay separately from the gradient update.
How do I choose the regularization strength?
Treat it as a hyperparameter. Try several values spaced by factors of ten, score each with cross-validation or a validation set, and keep the value with the lowest validation error. Too small and the model still overfits; too large and it underfits because the weights cannot grow enough.
Learn it by building
These free lessons build the ideas from the math up:
- Norms and Distances: the L1 and L2 norms and why their shapes differ.
- Convex Optimization: L1 and L2 as constraint regions, the diamond and the circle.
- Linear Regression: ridge regression from scratch, and lasso as an exercise.
- Feature Selection: L1 as an embedded feature selector.
- Bias-Variance Tradeoff: why a penalty trades a little bias for less variance.
- Regularization: weight decay, dropout and normalization in neural networks.