Problems
Loading...
1 / 1

K-Fold Split (Indices Only)

Data Processing
Hard

Split indices 0..N-1 into k folds for cross-validation. Return a list of (train_idx, val_idx) pairs where each index appears exactly once in validation across all folds.

Mathematical Definition

K-Fold Partitioning:

{0,1,,N1}=F1F2Fk\{0, 1, \ldots, N-1\} = F_{1} \cup F_{2} \cup \cdots \cup F_{k}

where Fi∩Fj=∅ for i≠j, and ∣Fi∣−∣Fj∣≤1 for all i, j.

For fold i:

vali=Fitraini=jiFj\text{val}_{i} = F_{i} \qquad \text{train}_{i} = \bigcup_{j \ne i} F_{j}

Function Arguments

  • N: int - total number of samples
  • k: int - number of folds
  • shuffle: bool - whether to shuffle before splitting
  • rng: np.random.Generator or None - random generator for reproducibility
Loading visualization...

Examples

Input: N=5, k=2, shuffle=False

Output: [(train=[3,4], val=[0,1,2]), (train=[0,1,2], val=[3,4])]

5 items split into 2 folds of sizes [3, 2]. Each fold uses one part as validation, the rest as training.

Input: N=7, k=3, shuffle=False

Output: [(train=[3,4,5,6], val=[0,1,2]), (train=[0,1,2,5,6], val=[3,4]), (train=[0,1,2,3,4], val=[5,6])]

7 items → 3 folds of sizes [3, 2, 2]. Larger folds come first (7 mod 3 = 1 extra item in fold 1).

Hint 1

Create np.arange(), optionally shuffle, then split into k contiguous chunks using np.array_split().

Hint 2

For fold i, validation is fold i, training is np.concatenate() of all other folds.

Requirements

  • Return list of k tuples: (train_idx, val_idx)
  • Both arrays are 1D numpy arrays of dtype int
  • Each index 0..N-1 appears exactly once in validation
  • Fold sizes differ by at most 1
  • Use rng.permutation() if rng provided, else np.random.shuffle()

Constraints

  • 2 ≤ k ≤ N ≤ 100,000
  • NumPy only
  • Time limit: 300ms
Try Similar Problems