Implement a K-Fold Cross-Validation Splitter From Scratch

Quick Overview

Implement a k-fold cross-validation splitter in NumPy that returns sorted train and validation index arrays for each fold, with optional seeded shuffling. It tests fold sizing when the samples do not divide evenly, matching the sklearn KFold layout, and input validation.

Implement a K-Fold Cross-Validation Splitter From Scratch

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: easy

Interview Round: Other

Implement `kfold_split(n_samples, n_splits=5, shuffle=False, seed=None)` that partitions `range(n_samples)` into `n_splits` folds. Return a list of `(train_indices, validation_indices)` tuples, one per fold, in fold order. - Fold `i` validates on the `i`-th contiguous chunk of the index order. The first `n_samples % n_splits` folds get one extra sample. - If `shuffle` is true, the order is `np.random.default_rng(seed).permutation(n_samples)`. Otherwise it is `np.arange(n_samples)`. - Both arrays are sorted ascending integer arrays. Train is the complement of validation. - If `n_splits < 2` or `n_splits > n_samples`, raise `ValueError`. For example: ```python kfold_split(10, n_splits=3) # validation folds: [0,1,2,3], [4,5,6], [7,8,9] # fold 0 train: [4,5,6,7,8,9] ``` ```hint Fold sizes Fix the whole index order once and slice it. When `n_samples` does not divide evenly by `n_splits`, work out how many folds need one extra sample before you start slicing. ``` ### Constraints & Assumptions - `n_samples` and `n_splits` are integers. - Unshuffled output must match `sklearn.model_selection.KFold`. Do not use it in your solution. ### What a Strong Answer Covers - Rejecting invalid `n_splits` values before any folds are built. - Fold sizes that differ by at most one, with the extra samples placed so the unshuffled output matches sklearn. - Validation folds that are disjoint and together cover every index exactly once, with and without shuffling. - Train and validation returned as sorted integer arrays, with train equal to the exact complement of validation. - The time and space cost of the approach. ### Follow-up Questions - How would you make this stratified, so each validation fold keeps the class proportions of the full dataset? - Why return sorted indices instead of the permuted order? - Several rows can belong to the same user. How would you change the splitter so a user never appears in both train and validation of the same fold? - How would the split change for time-ordered data, where every validation row must come after the rows used for training?

Overview: Implement a k-fold cross-validation splitter in NumPy that returns sorted train and validation index arrays for each fold, with optional seeded shuffling. It tests fold sizing when the samples do not divide evenly, matching the sklearn KFold layout, and input validation.

General logo
General
Nov 25, 2026
easyMachine Learning EngineerOtherMachine Learning
0
0

Implement kfold_split(n_samples, n_splits=5, shuffle=False, seed=None) that partitions range(n_samples) into n_splits folds. Return a list of (train_indices, validation_indices) tuples, one per fold, in fold order.

  • Fold i validates on the i -th contiguous chunk of the index order. The first n_samples % n_splits folds get one extra sample.
  • If shuffle is true, the order is np.random.default_rng(seed).permutation(n_samples) . Otherwise it is np.arange(n_samples) .
  • Both arrays are sorted ascending integer arrays. Train is the complement of validation.
  • If n_splits < 2 or n_splits > n_samples , raise ValueError .

For example:

kfold_split(10, n_splits=3)
# validation folds: [0,1,2,3], [4,5,6], [7,8,9]
# fold 0 train:     [4,5,6,7,8,9]

Constraints & Assumptions

  • n_samples and n_splits are integers.
  • Unshuffled output must match sklearn.model_selection.KFold . Do not use it in your solution.

What a Strong Answer Covers Guidance

  • Rejecting invalid n_splits values before any folds are built.
  • Fold sizes that differ by at most one, with the extra samples placed so the unshuffled output matches sklearn.
  • Validation folds that are disjoint and together cover every index exactly once, with and without shuffling.
  • Train and validation returned as sorted integer arrays, with train equal to the exact complement of validation.
  • The time and space cost of the approach.

Follow-up Questions Guidance

  • How would you make this stratified, so each validation fold keeps the class proportions of the full dataset?
  • Why return sorted indices instead of the permuted order?
  • Several rows can belong to the same user. How would you change the splitter so a user never appears in both train and validation of the same fold?
  • How would the split change for time-ordered data, where every validation row must come after the rows used for training?