AI ENGINEER01-07 · Bias–variance trade-off & regularisation
20/90
Sign in

Layer 01 · Classical ML · Ch 07

Bias–variance trade-off & regularisation

Recognise overfitting, constrain models honestly, and tune imbalance treatments without leaking evidence.

70 min readdifficulty beginnerdepth build

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

FIG 01-07.1 · ERROR CURVES REVEAL A GAPfit the pattern, not the noisemodel flexibility →errortraining errorvalidation errorchoose here with validationunderfitoverfitvariance controlsmore representative dataL1 / L2 penaltiessimpler features/modelearly stoppingvalidate every trade-offtraining fit is not generalisation — compare unseen data across seeds, folds, and time
FIG 01-07.1— as flexibility increases, training error usually falls. Validation error can fall then rise when the model begins fitting noise. The useful region is selected using validation evidence, not where training error is lowest.

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.

PythonCalculate two penalty contributions
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.

FIG 01-07.2 · RESAMPLE ONLY THE TRAINING FOLDbalance the learning, protect the evaluationrare-positive pipelinetraining fold onlyweights / SMOTE / pipelinefit scorenot a decision yetlower thresholdhigher thresholdselect on validation · test oncehyperparameter searchgrid: planned combinationsrandom: broad budgeted samplesBayesian: use prior trialsOptuna: a library for searchsame folds · same metric · fixed budgetnever create synthetic rows before the split — they can leak into validation and test evidence
FIG 01-07.2— class weights, oversampling, and SMOTE belong inside each training fold. Validation and test rows must remain real, untouched evidence. Thresholds turn learned scores into workload and should be selected on validation data.
  • 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.

  1. Train on earlier weeks; preserve whole incidents and later weeks for validation and test.
  2. Compare a simple baseline, class-weighted model, and threshold policy.
  3. Measure PR-AUC plus precision and recall at the human team’s daily capacity.
  4. Fit scalers and resampling inside each training fold.
  5. Review misses and false alarms with operators, including service and region slices.
  6. 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

warmup · 1

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.

core · 2

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.

stretch · 3

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

1What pattern most strongly suggests overfitting?
2What does L2 regularisation penalise?
3Where must SMOTE run during cross-validation?
4What is the honest role of a hyperparameter search?

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.

  1. Run the starter code and compare two candidates.
  2. Identify the likely underfit or overfit pattern.
  3. Choose one regularisation or capacity experiment and state what evidence would change your mind.
  4. Explain why resampling remains inside training folds.
  5. 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 day

Candidate 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 8

Revision and interview questions

  1. Explain bias, variance, underfitting, and overfitting using training and validation curves.
  2. Calculate L1 and L2 penalties and explain why their effects differ.
  3. Design a leakage-safe class-imbalance evaluation with weights, SMOTE, metrics, and threshold selection.
  4. Compare grid, random, and Bayesian search under a fixed trial budget.
  5. 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

balance the learning, protect the evaluationrare-positive pipelinetraining fold onlyweights / SMOTE / pipelinefit scorenot a decision yetlower thresholdhigher thresholdselect on validation · test oncehyperparameter searchgrid: planned combinationsrandom: broad budgeted samplesBayesian: use prior trialsOptuna: a library for searchsame folds · same metric · fixed budgetnever create synthetic rows before the split — they can leak into validation and test evidence

Code pattern

objective = loss + strength × penalty · fit training folds · choose validation settings · report once on test

Watch 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

  1. Is this gap a data problem or variance?
  2. Which error matters at capacity?
  3. Where can synthetic rows safely exist?

Lesson checklist

0 of 8 complete

Resources

Next up
Pipelines, interpretability & adjacent problems
You can now control complexity and evaluate choices. Next, keep transformations reproducible in pipelines, inspect model behaviour carefully, and distinguish time-series, recommender, and causal questions from ordinary tabular prediction.