K-Fold Cross-Validation: Every Example Tested Once

Data ProcessingMedium+15 XP+15

K-Fold Cross-Validation: Every Example Tested Once

One train/test split gives you one score, and that score depends on which examples happened to land in the test set. K-fold cross-validation removes that luck: chop the data into k equal blocks, then run k experiments, each using a different block as the test set and everything else for training. Every example gets tested exactly once.

Task: write k_fold_indices(n, k) returning a list of k pairs, [train_indices, test_indices], for a dataset of n examples numbered 0 to n - 1.

How the blocks are sized and placed:

  • Blocks are consecutive — fold 0 takes the first block, fold 1 the next, and so on. No shuffling.
  • n rarely divides evenly by k. Spread the remainder over the earliest folds, one extra each: with n = 7 and k = 3 the block sizes are 3, 2, 2.
  • For each fold, test_indices is its own block and train_indices is everything else, both in ascending order.

k is never larger than n, so no fold is ever empty.

The pay-off is that you end up with k scores instead of one. Their average is a far steadier estimate of real performance, and how much they disagree tells you how sensitive your model is to which data it happened to see.

Give Every Block a Turn

Run fold 1. That block becomes the testing set this round.

Fold 1
—
Fold 2
—
Fold 3
—
Fold 4
—
Fold 5
—

Examples

n = 6
k = 3
returns [[[2, 3, 4, 5], [0, 1]], [[0, 1, 4, 5], [2, 3]], [[0, 1, 2, 3], [4, 5]]]
n = 7
k = 3
returns [[[3, 4, 5, 6], [0, 1, 2]], [[0, 1, 2, 5, 6], [3, 4]], [[0, 1, 2, 3, 4], [5, 6]]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run