PIXELBANKv8.2.1
Menu

K-Fold Cross-Validation Indices

Generate the train and validation index splits for K-Fold cross-validation.

Given nn data points and kk folds, divide indices [0,1,...,n1][0, 1, ..., n-1] into kk approximately equal folds. For each fold ii, use fold ii as validation and the remaining folds as training.

Return a list of kk tuples: [(train_indices, val_indices), ...] where each set of indices is a sorted list.

Split the indices sequentially (first n//k go to fold 0, next to fold 1, etc.). If nn is not evenly divisible, the first nmodkn \mod k folds get one extra element.

Example:

Input:
n = 5, k = 3
Output:
[([2, 3, 4], [0, 1]), ([0, 1, 4], [2, 3]), ([0, 1, 2, 3], [4])]
Reasoning:
  • First, we divide the n=5n = 5 data points into k=3k = 3 folds. Since 55 is not evenly divisible by 33, we calculate the size of each fold as 53=1\frac{5}{3} = 1 with a remainder of 22. This means the first 22 folds will have 22 elements, and the last fold will have 11 element.
  • We then split the indices [0,1,...,4][0, 1, ..., 4] into 33 folds: fold 00 gets indices [0,1][0, 1], fold 11 gets indices [2,3][2, 3], and fold 22 gets index [4][4].
  • For each fold ii, we use the indices in fold ii as validation and the remaining folds as training. So for fold 00, the validation indices are [0,1][0, 1] and the training indices are [2,3,4][2, 3, 4]. For fold 11, the validation indices are [2,3][2, 3] and the training indices are [0,1,4][0, 1, 4]. For fold 22, the validation indices are [4][4] and the training indices are [0,1,2,3][0, 1, 2, 3].
  • The final output is a list of these training and validation index splits: [([2, 3, 4], [0, 1]), ([0, 1, 4], [2, 3]), ([0, 1, 2, 3], [4])]

Constraints:

  • n >= k >= 2
  • Return list of (train_indices, val_indices) tuples
  • Indices in each list should be sorted
  • Folds are sequential (not shuffled)
Editor

Test Results

0/0
Run code to see test results.