5.6.5 · D4Machine Learning (Aerospace Applications)

Exercises — Cross-validation — k-fold

2,313 words11 min readBack to topic
Figure — Cross-validation — k-fold

Throughout, = number of samples, = number of folds, = the metric measured on fold when it is the test set, and


Level 1 — Recognition

Exercise 1.1 (L1)

You run -fold cross-validation. How many models get trained in total, and how many times does each single data point appear in a test set across the whole procedure?

Recall Solution
  • Models trained: one per fold, so models.
  • Test appearances per point: the whole point of k-fold is that every sample lands in the test fold exactly once. So each point is tested time (and used for training in the other rounds).

Look at figure s01: follow any single row across the four columns — it is coloured "test" (pink) in exactly one column and "train" (blue) in the other three.

Exercise 1.2 (L1)

A dataset has samples split into folds of equal size. In one round of the loop, how many samples are in the training set and how many in the test set?

Recall Solution

Each fold holds samples.

  • Test set = one fold = samples.
  • Training set = the other folds = samples.

Exercise 1.3 (L1)

Three fold scores come back as . What is ?

Recall Solution

We take the mean because averaging independent estimates reduces variance — no single fold's luck dominates.


Level 2 — Application

Exercise 2.1 (L2)

You have flight records and choose . Write the size of the training set for each fold, and confirm what fraction of the data trains each model.

Recall Solution

Fold size .

  • Test set , training set .
  • Fraction used for training .

This is why k-fold estimates are close to full-data performance: every model still sees of everything, unlike LOOCV's tiny hold-out (see 5.6.06-Leave-one-out-cross-validation-(LOOCV)).

Exercise 2.2 (L2)

Five folds give F1 scores . Compute the CV mean and the sample standard deviation (use in the denominator).

Recall Solution

Mean: Deviations from mean (each ): Squared: , sum . Sample variance: divide by : Std: . So report .

We divide by , not , because we already "spent" one degree of freedom estimating the mean; using would systematically underestimate the spread.

Exercise 2.3 (L2)

Your dataset is sorted by flight date. You run plain KFold with shuffle=False. Why can this give a misleadingly low CV score, and what one-word fix removes the problem?

Recall Solution

With shuffle=False, fold 1 = oldest flights, fold 5 = newest. Each round tests on a time-contiguous block that may differ systematically from the training block (older engines, seasonal weather, different routes). The model is asked to generalise across a distribution shift it never trained on, so scores drop — but this reflects the split, not the model. Fix: shuffle (shuffle=True), which makes each fold a random sample of all dates. ⚠️ Exception: if the task is genuinely a forecast, you must not shuffle — use 8.5.02-Time-series-cross-validation instead.


Level 3 — Analysis

Exercise 3.1 (L3)

Model A gives over folds; Model B gives . A colleague says "B is better, ship it." Argue the case both ways and state what you would actually do.

Recall Solution
  • For B: its mean F1 () beats A's ().
  • Against B: its spread () is over four times A's (). A worst-plausible fold for B sits near , below A's worst fold near . B is inconsistent — its score depends heavily on which slice of data it sees, a red flag for a safety task.
  • What to do: the means are only apart while B's std is ; the difference is not clearly significant. Run a paired comparison across the same folds, or increase /repeats. In aerospace, prefer the model whose lower bound is safest — often A. See 5.6.10-Bias-variance-tradeoff-in-model-selection.

Exercise 3.2 (L3)

You increase from to (LOOCV). Predict the qualitative change in bias and variance of the estimate, and explain the mechanism for each.

Recall Solution
  • Bias ↓ (lower): each training set now has samples, almost the full dataset, so each model's performance is nearly what the full-data model would achieve. Small- models train on only of the data and slightly under-perform, biasing the estimate pessimistically.
  • Variance ↑ (higher): two mechanisms. (1) Each test set is a single sample, so each is or -ish — extremely noisy. (2) The training sets overlap in of their samples, so the models are almost identical and their errors are correlated; averaging correlated numbers barely reduces variance.
  • Net: LOOCV trades bias for variance, and costs model fits. That is why or is the usual sweet spot.

