2.6.5Model Evaluation & Selection

Stratified and leave-one-out cross-validation

3,671 words17 min readdifficulty · medium1 backlinks

Overview

While k-fold cross-validation randomly splits data, stratified cross-validation preserves the class distribution in each fold, and leave-one-out cross-validation (LOOCV) uses exactly one sample for testing. Both address specific weaknesses in standard k-fold CV.


Core Concepts


Stratified Cross-Validation: From First Principles

Why Stratification Matters

Setup: Dataset with n samples, C classes with counts n1,n2,...,nCn_1, n_2, ..., n_C where i=1Cni=n\sum_{i=1}^{C} n_i = n.

Class proportions: pi=ninp_i = \frac{n_i}{n} for class ii.

In random k-fold CV, each fold should ideally have nk\frac{n}{k} samples with class ii count nik\approx \frac{n_i}{k}. But random sampling introduces variance.

Expected deviation: For small nin_i (minority classes), random splits can produce folds with zero samples of that class.

Probability of missing a minority class in one fold (approximation): P(fold missing class i)(11k)niP(\text{fold missing class } i) \approx \left(1 - \frac{1}{k}\right)^{n_i}

For k=5k=5, ni=10n_i=10: P(0.8)100.107P \approx (0.8)^{10} \approx 0.107 — about 10% chance of a fold missing this class entirely.

Stratification Algorithm

Goal: Ensure each fold has exactly nik\frac{n_i}{k} samples from class ii (or as close as possible when nin_i is not divisible by kk).

Step-by-step derivation:

  1. Partition by class: Separate dataset into C groups: D1,D2,..,DCD_1, D_2, .., D_C where Di=ni|D_i| = n_i

  2. Per-class folding: For each class ii, create k sub-folds: Di(1),Di(2),...,Di(k)D_i^{(1)}, D_i^{(2)}, ..., D_i^{(k)} Size of each sub-fold: nik\left\lfloor \frac{n_i}{k} \right\rfloor or nik\left\lceil \frac{n_i}{k} \right\rceil

  3. Combine across classes: Fold jj = D1(j)D2(j)...DC(j)D_1^{(j)} \cup D_2^{(j)} \cup ... \cup D_C^{(j)}

Why this works: Each fold jj now contains: Fjclass i=nik±1|F_j \cap \text{class } i| = \frac{n_i}{k} \pm1

The class proportion in fold jj: Fjclass iFj=ni/kn/k=nin=pi\frac{|F_j \cap \text{class } i|}{|F_j|} = \frac{n_i/k}{n/k} = \frac{n_i}{n} = p_i

The fold maintains the original class distribution!


Leave-One-Out Cross-Validation: From First Principles

The Extreme Case: k = n

Standard k-fold uses< n. What happens as k increases?

k = 2: Each fold has n/2 samples, train on 50% of data k = 5: Each fold has n/5 samples, train on 80% of data k = 10: Each fold has n/10 samples, train on 90% of data k = n: Each fold has 1 sample, train on (n-1)/n ≈ 100% of data

LOOCV is the limit: maximum training data per iteration.

Bias-Variance Tradeoff in CV

The test error estimate from CV has two components:

E[CV Error]=Bias+VarianceE[\text{CV Error}] = \text{Bias} + \text{Variance}

Bias (how far the estimate is from true test error):

  • Higher k → larger training set → model closer to final model → lower bias
  • Lower k → smaller training set → model worse than final model → higher bias

Variance (how much the estimate fluctuates):

  • Higher k → more folds, more overlapping training sets → higher variance
  • Lower k → fewer folds, more independent training sets → lower variance

LOOCV bias: BiasLOOCV0\text{Bias}_{\text{LOOCV}} \approx 0

Why? Training on n-1 samples is almost identical to training on n samples. The model being validated is essentially the final model.

LOOCV variance: VarLOOCV1n2i=1nj=1nCov(ϵi,ϵj)\text{Var}_{\text{LOOCV}} \approx \frac{1}{n^2} \sum_{i=1}^{n} \sum_{j=1}^{n} \text{Cov}(\epsilon_i, \epsilon_j)

The n training sets overlap by n-2 samples, creating high correlation between error estimates.

Computational Cost Analysis

Standard k-fold: Train k models, each on k1kn\frac{k-1}{k} \cdot n samples

LOOCV: Train n models, each on n-1 samples

Ratio: LOOCV requires nk\frac{n}{k} times more training than k-fold.

For k=10, n=1000: LOOCV requires 100× more computation.

Special case - Linear models: Closed-form shortcut exists. For ordinary least squares:

CVLOOCV=1ni=1n(yiy^i1hii)2\text{CV}_{\text{LOOCV}} = \frac{1}{n} \sum_{i=1}^{n} \left(\frac{y_i - \hat{y}_i}{1 - h_{ii}}\right)^2

where y^i\hat{y}_i is the prediction from the model trained on all n samples, and hiih_{ii} is the leverage (diagonal of the hat matrix).

Why this works? The leave-one-out prediction can be computed from the full model without refitting. Training once gives all n LOOCV errors. Computation cost drops from O(n) model fits to O(1) model fit.


When to Use Each Method


Common Mistakes


Active Recall Practice

Recall Explain stratified CV to a12-year-old

Imagine you have a bag of 100 marbles: 70 red and 30 blue. You want to split them into 5 groups play a game.

Random split: You close your eyes and grab 20 marbles at a time. Sometimes you get 18red and 2 blue, sometimes 12 red and 8 blue. The groups are all different!

Stratified split: You separate the reds and blues first. Then take 14 red (70÷5) and 6 blue (30÷5) for each group. Now every group has exactly the same 14 red + 6 blue mix!

