Build stratified K-fold validation folds by dealing each class round-robin

Why it matters Fraud, churn and medical datasets are imbalanced, and an unstratified split can leave a fold with almost no positives, making metrics jump wildly.

Stratified K-fold keeps each class's share roughly equal in every fold, which matters when one class is rare.

Write stratified_kfold(y, k). y is a list of labels. For each class (in sorted label order), take that class's indices in their original order and deal them out like cards: the j-th index of the class goes to fold j % k, with j restarting at 0 for every class. Return a list of k validation folds, each a sorted list of indices.

Signaturedef stratified_kfold(y, k)

Example

y [0, 1, 0, 1, 0, 1], k 2 gives [[0, 1, 4, 5], [2, 3]].

Understand the idea

K-fold cross-validation splits the data into k parts and uses each part once for validation. Stratified K-fold also makes sure every part has about the same mix of labels, like a teacher dividing a class into teams so that each team gets some strong and some weak players.

Worked example: y = 0, 1, 0, 1, 0, 1 with k = 2. Class 0 sits at indices 0, 2, 4; dealing them gives fold 0: 0, 4 and fold 1: 2. Class 1 sits at 1, 3, 5; dealing gives fold 0: 1, 5 and fold 1: 3. Final folds: [0, 1, 4, 5] and [2, 3], and each fold has both classes.

Rule: for each class c, its j-th index goes to fold j mod k.

Without stratification, a rare positive class (say 2% fraud) can vanish from a fold. Production code usually shuffles each class first with a fixed seed, then deals exactly like this.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplestratified_kfold([0, 1, 0, 1, 0, 1], 2)
  • Sample 2: rare classstratified_kfold(['no', 'no', 'no', 'no', 'no', 'no', 'yes', 'yes', 'yes'], 3)
  • Test 3: unorderedstratified_kfold([1, 0, 1, 1, 0, 0, 1], 2)
  • Test 4: k larger than classstratified_kfold([2, 2, 5], 3)