Exercise 3.3 (L3)

Failures occur in of flights ( positives). With plain shuffled KFold and , one fold happens to receive only positive labels. Explain numerically why this wrecks that fold's F1, and name the fix.

Recall Solution

Each fold has samples; the expected positives per fold are . A fold with only positives means:

  • Recall is measured over just true positives — miss one and recall drops from to ; a single mistake swings the score wildly.
  • The training folds now hold positives concentrated elsewhere, so class balance differs round to round, injecting extra variance.

Fix: Stratified k-fold (5.6.04-Stratified-sampling) forces each fold to hold positives, i.e. per fold, stabilising every .


Level 4 — Synthesis

Exercise 4.1 (L4)

You must tune a Random Forest's max_depth over candidate values and report an honest final performance estimate. A junior engineer proposes: "Run -fold CV for each depth, pick the best CV score, and report that best CV score as the final number." Identify the flaw and design the correct procedure.

Recall Solution
  • Flaw: the CV score was used to choose max_depth. Reporting that same score as the final estimate is optimistically biased — you peeked at the validation folds to make a decision, so they are no longer unseen. The best-of- CV scores is inflated by selection.
  • Correct design — nested CV (5.6.07-Nested-cross-validation):
    • Outer loop ( folds): each outer training set is passed to an inner CV that tunes max_depth (this is grid search, 7.2.03-Hyperparameter-tuning-grid-search).
    • The winning depth is refit on the whole outer-training set and scored once on the untouched outer-test fold.
    • Average the outer-test scores → the honest estimate.
  • The key principle: the data used to select a model must be disjoint from the data used to estimate its performance.

Exercise 4.2 (L4)

Total compute budget: you can afford at most model fits. You want to (a) tune hyperparameter settings and (b) get a nested, unbiased estimate. Choose the outer and inner so total fits , and count them.

Recall Solution

Nested-CV fit count (ignoring the final refits, or counting them separately): Try : That exactly hits the budget. If you also count one refit per outer fold ( extra fits) you'd exceed it, so drop to : fits, leaving room. Either at the ceiling or with headroom is defensible; state your assumption.


Level 5 — Mastery

Exercise 5.1 (L5)

An aerospace team has labelled flights from 8 different aircraft, flights each. Failures are rare (). They want a CV estimate that (i) does not leak information between flights of the same physical aircraft, and (ii) preserves the failure rate per fold. Design the splitting scheme and justify each choice. Then state how many folds are natural.

Recall Solution
  • Leakage risk: two flights from the same aircraft share serial-number-specific sensor quirks. If some flights of aircraft #3 are in training and others in test, the model can "recognise" that aircraft rather than learn general failure signatures — optimistic and unsafe. So splits must be at the aircraft (group) level: all flights of an aircraft go entirely to train or entirely to test. This is group k-fold.
  • Class balance: with failures we also want each fold near — that argues for stratification. Combining both gives stratified group k-fold: partition by aircraft while balancing the failure rate across groups.
  • Natural : aircraft → up to folds, each fold = the flights of one held-out aircraft (a group-LOOCV over aircraft). If is too costly or too variable, group them aircraft per fold for .
  • Why this is the mastery answer: it simultaneously respects the two independence assumptions k-fold silently relies on — that (a) folds are disjoint in the units that matter (aircraft, not rows), and (b) each fold represents the true label distribution.

Exercise 5.2 (L5)

Prove that if every fold scored identically ( for all ), then and , and explain in one sentence what a real-world would (suspiciously) imply.

Recall Solution

Mean: Std: each deviation , so the sum of squares is and Interpretation: in practice fold scores are never exactly equal; a reported almost always signals a bug — e.g. the same data leaked into every fold, or the metric is being computed on the training set. Perfect consistency is a warning, not a trophy.


Recall Quick self-check (cloze)

k-fold trains == models, and each sample is tested exactly once==. The training fraction per model is ::: Sample std of fold scores divides the sum of squares by ::: Fix for rare-class folds ::: stratified k-fold Fix for same-aircraft leakage ::: group (aircraft-level) k-fold Honest estimate while tuning hyperparameters ::: nested cross-validation