Generate K-fold train and validation index splits

Cross-validation reports a score that does not depend on one lucky split.

Write kfold_indices(n, k). Split range(n) into k contiguous folds in order. The first n % k folds get one extra element. Return a list of k tuples (train_idx, val_idx) of int arrays, where fold i is the validation set and the rest, in order, is the training set.

Signaturedef kfold_indices(n, k)

Example

kfold_indices(5, 2) gives val [0, 1, 2] then val [3, 4].

Understand the idea

K-fold cross-validation splits the data into k parts, uses each part once as the validation set and trains on the rest, so the final score does not depend on one lucky split. Here the folds are contiguous blocks in order, and when n does not divide evenly, the first n % k folds get one extra item, so all folds differ in size by at most one. Worked example: n = 7, k = 3. 7 // 3 = 2 with remainder 1, so sizes are [3, 2, 2]. Fold 0 validates [0, 1, 2] and trains on [3, 4, 5, 6]. Fold 1 validates [3, 4] and trains on [0, 1, 2, 5, 6]. Fold 2 validates [5, 6] and trains on [0, 1, 2, 3, 4]. Rule: size_i = n // k + (1 if i < n % k else 0); walk a start pointer through range(n) cutting blocks of those sizes; for each fold return (train indices in original order, validation indices) as int arrays. Putting the whole remainder in the last fold makes it bigger than the rest. Used in model selection and hyperparameter tuning when data is small.

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

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

  • Sample 1: examplekfold_indices(5, 2)
  • Sample 2: ten in three[v.tolist() for _, v in kfold_indices(10, 3)]
  • Test 3: train sets[t.tolist() for t, _ in kfold_indices(7, 3)]