Skip to content
DeepForgeby svx
All problems
MediumML Fundamentalsml-010

K-Fold Split Indices

Problem

Generate k-fold cross-validation splits for n samples (indices 0..n-1).

Return a list of k entries, each of the form [train_indices, val_indices].

Distribute samples so that the first (n % k) folds get one extra sample. Train indices are everything except the validation indices for that fold.

Hint

Slice the indices into k contiguous chunks; train is the complement of val.

Test cases

case 1
in: [6,3]
expected: [[[2,3,4,5],[0,1]],[[0,1,4,5],[2,3]],[[0,1,2,3],[4,5]]]
case 2
in: [4,2]
expected: [[[2,3],[0,1]],[[0,1],[2,3]]]
case 3
in: [5,5]
expected: [[[1,2,3,4],[0]],[[0,2,3,4],[1]],[[0,1,3,4],[2]],[[0,1,2,4],[3]],[[0,1,2,3],[4]]]
Starter codePython
def kfold_indices(n, k):
    # Returns list of [train_indices, val_indices]
    # Your code here
    pass

3 test cases · run your code against them in the editor