Leak-Free Cross-Validated Preprocessing Pipeline

Quick Overview

Rewrite a leaky cross-validation loop so mean imputation, standardization, top-k correlation feature selection and ridge regression are all fit on each training fold only. It tests understanding of data leakage, per-fold fitting, and how to match a scikit-learn pipeline exactly.

Leak-Free Cross-Validated Preprocessing Pipeline

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

A legacy script fit mean imputation, standardization and top-k feature selection on the full dataset before cross-validating, so its scores used information from the validation folds. Implement `kfold_indices(n_samples, n_splits)` and `leak_free_cv(X, y, n_splits=5, k_features=3, alpha=1.0)` so that every preprocessing step is fit on the training fold only and then applied to the validation fold. Requirements: - `kfold_indices` builds unshuffled contiguous folds that match `KFold`, and the first `n % k` folds get one extra sample. It returns `[(train_idx, val_idx), ...]` and raises `ValueError` when `n_splits` is outside `[2, n_samples]`. - In each fold, impute NaNs with the training column `nanmean`, then standardize with the mean and population standard deviation of the imputed training data. A zero standard deviation becomes `1.0`. - Select the `k_features` columns with the largest absolute Pearson correlation to `y`, breaking ties toward the lower column index, and return them sorted ascending. Raise `ValueError` when `k_features` is outside `[1, n_features]`. - Fit `Ridge(alpha=alpha)`, score each validation fold with R², and store the out-of-fold predictions. - Results must match `make_pipeline(SimpleImputer(), StandardScaler(), SelectKBest(f_regression, k=k_features), Ridge(alpha=alpha))` evaluated under `KFold(n_splits)`. The match holds up to floating-point rounding whenever no two correlation scores tie exactly. On an exact tie, follow the lower-index rule above. Return value: ```python { "scores": np.ndarray, # shape (n_splits,), R² per fold "oof_predictions": np.ndarray, # shape (n_samples,) "selected_features": [np.ndarray, ...], # int indices per fold, ascending "imputer_means": [np.ndarray, ...], # training nanmean per fold "scaler_means": [np.ndarray, ...], # mean of imputed training fold "scaler_scales": [np.ndarray, ...], # population std of imputed training fold } ``` `numpy` and `sklearn.linear_model.Ridge` are available. Shuffling and stratification are out of scope. ```hint Order of fitting Each step's parameters depend on the output of the step before it. Work out which arrays each step may look at, and keep every fitted value so you can replay it on rows the step never saw. ``` ```hint Ranking without F `f_regression` turns each column's correlation into an F statistic. Check how F changes as the squared correlation grows, and decide what score a zero-variance column should get. ``` ### Constraints & Assumptions - `X` is a float array of shape `(n_samples, n_features)` that may contain `NaN`. `y` is a float vector of length `n_samples` with no missing values. - Every column has at least one observed value in every training fold. - `n_splits` is in `[2, n_samples]` and `k_features` is in `[1, n_features]`. - Rows stay in input order: no shuffling, grouping or stratification. ### What a Strong Answer Covers - Every fitted value (imputer means, scaler means and scales, selected columns, ridge coefficients) computed from training rows only and reused unchanged on the validation rows. - The exact imputation and scaling details: training `nanmean`, population standard deviation of the imputed data, and a zero scale replaced by 1.0. - A feature ranking that agrees with `f_regression`, with the tie rule and zero-variance columns handled. - Per-fold R², a complete out-of-fold vector, and the return dictionary in the stated shape. - A way to show the loop is leak-free, such as comparing with the sklearn pipeline or perturbing one fold's validation rows. ### Follow-up Questions - How would you tune `alpha` and `k_features` without leaking into the reported score? - Why does fitting feature selection on the full data inflate scores so badly? - How would you adapt this for time-series or grouped data?

Overview: Rewrite a leaky cross-validation loop so mean imputation, standardization, top-k correlation feature selection and ridge regression are all fit on each training fold only. It tests understanding of data leakage, per-fold fitting, and how to match a scikit-learn pipeline exactly.

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

A legacy script fit mean imputation, standardization and top-k feature selection on the full dataset before cross-validating, so its scores used information from the validation folds. Implement kfold_indices(n_samples, n_splits) and leak_free_cv(X, y, n_splits=5, k_features=3, alpha=1.0) so that every preprocessing step is fit on the training fold only and then applied to the validation fold.

Requirements:

  • kfold_indices builds unshuffled contiguous folds that match KFold , and the first n % k folds get one extra sample. It returns [(train_idx, val_idx), ...] and raises ValueError when n_splits is outside [2, n_samples] .
  • In each fold, impute NaNs with the training column nanmean , then standardize with the mean and population standard deviation of the imputed training data. A zero standard deviation becomes 1.0 .
  • Select the k_features columns with the largest absolute Pearson correlation to y , breaking ties toward the lower column index, and return them sorted ascending. Raise ValueError when k_features is outside [1, n_features] .
  • Fit Ridge(alpha=alpha) , score each validation fold with R², and store the out-of-fold predictions.
  • Results must match make_pipeline(SimpleImputer(), StandardScaler(), SelectKBest(f_regression, k=k_features), Ridge(alpha=alpha)) evaluated under KFold(n_splits) . The match holds up to floating-point rounding whenever no two correlation scores tie exactly. On an exact tie, follow the lower-index rule above.

Return value:

{
    "scores": np.ndarray,                    # shape (n_splits,), R² per fold
    "oof_predictions": np.ndarray,           # shape (n_samples,)
    "selected_features": [np.ndarray, ...],  # int indices per fold, ascending
    "imputer_means": [np.ndarray, ...],      # training nanmean per fold
    "scaler_means": [np.ndarray, ...],       # mean of imputed training fold
    "scaler_scales": [np.ndarray, ...],      # population std of imputed training fold
}

numpy and sklearn.linear_model.Ridge are available. Shuffling and stratification are out of scope.

Constraints & Assumptions

  • X is a float array of shape (n_samples, n_features) that may contain NaN . y is a float vector of length n_samples with no missing values.
  • Every column has at least one observed value in every training fold.
  • n_splits is in [2, n_samples] and k_features is in [1, n_features] .
  • Rows stay in input order: no shuffling, grouping or stratification.

What a Strong Answer Covers Guidance

  • Every fitted value (imputer means, scaler means and scales, selected columns, ridge coefficients) computed from training rows only and reused unchanged on the validation rows.
  • The exact imputation and scaling details: training nanmean , population standard deviation of the imputed data, and a zero scale replaced by 1.0.
  • A feature ranking that agrees with f_regression , with the tie rule and zero-variance columns handled.
  • Per-fold R², a complete out-of-fold vector, and the return dictionary in the stated shape.
  • A way to show the loop is leak-free, such as comparing with the sklearn pipeline or perturbing one fold's validation rows.

Follow-up Questions Guidance

  • How would you tune alpha and k_features without leaking into the reported score?
  • Why does fitting feature selection on the full data inflate scores so badly?
  • How would you adapt this for time-series or grouped data?