Regularisation — 99% Accuracy Masked 3x Default Rate
Weights >1e6 from no regularisation caused 3x default rates.
20+ years shipping production ML systems and the infrastructure behind them. Written from production experience, not tutorials.
- ✓Solid grasp of fundamentals
- ✓Comfortable reading code examples
- ✓Basic production concepts
- Regularisation adds a penalty term to the loss function that prevents overfitting by penalising large weights.
- L1 (Lasso) drives irrelevant feature weights to exactly zero — automatic feature selection.
- L2 (Ridge) shrinks all weights smoothly toward zero but keeps every feature in the game.
- Tuning lambda via cross-validation typically reduces test error by 15–30% compared to no regularisation.
- In production, skipping feature scaling before regularisation silently destroys model performance.
- The biggest mistake: treating regularisation as a magic fix instead of diagnosing the overfit first.
Imagine you're cramming for a test by memorising every single practice question word-for-word instead of learning the underlying concepts. You ace the practice paper but bomb the real exam because the questions are slightly different. That's overfitting — your model memorised the training data instead of learning the pattern. Regularisation is like your teacher saying 'stop memorising, start understanding' — it adds a penalty that forces the model to stay simple and generalise better to new data.
Every machine learning model has the same enemy: a model that looks brilliant on training data but falls apart the moment it sees real-world data. This isn't a rare edge case — it's the default failure mode. Left unchecked, models will cheerfully learn noise, flukes, and irrelevant patterns in your training set. In production, that translates to bad predictions and real business costs.
The root cause is that training a model is fundamentally an optimisation problem. The algorithm tries to minimise error on the data it can see. Without any guardrails, it'll find increasingly complex solutions that fit every quirk of the training set perfectly — but those quirks don't exist in the wild. Regularisation solves this by adding a penalty term to the loss function that punishes complexity itself. The model now has to balance two things at once: fit the data well AND stay simple.
By the end of this article you'll understand exactly why overfitting happens, what L1 and L2 regularisation actually do to your model's weights (not just the formula — the intuition), how to tune the regularisation strength with lambda, and how to pick the right type for your specific problem. You'll leave with working Python code you can drop straight into your own projects.
Why Regularisation Prevents Your Model From Memorising Noise
Regularisation is a set of techniques that constrain a machine learning model's complexity to prevent overfitting — learning training data so precisely that it fails on unseen data. The core mechanic adds a penalty term to the loss function proportional to the magnitude of the model's weights. For linear models, L2 regularisation (ridge) penalises the sum of squared weights, while L1 (lasso) penalises the sum of absolute weights, driving some weights to exactly zero. This forces the model to distribute importance across features rather than relying on a few dominant ones.
In practice, regularisation introduces a hyperparameter λ (lambda) that controls the penalty strength. A λ of 0 means no regularisation — the model fits training data perfectly but generalises poorly. As λ increases, weights shrink toward zero, reducing variance at the cost of increased bias. The sweet spot typically lies where validation error is minimised, often found via cross-validation. L1 regularisation is particularly useful for feature selection in high-dimensional spaces, while L2 handles multicollinearity by keeping all features but dampening their influence.
Use regularisation whenever your model has more parameters than necessary or when feature count approaches sample size. In production systems, it's not optional — it's the difference between a model that maintains 95% accuracy on new data and one that drops to 70% after a month. Regularisation is why logistic regression with thousands of features can still generalise, and why deep networks with millions of parameters don't simply memorise the training set.
Why Models Overfit — and What Regularisation Actually Does
To understand regularisation, you first need a crisp mental model of overfitting. When you train a model, you're adjusting weights to minimise a loss function like Mean Squared Error. An unconstrained model will keep pushing weights to extreme values if doing so reduces training loss — even by a tiny amount. Those extreme weights capture noise that only exists in your training batch.
Here's the key insight: large weights are the symptom of overfitting. A weight of 847.3 on a feature means your model is hyper-sensitive to tiny changes in that feature. That's almost never justified by real-world signal.
Regularisation works by adding an extra term to the loss function:
Regularised Loss = Original Loss + λ × Penalty
The penalty is a function of the weights themselves. Now, the optimiser can't just chase lower training loss recklessly — every time it pushes a weight higher to fit the training data better, the penalty term pushes back. Lambda (λ) controls how aggressive that pushback is. A higher lambda means stronger regularisation, simpler model. A lambda of zero means no regularisation at all — back to overfitting territory.
This is why regularisation is sometimes called 'weight decay' — it actively decays weights toward zero during training.
L1 vs L2 Regularisation — The Real Difference That Matters in Practice
Both L1 (Lasso) and L2 (Ridge) add a penalty term to the loss function, but the penalty is calculated differently — and that difference has profound practical consequences.
L2 (Ridge) penalises the sum of squared weights: λ × Σ(wᵢ²). Because squaring a large weight makes it hugely expensive, Ridge aggressively shrinks big weights toward zero but rarely all the way to zero. Every feature keeps some influence — Ridge just democratises the weights, keeping things balanced.
L1 (Lasso) penalises the sum of absolute weights: λ × Σ|wᵢ|. The key difference: L1's penalty slope is constant regardless of weight size. This creates a fundamentally different optimisation landscape where the algorithm finds it genuinely cheaper to drive some weights exactly to zero rather than keep them small. The result is automatic feature selection.
Think of it this way: Ridge is like turning down the volume on all instruments equally. Lasso is like removing some instruments from the band entirely.
When to use which? Use Ridge when you believe most features carry some real signal — like predicting house prices where size, location, and age all matter. Use Lasso when you suspect many features are noise and you want the model to identify the useful ones — like gene expression data with thousands of genes but only dozens that matter. Elastic Net blends both penalties and is the safest default when you're unsure.
Tuning Lambda — How to Find the Right Regularisation Strength
Lambda (α in sklearn) is the most important hyperparameter in regularisation. Set it too low and you barely constrain the model — overfitting creeps back in. Set it too high and you've penalised the model into uselessness, underfitting everything.
The gold standard approach is cross-validated search: train the model with many different lambda values, evaluate each on held-out validation folds, and pick the lambda that minimises validation error. Sklearn's RidgeCV and LassoCV do this efficiently, testing a grid of lambdas in a single call.
The validation curve is your most important diagnostic tool here. Plot training error and validation error against lambda values. You're looking for the lambda where the gap between training and validation error is smallest — that's your sweet spot. Too far left (small lambda): gap is wide — overfitting. Too far right (large lambda): both errors are high — underfitting.
One practical rule of thumb: start with a logarithmic search space (0.001, 0.01, 0.1, 1, 10, 100) rather than a linear one. Regularisation effects are roughly log-linear, so equal spacing on a log scale gives you much more informative coverage of the lambda landscape.
Elastic Net — When L1 and L2 Alone Aren't Enough
Real-world data rarely fits neatly into the 'all features relevant' or 'most features noise' buckets. Often you have many features, some correlated, some noisy, some genuinely useful. Choosing L1 loses correlated groups. Choosing L2 never sparsifies. Elastic Net combines both penalties: λ × (0.5 × (1 − l1_ratio) × Σwᵢ² + l1_ratio × Σ|wᵢ|).
The l1_ratio parameter (0 to 1) controls the mix. l1_ratio=1 is pure Lasso. l1_ratio=0 is pure Ridge. In practice, l1_ratio=0.5 is a solid default. But like lambda, l1_ratio should be cross-validated.
Elastic Net solves the 'grouped feature' problem. When you have highly correlated features (like one-hot encoded categories or noisy sensor readings), Lasso arbitrarily picks one and drops the rest. Elastic Net either keeps the whole group or drops it together — more stable and often more accurate.
Bottom line: if you're unsure, start with Elastic Net. Cross-validate both alpha and l1_ratio. It's computationally heavier but gives you the best of both worlds.
- Lasso removes entire correlated groups; Elastic Net keeps or drops them together.
- l1_ratio near 1 = Lasso behaviour; near 0 = Ridge behaviour.
- Cross-validating l1_ratio adds one more hyperparameter dimension but often pays off.
- Use when you have many features with unknown structure — the safe default for most production datasets.
Regularisation Beyond Linear Models — Neural Networks, Trees & Ensembles
Regularisation isn't exclusive to linear models. Neural networks overfit just as badly — often worse because they have millions of parameters. Three common regularisation techniques in deep learning:
- L1/L2 weight decay: PyTorch and Keras apply weight decay by adding an extra term to the loss. In PyTorch, you set weight_decay in the optimiser. In Keras, use kernel_regularizer=l2(0.01) on each layer.
- Dropout: Randomly drops neurons during training with probability p. Forces the network to learn redundant representations. At inference, all neurons are active but their outputs are scaled by p. Typical p=0.5 for fully connected layers, 0.2–0.3 for convolutional layers.
- Early stopping: Stop training when validation loss stops improving. The model hasn't had time to memorise noise. In practice, early stopping with patience=5–10 works as regularisation — it prevents the optimisation from converging to an overfitted minimum.
For tree-based models (Random Forest, XGBoost), regularisation works differently. XGBoost has L1 and L2 regularisation on leaf weights (reg_alpha, reg_lambda). Random Forest uses built-in ensembling (bagging + random feature selection) as its regularisation — more trees means lower variance.
The key takeaway: regularisation is universal. No matter your model family, you need a mechanism to constrain complexity.
Common Pitfalls and Production Best Practices
Even experienced engineers make these mistakes. Let's cover the traps you'll actually encounter in production.
Pitfall 1: Applying regularisation without scaling. Regularisation penalises weight magnitude. If Feature A is in metres (values ~0–100) and Feature B is in millimetres (values ~0–100,000), the model will penalise Feature B's weight even though its natural coefficient is smaller. Always standardise features to zero mean and unit variance before any penalty-based regularisation.
Pitfall 2: Using default lambda. The sklearn default for Ridge is alpha=1.0. That might be perfect for one dataset and disastrous for another. Always use RidgeCV or LassoCV to find your lambda.
Pitfall 3: Regularising after leakage. If you shuffle the dataset before train/test split, you've already leaked test data into the training process. Regularisation won't fix that — it'll just compress a leaking model. Never shuffle before splitting.
Pitfall 4: Treating regularisation as a substitute for data cleaning. Regularisation reduces overfitting but doesn't remove bad data. Duplicate rows, extreme outliers, and target leakage must be fixed in preprocessing. Regularisation is a band-aid, not a cure.
Best Practice: Always run a no-regularisation baseline. Train a model with alpha=0 first to see how bad the overfitting is. Then add regularisation. The gap between the two is your 'overfitting budget' — it tells you how much regularisation you need.
Why Regularisation Shrinks Coefficients and What That Actually Buys You
Here's the part textbooks gloss over. Regularisation doesn't just "add a penalty". It forces a trade-off between fitting the training data and keeping weights small. When lambda goes up, coefficients shrink. Some hit zero. That's not a math trick — it's a direct attack on variance.
Ridge regression (L2) pulls weights toward zero but never all the way. The model keeps every feature but damps their influence. Lasso (L1) outright kills irrelevant features. If your dataset has 500 columns and most are noise, Lasso zeroes them out. You get a simpler model and automatic feature selection.
Why should you care? Smaller coefficients mean the model's output changes less when input values shift. Real-world data has noise. It has drift. Coefficients that are small make the model stable. When your production metrics flatline after a data pipeline change, that stability is what keeps you from getting paged at 3 AM.
Stop thinking of regularisation as a penalty. Think of it as a governor on your model's tendency to overreact.
How Regularisation Rescues the Bias-Variance Trade-off You Keep Ignoring
Every model you've ever trained sits on a spectrum. One end: high bias, low variance — think of a constant predictor that never changes. Other end: low bias, high variance — a deep tree that memorises every training point. Regularisation slides you along this spectrum without rewriting your architecture.
High variance models overfit. They're hypersensitive to training noise. Change one row in your training set and the weights dance. Regularisation adds bias — it forces the model to be simpler. That extra bias smooths out the weight landscape. The model becomes less sensitive to tiny fluctuations in input.
This isn't academic. In production, you don't get clean training data. Nulls sneak in. Sensors drift. Users behave differently on weekends. A model with high variance will spike predictions on Thursday and get you called into a fire drill. Regularisation flattens those spikes by penalising complexity.
The trick is balance. Too little regularisation and you're back to overfitting. Too much and your model becomes a flat line. Tune lambda like you tune a hyperparameter — with cross-validation and a cold beer. Start with lambda values spanning three orders of magnitude and watch validation loss.
The 99% Training Accuracy That Masked a Useless Model
- Never trust training accuracy alone — always compare to validation/hold-out metrics.
- High-dimensional data with few samples is a red flag: regularise aggressively from the start.
- Scale all features to zero mean, unit variance before applying any penalty-based regularisation.
- Cross-validate lambda — never use the default blindly.
from sklearn.model_selection import learning_curve; import matplotlib.pyplot as pltplot_learning_curve(model, X_train, y_train, cv=5)| File | Command / Code | Purpose |
|---|---|---|
| overfitting_demo.py | from sklearn.linear_model import LinearRegression, Ridge, Lasso | Why Models Overfit |
| l1_vs_l2_feature_selection.py | from sklearn.linear_model import Ridge, Lasso, ElasticNet | L1 vs L2 Regularisation |
| lambda_tuning_crossval.py | from sklearn.linear_model import RidgeCV, LassoCV | Tuning Lambda |
| elastic_net_grid.py | from sklearn.linear_model import ElasticNetCV | Elastic Net |
| regularisation_nn.py | model = nn.Sequential( | Regularisation Beyond Linear Models |
| best_practices.py | from sklearn.linear_model import Ridge | Common Pitfalls and Production Best Practices |
| RidgeLassoShrinkage.py | from sklearn.linear_model import Ridge, Lasso | Why Regularisation Shrinks Coefficients and What That Actual |
| BiasVarianceTradeoff.py | from sklearn.linear_model import Ridge | How Regularisation Rescues the Bias-Variance Trade-off You K |
Key takeaways
Interview Questions on This Topic
Can you explain the geometric intuition behind why L1 regularisation tends to produce sparse weights while L2 doesn't? Walk me through what happens at the constraint boundary.
Frequently Asked Questions
20+ years shipping production ML systems and the infrastructure behind them. Written from production experience, not tutorials.
That's ML Basics. Mark it forged?
8 min read · try the examples if you haven't