Generalisation means performing well on useful unseen cases, not memorising last month’s rows.
Some models are too simple to learn the pattern. Others are flexible enough to learn noise. Regularisation is one controlled way to prefer patterns that survive new data.
Lesson details
- Module
- Classical machine learning
- Lesson
- 7 · Bias–variance & regularisation
- Difficulty
- Beginner
- Learning time
- 70 minutes
Before you start
- Training, validation, testing, metrics, and cross-validation
- Linear-model weights, features, loss, and class thresholds
Skills you will gain
- Diagnose underfitting and overfitting from training and validation evidence
- Explain bias and variance without confusing them with social bias
- Apply L1, L2, and elastic-net regularisation in a validation-safe pipeline
- Compare class weights, threshold tuning, and SMOTE for imbalanced data
- Run a bounded, reproducible hyperparameter search
Why this matters
The same problem appears in classical ML, deep learning, prompts, retrieval, and agents: a system looks good on examples it has already influenced, then fails on new work.
Plain-English mental model
Step 1 — Read training and validation evidence together
Underfitting often shows high training and validation error. The representation or model cannot express a useful relationship.
Overfitting often shows low training error but noticeably worse validation error. The model is sensitive to the particular training sample.
BiasBiasError from systematic simplifying assumptions that make a model unable to represent a useful pattern. In the bias-variance trade-off it does not mean social bias, although both require careful review. means systematic approximation error from overly restrictive assumptions. VarianceVarianceSensitivity of a fitted model to which training examples it happened to see. High variance can fit training noise and produce unstable unseen-data performance. means sensitivity to training data. These technical terms are distinct from social bias, which must be assessed separately.
Step 2 — Regularisation adds a cost for unnecessary complexity
Objective:
objective = data_loss + strength × penalty(weights)
Strength is often called alpha, lambda, or C. Conventions differ: in many APIs a larger C means less regularisation. Read documentation and tune safely.
L1 and L2
L1 regularisationL1 regularisationA penalty proportional to the sum of absolute parameter values. It can set some linear-model weights exactly to zero, but correlated features can make its selections unstable. adds absolute values:
L1 penalty = Σ |weight_j|
It can make some weights exactly zero. Correlated features can swap importance, so zero weight is not proof that a feature is irrelevant.
L2 regularisationL2 regularisationA penalty proportional to the sum of squared parameter values. It shrinks weights smoothly and is also called ridge regularisation or weight decay in some contexts. adds squares:
L2 penalty = Σ weight_j²
It discourages large individual weights and is commonly called ridge regularisation. Elastic netElastic netA regularisation method combining L1 and L2 penalties, balancing sparsity with smooth weight shrinkage through validated hyperparameters. combines L1 and L2; tune its overall strength and mix on held-out evidence.
weights = [3.0, -1.0, 2.0]
strength = 0.1
l1 = sum(abs(weight) for weight in weights)
l2 = sum(weight ** 2 for weight in weights)
print("L1 sum:", l1)
print("L2 sum:", l2)
print("L1 contribution:", strength * l1)
print("L2 contribution:", strength * l2)Important lines
sum(abs(weight) ...)- L1 grows linearly with weight magnitude.
sum(weight ** 2 ...)- L2 grows faster for a large weight, so it penalises extreme values more.
strength * penalty- Strength trades fit against simplicity. Its scale depends on library and loss.
Step 3 — Class imbalance is a decision problem
Class imbalanceClass imbalanceA classification dataset where one class is much rarer than another. It makes accuracy misleading and requires attention to splits, metrics, thresholds, and the data-generating process. means positives are much rarer than negatives. A 99% accurate model can predict negative for every row and still miss every positive.
Start by checking whether rarity reflects reality, labels, collection gaps, or a changing policy. Use grouped/time-aware splits and inspect prevalence in every split.
- class weights: increase loss for errors on rare classes;
- threshold tuning: choose action volume and error trade-off on validation;
- undersampling: remove majority rows and potentially lose information;
- oversampling: repeat minority rows and potentially overfit;
- SMOTE: create synthetic minority rows between nearby minority examples.
SMOTESMOTESynthetic Minority Over-sampling Technique, which creates synthetic minority examples between nearby minority rows. It belongs inside training folds only and can create unrealistic data if used blindly. must run only inside each training fold. Creating synthetic rows before splitting lets related rows enter validation or test data and falsely improve measurements. It can also create implausible examples across categorical or constrained features.
Step 4 — Tune with a declared budget and one objective
Hyperparameter tuningHyperparameter tuningSelecting settings chosen before fitting, such as regularisation strength, tree depth, or learning rate, using validation or cross-validation evidence within a declared search budget. searches choices such as regularisation strength, tree depth, neighbours, or class weights.
- Grid search: planned combinations; clear but wasteful in many dimensions.
- Random search: samples ranges; often covers influential dimensions better within a budget.
- Bayesian optimisation: selects later trials using earlier results; it can be efficient but still overfits validation.
- Optuna: a Python library that can run and prune declared searches; it does not replace sound splits or a final test.
Declare metric, folds, budget, seed policy, ranges, and stopping rule before examining results. Record every trial. If many people repeatedly tune against one validation set, use nested cross-validation or a new validation period.
Worked system example — rare incident escalation
An operations team wants to escalate rare infrastructure incidents.
- Train on earlier weeks; preserve whole incidents and later weeks for validation and test.
- Compare a simple baseline, class-weighted model, and threshold policy.
- Measure PR-AUC plus precision and recall at the human team’s daily capacity.
- Fit scalers and resampling inside each training fold.
- Review misses and false alarms with operators, including service and region slices.
- Select a documented threshold on validation, then test once on a later period.
The aim is not the lowest average loss. It is a safe operational policy with an honest fallback.
Common mistakes
Calling any train–validation gap overfitting without checking split quality.
Fix — Inspect leakage, time drift, grouping, label noise, and sample size, then compare a controlled change on held-out evidence.
Using a stronger penalty because it feels safer.
Fix — Tune strength and capacity with validation. Too much regularisation underfits.
Interpreting L1 zero weights as causal feature selection.
Fix — Correlated features and preprocessing change selections. Use domain review and stability checks.
Oversampling before cross-validation.
Fix — Put SMOTE and all resampling inside each training fold only.
Treating class weights as a complete imbalance solution.
Fix — Still choose metrics, threshold, capacity, calibration, and fallback rules using validation data.
Searching endlessly until validation improves.
Fix — Declare a search budget, log trials, and protect final test evidence.
Exercises
A model has training error 0.03 and validation error 0.25. A simpler model has training error 0.13 and validation error 0.15. Which shows stronger evidence of overfitting, and what would you try next?
Reveal solution
The first model has a large train-validation gap, so it shows stronger evidence of overfitting. Try simpler features or model settings, regularisation, more representative data, and validate each change.
Weights are [3, -1, 2]. Calculate L1 and L2 penalty sums before multiplying by a regularisation strength.
Reveal solution
L1 is 6. L2 is 14. Libraries may include scaling factors or different conventions, so compare the documented objective and tune strength on validation data.
Describe a leakage-safe five-fold evaluation for SMOTE and regularisation strength selection on an imbalanced dataset.
Reveal solution
For each training fold, fit imputation, scaling, and SMOTE only on that fold’s training portion, then score untouched fold rows. Aggregate fold evidence, refit on permitted training data, and test once on untouched real rows.
Knowledge check
Knowledge check
Practice activity
Practice · 10–20 minutes
Diagnose a validation gap and choose a safe next experiment
Goal: Use train/validation evidence and an operational constraint to choose a controlled next step.
- Run the starter code and compare two candidates.
- Identify the likely underfit or overfit pattern.
- Choose one regularisation or capacity experiment and state what evidence would change your mind.
- Explain why resampling remains inside training folds.
- Choose a threshold based on capacity instead of assuming 0.5.
Expected result: Candidate B has a much larger training-validation gap and is the stronger overfitting candidate. A valid next experiment changes one constraint, then compares the same validation protocol.
Optional challenge: Write a tiny trial table with seed, split, strength, metric, capacity, and decision notes.
Reveal solution
candidates = {
"A simpler": {"train_error": 0.16, "validation_error": 0.17},
"B flexible": {"train_error": 0.03, "validation_error": 0.25},
}
for name, result in candidates.items():
gap = result["validation_error"] - result["train_error"]
print(name, "gap:", round(gap, 2))
print("review capacity:", 25, "alerts per day")Expected output:
A simpler gap: 0.01
B flexible gap: 0.22
review capacity: 25 alerts per dayCandidate B fits training rows extremely well but loses much more on validation, which is evidence of high variance or a split/data issue worth investigating. Try a simpler setting or stronger regularisation, keeping the same split and metric. Do not run SMOTE across all rows: it would leak synthetic relationships into validation. Select alert threshold after seeing validation scores and real review capacity.
Key takeaways
- Bias and variance describe different sources of generalisation error; both are measured on unseen evidence.
- Underfitting misses useful patterns; overfitting learns training-specific noise.
- L1 can encourage sparse weights, L2 shrinks weights, and elastic net combines them.
- Imbalance changes what metrics and thresholds mean; accuracy alone is often unhelpful.
- SMOTE, scaling, and selection must live inside training folds.
Flashcards
Flashcards
1 of 8Revision and interview questions
- Explain bias, variance, underfitting, and overfitting using training and validation curves.
- Calculate L1 and L2 penalties and explain why their effects differ.
- Design a leakage-safe class-imbalance evaluation with weights, SMOTE, metrics, and threshold selection.
- Compare grid, random, and Bayesian search under a fixed trial budget.
- Explain why a validation set can itself be overfit and how to respond.
One-page sketchnote summary
Print me · one-page revision sheet
Bias–variance & regularisation
Main idea
Generalisation needs the right amount of flexibility. Constrain models, handle rare cases safely, and select every setting within protected evaluation boundaries.
Core terms
- Bias — systematic simplification error
- Variance — training-sample sensitivity
- L1 — absolute-weight penalty
- L2 — squared-weight penalty
- SMOTE — training-fold-only synthetic rows
- Tuning — validation-based settings search
One picture
Code pattern
objective = loss + strength × penalty · fit training folds · choose validation settings · report once on testWatch out
- Do not trust training error alone
- Do not oversample before splitting
- Do not assume a larger penalty is safer
- Do not use accuracy alone for rare events
- Do not tune on test results
Remember
- Fit stable patterns, not noise
- Regularise with validation evidence
- Weights and thresholds are different tools
- Keep synthetic data out of held-out evidence
- Bound and record tuning
Three quick questions
- Is this gap a data problem or variance?
- Which error matters at capacity?
- Where can synthetic rows safely exist?
Lesson checklist
0 of 8 completeResources
- docsscikit-learn — linear modelsOfficial guide to ridge, lasso, elastic net, logistic regression, and regularisation parameters.
- docsimbalanced-learn documentationOfficial documentation for resampling methods and safe pipeline integration.
- docsscikit-learn — model selectionOfficial documentation for validation, cross-validation, learning curves, and parameter search.