AI
Regularization in Machine Learning, Explained
Regularization in machine learning explained: L1 vs L2, elastic net, dropout, early stopping and weight decay, with a worked example and tuning tips.
Regularization in machine learning is any technique that stops a model from fitting its training data too closely, so it performs better on new data. The most common form adds a penalty to the training loss for large model weights: L2 regularization (ridge) shrinks all weights toward zero, while L1 regularization (lasso) pushes some weights to exactly zero. Other techniques, like dropout, early stopping and data augmentation, regularize neural networks without changing the loss formula.
This guide goes beyond the basic definition: it explains why regularization reduces overfitting, compares L1 vs L2 regularization with a worked example in real numbers, walks through the main regularization techniques in machine learning and deep learning, shows how each looks in scikit-learn, Keras and PyTorch, and explains how to choose the regularization strength.
What Is Regularization in Machine Learning?
Regularization is a way to trade a little accuracy on the training data for better accuracy on data the model hasn't seen. A model with too much freedom can learn the noise in its training set: random quirks that won't repeat. That's overfitting. Regularization limits that freedom.
The classic version changes what the model minimizes during training:
regularized loss = data loss + λ × penalty on the weights
- The data loss measures how wrong the predictions are, for example mean squared error for regression or cross-entropy for classification.
- The penalty grows as the weights get larger.
- λ (lambda, called
alphain scikit-learn) controls how strong the penalty is. At λ = 0 there's no regularization; as λ grows, the model is pushed toward simpler solutions.
Our explainer on the bias variance tradeoff covers the theory behind this: regularization adds a little bias to cut a lot of variance. This article focuses on the practical side: which technique to use, how it behaves and how to tune it.
Why Regularization Reduces Overfitting
Why regularization reduces overfitting comes down to one idea: overfit models usually need extreme weights. To pass exactly through every noisy training point, a model has to twist sharply, and in a linear or polynomial model that means very large positive and negative coefficients that cancel each other out. A neural network that memorizes its training data similarly relies on a few large, specific weights.
A penalty on weight size makes those extreme solutions expensive. The model can still fit the main trend, because that needs only moderate weights, but fitting the noise now costs more in penalty than it saves in data loss. So the optimizer settles on a smoother function that generalizes better.
Other techniques reach the same goal by different routes:
- Dropout stops a network from relying on any single neuron.
- Early stopping ends training before the model starts memorizing.
- Data augmentation gives the model more varied data, so memorizing becomes harder than learning the real pattern.
Regularization doesn't fix every problem. If a model underfits, meaning it's too simple to capture the pattern at all, more regularization makes things worse.
What Is L2 Regularization?
L2 regularization adds the sum of the squared weights to the loss. In linear regression it's called ridge regression. scikit-learn's documentation writes the ridge objective as minimizing ||Xw − y||² + α||w||², where ||w||² is the sum of squared coefficients.
What L2 does:
- It shrinks all weights toward zero, but almost never to exactly zero.
- It shrinks large weights much more than small ones, because the penalty grows with the square.
- It handles correlated features well: when two features carry the same information, L2 spreads the weight between them instead of picking one arbitrarily.
In neural networks, L2 regularization is usually called weight decay, because each update step slightly shrinks every weight. Keras computes its L2 penalty as l2 * reduce_sum(square(x)) with a default factor of 0.01 when you pass kernel_regularizer='l2'.
What Is L1 Regularization?
L1 regularization adds the sum of the absolute values of the weights. In linear regression it's called the lasso (least absolute shrinkage and selection operator). scikit-learn's lasso minimizes (1 / 2n) × ||Xw − y||² + α||w||₁.
The key property: L1 sets some weights exactly to zero. scikit-learn's documentation describes the lasso as "able to set coefficients exactly to zero," which means it effectively removes features from the model. That makes L1 a built-in feature selection method, useful when you suspect only a few of many features matter.
Why the difference? The L2 penalty's slope shrinks as a weight approaches zero, so the push toward zero fades. The L1 penalty pushes with the same force no matter how small the weight is, so weak weights get pushed all the way to zero and stay there.
L1 vs L2 Regularization
| L1 (lasso) | L2 (ridge, weight decay) | |
|---|---|---|
| Penalty | Sum of absolute weights | Sum of squared weights |
| Effect on weights | Many become exactly zero | All shrink, few reach zero |
| Feature selection | Yes, built in | No |
| Correlated features | Tends to keep one and drop the others | Spreads weight across them |
| Solution | Sparse | Dense, smooth |
| Optimization | Not differentiable at zero; needs special solvers | Smooth; easy to optimize; ridge has a closed-form solution |
| Typical use | Many features, few expected to matter; interpretable models | Default choice for most linear models and neural networks |
| scikit-learn | Lasso(alpha=...) | Ridge(alpha=...) |
| Keras | regularizers.L1(l1=...) | regularizers.L2(l2=...) |
L1 vs L2 regularization: when to use each. Start with L2: it's stable, works with any model and rarely hurts. Switch to L1 when you want a sparse model that uses fewer features, for example to explain predictions or to cut the cost of collecting features. If you want both, use elastic net.
Regularization in Machine Learning: A Worked Example
Here's L1 vs L2 regularization on a tiny dataset you can check by hand. Four points, one feature, no intercept:
| x | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| y | 2.1 | 3.9 | 6.2 | 7.8 |
Without regularization, the best slope is Σxy ÷ Σx² = 59.7 ÷ 30 = 1.99.
With ridge (scikit-learn's objective, no 1/n factor), the slope becomes Σxy ÷ (Σx² + α). With lasso (scikit-learn's objective, which divides the data term by 2n), the one-feature solution is the unregularized fit pulled toward zero by a fixed amount, then clipped at zero.
| Strength (α) | Ridge slope | Lasso slope |
|---|---|---|
| 0 | 1.990 | 1.990 |
| 1 | 1.926 | 1.857 |
| 5 | 1.706 | 1.323 |
| 10 | 1.493 | 0.657 |
| 15 | 1.327 | 0.000 |
| 100 | 0.459 | 0.000 |
Two lessons jump out:
- Ridge never reaches zero. Even at α = 100, the slope is 0.459. It just keeps shrinking.
- Lasso hits exactly zero. Once α passes 14.925 (the average of x times y in this data), the lasso decides the feature isn't worth its penalty and drops it.
Also note that the same α means different things in Ridge and Lasso because their objectives are scaled differently. Never copy an α from one to the other.
Elastic Net
Elastic net combines both penalties. scikit-learn's version mixes them with l1_ratio: 1.0 is pure lasso, 0.0 is pure ridge, and values in between give some sparsity while keeping L2's stability with correlated features. It's a good choice when you have many correlated features and still want some of them removed.
Regularization Techniques in Machine Learning and Deep Learning
Penalties on weights are only part of the toolbox. Here are the main regularization techniques in machine learning, and where each fits:
| Technique | How it works | Where it's used | Main setting |
|---|---|---|---|
| L2 / weight decay | Penalizes squared weights | Linear models, neural networks | λ, alpha, weight_decay |
| L1 / lasso | Penalizes absolute weights; zeros some out | Linear models with many features | λ, alpha |
| Elastic net | Mix of L1 and L2 | Linear models with correlated features | alpha, l1_ratio |
| Dropout | Randomly zeroes neurons during training | Neural networks | Drop probability p |
| Early stopping | Stops training when validation loss stops improving | Any iteratively trained model | Patience (epochs to wait) |
| Data augmentation | Creates varied copies of training data (flips, crops, noise, paraphrases) | Vision, audio, text | Which transforms, how strong |
| Label smoothing | Softens one-hot targets so the model isn't over-confident | Classification networks | Smoothing factor |
| Tree limits | Max depth, min samples per leaf, pruning | Decision trees, random forests, gradient boosting | max_depth, min_samples_leaf |
| Boosting regularization | Shrinkage (learning rate), subsampling, L1/L2 on leaf weights | XGBoost, LightGBM | learning_rate, lambda, alpha |
| Batch normalization | Normalizes layer inputs; adds mild noise as a side effect | Deep networks | Mostly a training aid |
Dropout
Dropout, introduced in a 2012 paper by Hinton and colleagues on "preventing co-adaptation of feature detectors," randomly sets a fraction of neuron outputs to zero on each training step. The network can't depend on any single neuron, so it learns redundant, more general features. PyTorch's nn.Dropout uses p = 0.5 by default, scales the remaining outputs by 1/(1 − p) during training, and does nothing at evaluation time. Lower rates like 0.1 to 0.3 are common in modern architectures.
Early stopping
Early stopping watches validation loss during training and stops when it hasn't improved for a set number of epochs (the "patience"), then restores the best weights. It's free, simple and works with any model trained in steps. It's often the first regularizer to add, together with weight decay.
Data augmentation
Data augmentation creates new training examples by changing existing ones in ways that shouldn't change the label: flipping or cropping images, adding background noise to audio, paraphrasing text. More varied data makes memorization harder. It's one of the most effective regularizers in computer vision.
Weight decay vs L2 regularization
With plain stochastic gradient descent, weight decay and an L2 penalty are mathematically the same. With adaptive optimizers like Adam, they aren't: adding L2 to the loss gets scaled by Adam's per-parameter step sizes, which weakens it for some weights. The paper "Decoupled Weight Decay Regularization" (Loshchilov and Hutter) proposed AdamW, which applies weight decay directly to the weights instead. AdamW is now the standard optimizer for transformers; PyTorch's AdamW uses a default weight_decay of 0.01.
How to Choose the Regularization Strength
The strength λ is a hyperparameter, so you choose it with validation data, not training data.
- Search on a log scale. Try values like 0.001, 0.01, 0.1, 1, 10, 100. The right value can sit anywhere across several orders of magnitude.
- Use cross-validation. scikit-learn's
RidgeCV,LassoCVandElasticNetCVtest a range of α values and pick the best automatically. - Read the curves. If training and validation error are both high, you're underfitting: lower λ. If training error is low but validation error is high, you're overfitting: raise λ.
- Scale your features first. Penalties treat all weights alike, so a feature measured in thousands gets a tiny weight and almost no penalty, while one measured in fractions gets penalized heavily. Standardize features before using L1 or L2.
- Don't penalize the intercept. Libraries handle this by default; if you write your own loss, leave the bias out of the penalty.
Regularization in Code
scikit-learn:
from sklearn.linear_model import Ridge, Lasso, ElasticNet, LogisticRegression
ridge = Ridge(alpha=1.0)
lasso = Lasso(alpha=0.1)
enet = ElasticNet(alpha=0.1, l1_ratio=0.5)
clf = LogisticRegression(C=0.5) # smaller C = stronger regularizationNote the inverse setting in LogisticRegression (and SVMs): C is the inverse of regularization strength, with a default of 1.0, so smaller values regularize more. In scikit-learn 1.8, the penalty parameter of LogisticRegression was deprecated; you pick L1, L2 or elastic net with l1_ratio (0 for L2, 1 for L1) and turn regularization off with C=np.inf.
Keras:
from keras import layers, regularizers
dense = layers.Dense(64, activation="relu", kernel_regularizer=regularizers.L2(1e-4))
drop = layers.Dropout(0.3)PyTorch:
import torch
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.01)
dropout = torch.nn.Dropout(p=0.1)Regularization vs Normalization
These two words sound alike but do different jobs. Normalization rescales data or activations so values sit in a similar range (for example standardizing features, or batch normalization inside a network); it helps training run smoothly. Regularization limits model complexity to reduce overfitting. Normalization can have a mild regularizing side effect, and scaling features is a prerequisite for L1 and L2 to work fairly, but they aren't the same thing.
Common Mistakes
- Regularizing without scaling features. The penalty then depends on units, not importance.
- Tuning λ on the test set. Use a validation set or cross-validation; keep the test set for the final check.
- Copying α between Ridge and Lasso. Their objectives are scaled differently.
- Adding regularization to an underfitting model. If the model can't fit the training data, make it more flexible instead.
- Using dropout at inference time. Frameworks turn it off in evaluation mode; forgetting
model.eval()in PyTorch gives noisy predictions. - Using L2 with Adam and expecting weight decay. Use AdamW for decoupled weight decay.
If you're just starting out, our explainer on AI vs machine learning shows where models like these fit in the bigger picture.
FAQ
What is regularization in simple words?
It's a way of stopping a model from memorizing its training data. Usually it adds a cost for large weights, so the model prefers simpler patterns that also work on new data.
What is the difference between L1 and L2 regularization?
L1 adds the absolute size of the weights to the loss and drives some weights to exactly zero, removing features. L2 adds the squared size and shrinks all weights smoothly without removing any.
Does regularization increase bias?
Yes, slightly. It makes the model a bit less flexible on purpose, which adds some bias but usually cuts variance by more, so error on new data goes down.
Is dropout a regularization technique?
Yes. Dropout regularizes neural networks by randomly switching off neurons during training, so the network can't rely on any single path through the model.
What is a good value for lambda?
There's no universal value. Search across powers of ten with cross-validation. For neural networks, weight decay around 0.01 with AdamW and dropout between 0.1 and 0.5 are common starting points.