📘
K-Fold Cross-Validation Indices
MediumModel Evaluation
Generate the train and validation index splits for K-Fold cross-validation.
Given n data points and k folds, divide indices [0,1,...,n−1] into k approximately equal folds. For each fold i, use fold i as validation and the remaining folds as training.
Return a list of k 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 n is not evenly divisible, the first nmodk 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=5 data points into k=3 folds. Since 5 is not evenly divisible by 3, we calculate the size of each fold as 35=1 with a remainder of 2. This means the first 2 folds will have 2 elements, and the last fold will have 1 element.
- We then split the indices [0,1,...,4] into 3 folds: fold 0 gets indices [0,1], fold 1 gets indices [2,3], and fold 2 gets index [4].
- For each fold i, we use the indices in fold i as validation and the remaining folds as training. So for fold 0, the validation indices are [0,1] and the training indices are [2,3,4]. For fold 1, the validation indices are [2,3] and the training indices are [0,1,4]. For fold 2, the validation indices are [4] and the training indices are [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
Python 3.13.1
Test Results
0/0Run code to see test results.