Neural Mastery
← Practice
K-Fold Cross-Validation Split Generationmedium

K-Fold Cross-Validation Split Generation

medium Classical ML from Scratch 15–20 min

NumPy allowed · plain Python earns 10 bonus points

LLM step 1/4

Logits become a next-token distribution

Softmax turns a model score vector into probabilities.
Open lesson →
01prompt
02tokens
03logits
04probabilities
attention→next token
mechanism65%
layer20%
pattern10%
model5%

Softmax(logits) → probability distribution

Implement the actual index bookkeeping behind k-fold cross-validation -- the fold-size arithmetic and train/validation partitioning every CV loop is built on top of, independent of whatever model gets trained on each fold.

Task

Implement k_fold_splits(n_samples, k): partition range(n_samples) into k contiguous folds of size n_samples//k (the first n_samples % k folds get one extra sample), then return k [train_indices, val_indices] pairs, one per fold held out as validation.

Function Signature

k_fold_splits(n_samples: int, k: int) -> list

Examples

Example 1: 10 Samples, 3 Folds (Uneven)
Input: n_samples = 10 k = 3
Output: [[[4, 5, 6, 7, 8, 9], [0, 1, 2, 3]], [[0, 1, 2, 3, 7, 8, 9], [4, 5, 6]], [[0, 1, 2, 3, 4, 5, 6], [7, 8, 9]]]
Explanation: 10 does not divide evenly by 3 -- the first fold gets 4 samples, the rest get 3

Constraints

  • No shuffling -- folds are contiguous blocks of range(n_samples), in order.
  • Fold sizes: n_samples // k for every fold, plus one extra sample for each of the first (n_samples % k) folds.
  • For each of the k pairs, val_indices is that one fold and train_indices is every index NOT in that fold (order within train_indices should follow the other folds' natural order).
  • Raise ValueError if k <= 1 or k > n_samples.
Python3Saved ✓
def k_fold_splits(n_samples: int, k: int) -> list:
"""Return a list of k [train_indices, val_indices] pairs (both plain
lists of 0-indexed ints) splitting range(n_samples) into k
contiguous, near-equal folds (no shuffling). If n_samples doesn't
divide evenly by k, the first (n_samples % k) folds get one extra
sample. Raise ValueError if k <= 1 or k > n_samples."""
# Your implementation here
pass

Case 1: 10 Samples, 3 Folds (Uneven)
Input: n_samples = 10 k = 3
Expected: [[[4, 5, 6, 7, 8, 9], [0, 1, 2, 3]], [[0, 1, 2, 3, 7, 8, 9], [4, 5, 6]], [[0, 1, 2, 3, 4, 5, 6], [7, 8, 9]]]