Cross-validation and micro and macro averaging
Cross-validation gives an estimate of a model's generalisation error by reusing data splits; micro and macro averaging are two ways to combine per-class precision/recall/F1 in multiclass evaluation.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Engineers use cross-validation to estimate how well a machine learning model will perform on new (unseen) data when the available labelled data is limited. When a classification problem has many classes or class imbalance, engineers use micro-averaging and macro-averaging to summarise precision, recall and F1 across classes so they can compare models fairly.
Key ideas
Definitions (bold the first time each term is used):
Cross-validation (CV): a set of methods to estimate the generalisation error of a learning algorithm by splitting labelled data into training and validation (test) parts multiple times and averaging the validation loss. Assumes data are independent and identically distributed (IID) and representative of the target distribution.
k-fold cross-validation: split the dataset into k disjoint folds of (approximately) equal size. For i = 1..k, train the model on the k−1 other folds and evaluate on fold i. The k-fold CV estimate is the average of the k validation losses. Assumes folds preserve IID property; with classification one often uses stratified folds to keep class proportions.
Leave-one-out cross-validation (LOOCV): the extreme case of k-fold where k = n (n = number of samples). Each fold contains exactly one sample as validation; model is trained on n−1 samples. LOOCV provides nearly unbiased estimate of the error for some models but usually has high variance and high computational cost.
Stratified cross-validation: a variant of k-fold CV for classification where each fold preserves the class proportion of the whole dataset. This helps when classes are imbalanced.
Holdout validation: one simple split into a training set and a validation set (e.g., 70/30). Simpler but higher variance in the estimate because it uses fewer training samples and only one split.
Micro-averaging: for multiclass classification, compute global counts of true positives (TP), false positives (FP) and false negatives (FN) across all classes and then compute precision/recall/F1 from these totals. Micro-averaging weights each sample equally.
Macro-averaging: compute precision/recall/F1 for each class separately, then average these per-class metrics equally. Macro-averaging weights each class equally regardless of class size.
Confusion matrix (multiclass): a C×C table for C classes where entry (i, j) is the number of samples whose true class is i but predicted class is j. Diagonal entries are true positives per class.
Precise CV formula and assumptions:
Let D be the dataset of n IID samples. Partition D into k folds D1, D2, …, Dk. Let L(model, Dx) be the average loss (e.g., 0–1 loss for classification) evaluated on data Dx. For fold i, train model on D \ Di to obtain model_i, and compute validation loss Li = L(model_i, Di).
The k-fold cross-validation estimate of the generalisation loss is the average
E_CV = (1/k) * sum_{i=1..k} L_i.
Assumptions and properties commonly asked in exams:
Assumes IID samples and that each validation fold is disjoint from its corresponding training data (no sample appears in both). Note that per-fold training sets overlap across i, so the L_i are correlated. The CV estimate targets the expected loss of a model trained on n*(k−1)/k samples (slightly pessimistic compared to training on all n), and is approximately unbiased under stable training procedures that do not depend on sample order. For non-IID data (e.g., time series, grouped/clustered data), use appropriate blocked/forward-chaining or grouped CV instead of random k-fold.
LOOCV: training sets are almost the full dataset (n−1 samples), so LOOCV has lower bias compared to small-k CV; however LOOCV folds are highly correlated so the CV estimate has higher variance. This trade-off is standard: small k (e.g., 2) gives higher bias and lower variance in some cases; large k (LOOCV) gives lower bias and higher variance. Typical practical choice is k = 5 or k = 10.
For models where training is deterministic and loss is measured on disjoint sets, the k-fold CV estimate equals the mean of the per-fold losses (exact equality by definition).
Diagrams to draw (describe exactly):
For k-fold CV: Draw k rectangles labelled Fold 1, Fold 2, … Fold k arranged left-to-right. Draw arrows showing: for Fold 1 arrow from all other folds to a box labelled Train_1, and arrow from Fold 1 to a box labelled Validate_1. Repeat for Fold 2 etc. Label the final box as E_CV = mean(L1,..,Lk).
For a multiclass confusion matrix: Draw a 3×3 table for classes A,B,C with rows = Actual and columns = Predicted. Put numbers in each cell (example values are used in worked examples below). Mark TP for each class as diagonal cell, FP for class j as the column j off-diagonal entries, FN for class j as row j off-diagonal entries.
Uncertainties (please check):
- I state the practical bias/variance behaviours of LOOCV vs small-k CV qualitatively (above); check if you want a formal statement or references to specific theorems. See verify list.
Formulas
E_CV = (1/k) * sum_{i=1..k} L_i — E_CV: k-fold CV estimate (unitless loss), k: number of folds, L_i: validation loss on fold i (unitless). Applies to any loss averaged per-sample.
L_i = (1/|D_i|) * sum_{x in D_i} loss(model_{-i}(x), y) — L_i: average loss on fold i; |D_i| is number of samples in fold i (unitless); loss(...) is per-sample loss (unitless).
s^2 = (1/(k-1)) * sum_{i=1..k} (L_i - E_CV)^2 — sample variance of fold losses (unitless). Assumes k>1.
SE = s / sqrt(k) — standard error of the mean CV loss (unitless). Assumes fold losses are approximately independent (an approximation; in practice they are correlated so SE underestimates true uncertainty).
For classification metrics (per-class j):
precision_j = TP_j / (TP_j + FP_j) — proportion of predicted class-j samples that are correct (unitless). If denominator is 0, precision is undefined (handle as 0 or skip class as per convention).
recall_j = TP_j / (TP_j + FN_j) — proportion of actual class-j samples correctly predicted (unitless).
F1_j = 2 * precision_j * recall_j / (precision_j + recall_j) — harmonic mean of precision and recall for class j (unitless).
Macro-averages:
precision_macro = (1/C) * sum_{j=1..C} precision_j — average of per-class precisions (unitless).
recall_macro = (1/C) * sum_{j=1..C} recall_j — average of per-class recalls (unitless).
F1_macro = (1/C) * sum_{j=1..C} F1_j — average of per-class F1 scores (unitless). Note: this is the usual definition of macro-F1; some texts define macro-F1 as F1 calculated from macro-precision and macro-recall — be explicit in answer which definition you use.
Micro-averages (global counts):
TP_total = sum_{j=1..C} TP_j, FP_total = sum_{j=1..C} FP_j, FN_total = sum_{j=1..C} FN_j — totals across classes (unitless).
precision_micro = TP_total / (TP_total + FP_total) — micro-precision (unitless).
recall_micro = TP_total / (TP_total + FN_total) — micro-recall (unitless).
F1_micro = 2 * precision_micro * recall_micro / (precision_micro + recall_micro) — micro-F1 (unitless). For single-label multiclass problems where every sample has exactly one true label and exactly one predicted label, precision_micro = recall_micro = accuracy = TP_total / total_samples.
Worked examples
Example 1 — 5-fold cross-validation numeric (university exam style)
Dataset: 100 labelled samples (no units). You run stratified 5-fold CV and get per-fold validation error rates (0–1 loss) as:
Fold 1 error L1 = 0.10 Fold 2 error L2 = 0.12 Fold 3 error L3 = 0.08 Fold 4 error L4 = 0.11 Fold 5 error L5 = 0.09
Step 1: Compute E_CV = (1/5)*(0.10+0.12+0.08+0.11+0.09)
E_CV = 0.10 (unitless, error rate)
Step 2: Compute sample variance s^2 of the five L_i:
Deviations: 0, +0.02, −0.02, +0.01, −0.01. Squared sum = 0 + 0.0004 + 0.0004 + 0.0001 + 0.0001 = 0.001.
s^2 = 0.001 / (5 - 1) = 0.00025 (unitless)
s = sqrt(0.00025) = 0.0158113883 (unitless)
Step 3: Standard error of mean
SE = s / sqrt(5) = 0.0158113883 / 2.236067977 = 0.0070710678 (unitless)
Final answer: Cross-validation estimate = 0.10 ± 0.00707 (error rate). Explain: this means estimated error 10% with SE ≈ 0.71 percentage points.
Example 2 — micro and macro averaging (numerical confusion matrix)
Consider 3 classes A, B, C. Confusion matrix (rows = Actual, columns = Predicted):
- Actual A: Pred A=40, Pred B=5, Pred C=5 (total actual A = 50)
- Actual B: Pred A=8, Pred B=30, Pred C=2 (total actual B = 40)
- Actual C: Pred A=2, Pred B=3, Pred C=25 (total actual C = 30)
Total samples = 50 + 40 + 30 = 120.
Per-class counts (extract):
Class A: TP_A = 40, FP_A = predictions A but actual not A = 8 + 2 = 10, FN_A = actual A but predicted not A = 5 + 5 = 10.
Class B: TP_B = 30, FP_B = 5 + 3 = 8, FN_B = 8 + 2 = 10.
Class C: TP_C = 25, FP_C = 5 + 2 = 7, FN_C = 2 + 3 = 5.
Compute per-class precision, recall, F1:
precision_A = 40 / (40 + 10) = 40/50 = 0.80000 recall_A = 40 / (40 + 10) = 40/50 = 0.80000 F1_A = 20.80.8/(0.8+0.8) = 0.80000
precision_B = 30 / (30 + 8) = 30/38 = 0.78947 recall_B = 30 / (30 + 10) = 30/40 = 0.75000 F1_B = 20.789470.75/(0.78947+0.75) = 0.76923 (rounded)
precision_C = 25 / (25 + 7) = 25/32 = 0.78125 recall_C = 25 / (25 + 5) = 25/30 = 0.83333 F1_C = 20.781250.83333/(0.78125+0.83333) = 0.80645 (rounded)
Macro-averages (simple mean of per-class metrics):
precision_macro = (0.80000 + 0.78947 + 0.78125)/3 = 0.79024 recall_macro = (0.80000 + 0.75000 + 0.83333)/3 = 0.79444 F1_macro = (0.80000 + 0.76923 + 0.80645)/3 = 0.79189
Micro-averages (global counts):
TP_total = 40 + 30 + 25 = 95 FP_total = 10 + 8 + 7 = 25 FN_total = 10 + 10 + 5 = 25
precision_micro = TP_total / (TP_total + FP_total) = 95 / 120 = 0.79167 recall_micro = TP_total / (TP_total + FN_total) = 95 / 120 = 0.79167 F1_micro = 0.79167 (same) — for single-label multiclass problems micro-F1 = accuracy = 95/120 = 0.79167.
Interpretation: Macro averages treat each class equally, while micro averages weight by class frequency. Here macro-F1 = 0.79189, micro-F1 = 0.79167 (very close because class sizes and per-class performance are similar).
Worked-theory example (model answer style)
Question: Explain why stratified k-fold is preferred over random k-fold for highly imbalanced classification. Provide the effect on per-fold variance and on average estimates.
Model answer (short): Stratified k-fold preserves class proportions in each fold, so each validation fold contains examples of every class (as far as possible). This reduces the variance of per-fold loss estimates and prevents some folds from missing minority classes entirely (which would make per-fold precision/recall undefined or unstable). Therefore stratified k-fold leads to more stable and reliable CV estimates for imbalanced classification than non-stratified random splits. Note the assumption: class-conditional distribution is approximately the same across folds (IID condition); with extreme imbalance and tiny minority counts, even stratification cannot fully stabilise variance.
Common mistakes
Reporting CV standard error using independent-fold formula without noting fold losses are correlated: SE formula
s/sqrt(k)underestimates uncertainty because Li are not independent; mention this caveat.Using LOOCV blindly for complex models: LOOCV is computationally costly and can have high variance; do not claim it always gives the best estimate.
Forgetting to stratify for classification with imbalance: leads to folds with no examples of some classes.
Mixing up FP/FN when converting a multiclass confusion matrix to per-class FP/FN: use column sums and row sums carefully (FP for class j = column j sum minus TP_j; FN for class j = row j sum minus TP_j).
For your exam
Typical question types and what to include in full-marks answers:
Definitions: Give clear, concise definitions of cross-validation, k-fold, LOOCV, stratified CV, micro-averaging, macro-averaging. State assumptions (IID, representativeness).
Short notes: Compare k choices (k=5,10,LOOCV): discuss bias vs variance and computation cost; state practical recommendation (k = 5 or 10) and why.
Derivations: Show derivation of E_CV = mean of per-fold losses and compute sample variance and SE as shown. For linear regression questions you may be asked to show LOOCV formula using the hat matrix — mention that as an advanced topic and reference hat-matrix identity.
Numericals: Compute E_CV and SE as in worked example; compute micro and macro precision/recall/F1 from a confusion matrix. Show step-by-step bookkeeping of TP, FP, FN.
Diagrams: Draw k-fold split and multiclass confusion matrix as described; label folds, training and validation sets, and show averaging.
Practical notes: Mention stratification for classification; repeated CV (repeat k-fold with different random splits) to reduce variance; and that CV results should be used with an outer test set for final evaluation when tuning hyperparameters (nested CV concept — reference it by name but do not explain here).
Quick check
- What is the k-fold CV estimate E_CV if fold losses are 0.2, 0.1, 0.15 for k=3?
- If TP_total = 80, total samples = 200 in single-label multiclass, what is precision_micro?
- If class j has TP=10, FP=5, FN=15, what are precision_j, recall_j and F1_j (two decimal places)?
Answers: E_CV = 0.15; precision_micro = 80/200 = 0.40; precision_j = 10/(10+5)=0.67, recall_j = 10/(10+15)=0.40, F1_j = 20.670.40/(0.67+0.40)=0.50 (rounded).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?