K-Fold Cross-Validation Splits

easy
Unit 2 · Evaluation & Preprocessing0/3 to milestone

A single train/test split can be lucky or unlucky. K-fold cross-validation splits the data into kk folds and evaluates kk times, each time holding out a different fold.

Implement kfold_indices(n, k, shuffle=False, seed=0) returning a list of k (train_idx, val_idx) pairs of NumPy integer arrays.

Rules (these match scikit-learn's KFold)

  • Start with the indices 0 … n-1. If shuffle is true, use np.random.default_rng(seed).permutation(n) instead.
  • Fold sizes are n // k, with the first n % k folds getting one extra element.
  • Folds are consecutive slices of that index order. Each fold is the validation set once, and everything else is the training set, kept in order.

Example

kfold_indices(7, 3)
# [([3, 4, 5, 6], [0, 1, 2]), ([0, 1, 2, 5, 6], [3, 4]), ([0, 1, 2, 3, 4], [5, 6])]
#evaluation#numpy3 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
K-Fold Cross-Validation Splits · TechGradify