Implement a Cross-Validation Split Leakage Checker for Index, Group and Temporal Leaks

Quick Overview

Write a checker that audits cross-validation splits for indices shared between train and validation, groups that appear on both sides, and validation rows older than the training data. It tests NumPy set logic, an exact report contract and how leakage slips into CV pipelines.

Implement a Cross-Validation Split Leakage Checker for Index, Group and Temporal Leaks

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Given an iterable `splits` of `(train_idx, val_idx)` integer arrays (a list or a generator), plus optional per-row `groups` and `timestamps`, implement `leakage_report` to return a per-fold leakage `pd.DataFrame`. Also implement `assert_no_leakage`, which raises on the first leak found. ```python def leakage_report(splits, groups=None, timestamps=None) -> pd.DataFrame: ... def assert_no_leakage(splits, groups=None, timestamps=None) -> None: ... ``` Requirements: - Columns in order: `fold, n_train, n_val, index_overlap, shared_groups, temporal_violations` (all `int64`), then `ok` (`bool`, True if and only if all three checks are 0). `fold` is 0-based. `n_train` and `n_val` are raw array lengths. - `index_overlap` is the number of distinct indices present in both train and val. - `shared_groups` is the number of distinct group labels present on both sides (0 if `groups is None`). - `temporal_violations` is the count of val rows with a timestamp strictly less than the max train timestamp. Ties are allowed. It is 0 if `timestamps is None` or either side is empty. Numeric and `datetime64` timestamps are both supported. - `assert_no_leakage` scans folds in order, and within each fold checks overlap, then groups, then time. On the first nonzero check it raises `AssertionError("fold {k}: {check} = {count}")`. Otherwise it returns `None`. Example: ```python groups = [0, 0, 1, 1, 2, 2] timestamps = [0, 1, 2, 3, 4, 5] splits = [([0, 1], [2, 3]), ([1, 2], [0, 3])] leakage_report(splits, groups, timestamps) # fold n_train n_val index_overlap shared_groups temporal_violations ok # 0 2 2 0 0 0 True # 1 2 2 0 2 1 False assert_no_leakage(splits, groups, timestamps) # AssertionError: fold 1: shared_groups = 2 ``` ```hint Distinct counts Two of the checks count distinct values, so look for a NumPy set operation that already deduplicates its inputs. ``` ```hint One pass over the splits `splits` may be a generator that can only be read once. Compute all three counts for a fold in one helper and call it from both functions. ``` ### Constraints & Assumptions - `groups` and `timestamps`, when given, have one entry per row and are indexed by the integers in the splits. - Index arrays may contain repeated indices and may be empty. - Timestamps are numeric or `datetime64`. ### What a Strong Answer Covers - Distinct-value semantics for `index_overlap` and `shared_groups`, with `n_train` and `n_val` kept as raw lengths. - The strict temporal rule, including ties, empty sides, missing `timestamps` and `datetime64` input. - The exact column order and dtypes of the report, with `ok` derived from the three checks. - The check order and exact error message in `assert_no_leakage`. - A single pass over generator input and the per-fold complexity. ### Follow-up Questions - How would you extend the temporal check to enforce a purge or embargo gap? - What cross-fold properties would you also validate? - How does this apply to nested CV or to preprocessing leakage?

Overview: Write a checker that audits cross-validation splits for indices shared between train and validation, groups that appear on both sides, and validation rows older than the training data. It tests NumPy set logic, an exact report contract and how leakage slips into CV pipelines.

PracHub logo
General
Nov 24, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Given an iterable splits of (train_idx, val_idx) integer arrays (a list or a generator), plus optional per-row groups and timestamps, implement leakage_report to return a per-fold leakage pd.DataFrame. Also implement assert_no_leakage, which raises on the first leak found.

def leakage_report(splits, groups=None, timestamps=None) -> pd.DataFrame: ...

def assert_no_leakage(splits, groups=None, timestamps=None) -> None: ...

Requirements:

  • Columns in order: fold, n_train, n_val, index_overlap, shared_groups, temporal_violations (all int64 ), then ok ( bool , True if and only if all three checks are 0). fold is 0-based. n_train and n_val are raw array lengths.
  • index_overlap is the number of distinct indices present in both train and val.
  • shared_groups is the number of distinct group labels present on both sides (0 if groups is None ).
  • temporal_violations is the count of val rows with a timestamp strictly less than the max train timestamp. Ties are allowed. It is 0 if timestamps is None or either side is empty. Numeric and datetime64 timestamps are both supported.
  • assert_no_leakage scans folds in order, and within each fold checks overlap, then groups, then time. On the first nonzero check it raises AssertionError("fold {k}: {check} = {count}") . Otherwise it returns None .

Example:

groups = [0, 0, 1, 1, 2, 2]
timestamps = [0, 1, 2, 3, 4, 5]
splits = [([0, 1], [2, 3]), ([1, 2], [0, 3])]

leakage_report(splits, groups, timestamps)
#  fold n_train n_val index_overlap shared_groups temporal_violations    ok
#     0       2     2             0             0                   0  True
#     1       2     2             0             2                   1 False

assert_no_leakage(splits, groups, timestamps)
# AssertionError: fold 1: shared_groups = 2

Constraints & Assumptions

  • groups and timestamps , when given, have one entry per row and are indexed by the integers in the splits.
  • Index arrays may contain repeated indices and may be empty.
  • Timestamps are numeric or datetime64 .

What a Strong Answer Covers Guidance

  • Distinct-value semantics for index_overlap and shared_groups , with n_train and n_val kept as raw lengths.
  • The strict temporal rule, including ties, empty sides, missing timestamps and datetime64 input.
  • The exact column order and dtypes of the report, with ok derived from the three checks.
  • The check order and exact error message in assert_no_leakage .
  • A single pass over generator input and the per-fold complexity.

Follow-up Questions Guidance

  • How would you extend the temporal check to enforce a purge or embargo gap?
  • What cross-fold properties would you also validate?
  • How does this apply to nested CV or to preprocessing leakage?