Why it matters: If you're testing how well your friend can guess marble colors, you want each test to be fair. With random splits, some tests are easier (more of one color) and some harder. With stratified splits, every test is equally hard because they all have the same mix.

LOOCV is even more extreme: Instead of 5 groups of 20 marbles, you make 100 groups—each group has 99 marbles for practice and 1 marble for testing. You test your friend 100 times! This takes forever but you learn the most about their guessing ability.


Connections 2.6.01-Training-validation-and-test-sets - Stratified CV is still a validation technique within train/val split

  • 2.6.03-K-fold-cross-validation - Stratified CV is a refinement of k-fold; LOOCV is k-fold with k=n
  • 2.6.04-Bias-variance-tradeoff-in-cross-validation - LOOCV minimizes bias but maximizes variance
  • 3.2.05-Handling-imbalanced-classes - Stratified CV is essential when classes are imbalanced
  • 2.3.08-Sampling-methods - Stratification is a form of stratified sampling applied to CV
  • 5.4.02-Time-series-cross-validation - Time series requires different CV; can't use LOOCV or random splits

#flashcards/ai-ml

What is the key difference between stratified CV and standard k-fold CV? :: Stratified CV preserves the class distribution in each fold by splitting each class separately then combining, while standard k-fold randomly splits all samples together which can create imbalanced folds

Why does LOOCV have lower bias than k-fold CV?
LOOCV trains on n-1 samples (almost all data), making the validated model nearly identical to the final model trained on all n samples, minimizing the gap between CV performance and true test performance
What is the computational cost ratio of LOOCV vs k-fold?
LOOCV requires n/k times more training than k-fold; for k=10 and n=1000, LOCV needs 100× more computation (1000 model fits vs 10)

Write the LOOCV error formula :: CVLOOCV=1ni=1nL(yi,f^(i)(xi))\text{CV}_{\text{LOOCV}} = \frac{1}{n} \sum_{i=1}^{n} L(y_i, \hat{f}^{(-i)}(x_i)) where f^(i)\hat{f}^{(-i)} is trained on all samples except i

When should you use stratified CV? :: When class imbalance exists and mini(pi)<2k\min_i(p_i) < \frac{2}{k} (smallest class proportion is less than 2/k), or when minority classes have fewer than 10 samples per fold

Why does LOOCV have high variance despite using all data?
The n training sets overlap by-2 samples, creating high correlation between error estimates; variance doesn't decrease with n because Var(eˉ)σ2\text{Var}(\bar{e}) \approx \sigma^2 due to correlation
How does stratified CV ensure class balance?
It splits each class into k groups separately, then combines one group from each class to form each fold, guaranteeing each fold has proportional class representation
What is the special property of LOOCV for linear models?
For OLS, LOOCV can be computed from a single model fit using 1n(yiy^i1hii)2\frac{1}{n}\sum(\frac{y_i - \hat{y}_i}{1-h_{ii}})^2 where hiih_{ii} is leverage, reducing cost from O(n) to O(1) fits
When is LOOCV preferred over k-fold?
When dataset is very small (n < 50-100), model training is fast, and you need minimum bias; avoid when n > 1000 or training is expensive
What happens if you use random5-fold on a 95%/5% imbalanced dataset?
Some folds might get 100% majority class or very few minority samples, causing the model to learn biased patterns and producing unreliable validation metrics

Concept Map

random splits cause

unreliable metrics on

variant preserving balance

extreme case k=n

solves

each fold keeps

algorithm

combine sub-folds

n samples means

trains on

tradeoff

k-fold CV

Unbalanced class folds

Minority classes missing

Stratified CV

LOOCV

Class distribution p_i = n_i/n

Partition by class then fold

Fold j from each class

n training cycles

n-1 samples per fold

Max data high compute cost

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Chalo ise simple tarike se samajhte hain. Jab hum normal k-fold cross-validation karte hain, toh data randomly split hota hai. Problem yeh hai ki agar aapke paas imbalanced data hai — jaise 90% negative aur sirf 10% positive samples — toh random split se koi fold mein shayad 100% negative hi aa jaayein aur positive samples bilkul na aayein. Aisa hone par model galat cheez seekhta hai aur aapke validation numbers reliable nahi rehte. Stratified cross-validation yahi problem solve karta hai — yeh ensure karta hai ki har fold mein original dataset waali hi class ratio maintain rahe. Matlab agar poore data mein 70% cats aur 30% dogs hain, toh har fold mein bhi 70:30 ratio hi milega.

Iska logic bhi seedha hai: pehle data ko class ke hisaab se alag karo, phir har class ko k barabar groups mein todo, aur phir har fold banane ke liye har class se ek-ek group utha ke combine kar do. Is tarah har fold mein saari classes proportional matra mein aa jaati hain. Doosra variant hai LOOCV (Leave-One-Out), jahan hum k ko extreme tak le jaate hain — agar n samples hain toh n folds banate hain, har baar n-1 samples pe train karke sirf 1 sample pe test. Isse maximum training data milta hai, lekin computational cost bhi utni hi zyaada ho jaati hai kyunki aapko n baar model train karna padta hai.

Yeh cheezein isliye important hain kyunki real-world data aksar imbalanced hota hai — medical diagnosis, fraud detection, rare disease prediction, in sabme minority class kam hoti hai lekin sabse important hoti hai. Agar aap stratification use nahi karenge toh aapka model evaluation galat picture dikhayega aur aapko lagega model achha kaam kar raha hai, jabki asal mein woh minority class ko pehchaan hi nahi pa raha. Isliye jab bhi imbalanced dataset ho, stratified CV default choice honi chahiye, aur jab data bahut kam ho tabhi LOOCV ka istemaal karein kyunki wahaan har ek sample keemti hota hai.

Go deeper — visual, from zero

Test yourself — Model Evaluation & Selection

Connections