Interview conceptMachine Learning

Cross-Validation, Data Splitting, And Leakage Control

Asked of: Machine Learning Engineer

Last updated

Editorial infographic showing leakage-safe machine-learning evaluation: raw data flows through fold-aware preprocessing, production-matched splitters, nested tuning, and unbiased reporting.

What's being tested

The interviewer is testing whether you can design an evaluation protocol that estimates the model’s behavior in production, not merely produce a high offline score. You need to reason about generalization, dependence between examples, model-selection bias, computational cost, and leakage through preprocessing or feature construction. For an MLE, this matters because evaluation logic lives inside training and deployment pipelines: a flawed split can promote a model that fails immediately under temporal, spatial, user-level, or distribution-shifted traffic.

Core knowledge

  • Cross-validation partitions data into folds, trains on K−1K-1 folds, and evaluates on the held-out fold; the mean score estimates expected performance while fold-to-fold variance exposes instability. Stratification preserves class proportions when labels are imbalanced.

  • Use nested cross-validation when reporting an unbiased estimate after hyperparameter search: the inner loop selects settings, while the untouched outer loop estimates performance. Reusing the same folds for tuning and final reporting creates optimistic selection bias.

  • Every learned transformation must be fit inside each training fold: imputation, scaling, vocabulary construction, target encoding, feature selection, and dimensionality reduction. In scikit-learn, put them in a Pipeline so fit_transform never sees validation rows.

  • Choose the splitter to match production dependence. Group K-fold keeps all records from one user, device, patient, or property in one fold; time-series splits train on the past and validate on the future; random K-fold is invalid when correlated entities cross folds.

  • Blocked cross-validation assigns contiguous spatial regions to folds, often adding a buffer between training and validation blocks. The buffer suppresses short-range spatial autocorrelation, preventing nearby soil samples or houses from acting as near-duplicates across folds.

  • For temporal data, preserve the prediction-time information boundary: train on [t0,t][t_0,t] and validate on (t,t+Δ](t,t+\Delta]. Feature windows, labels, aggregates, and delayed outcomes must be computed using only data available at prediction time.

  • For model comparison, use identical folds and preferably identical predictions for every candidate: this is a paired comparison that reduces noise. Report mean, standard deviation or confidence intervals, per-fold scores, and the selected metric rather than only the best fold.

  • Leave-one-out cross-validation requires approximately NN fits, has high estimator variance because training sets differ by only one example, and is operationally expensive for large neural or boosted models. For millions of rows, use a fixed holdout, repeated K-fold on a sample, or a scalable temporal split.

  • Out-of-bag error in a random forest predicts each training row using trees whose bootstrap sample omitted that row; roughly e−1≈36.8%e^{-1}\approx36.8\% of trees omit a row. It can be pessimistic relative to the final forest because each OOB prediction uses fewer trees, especially with few trees or small datasets.

  • OOB error is not a substitute for a deployment-faithful test set when rows are grouped, temporal, or spatially correlated. It also becomes optimistic if preprocessing, feature engineering, or hyperparameter selection used all rows before OOB scoring.

  • The train/validation/test allocation depends on absolute sample counts, rare-class coverage, subgroup coverage, expected effect size, and tuning pressure—not a universal 80/10/10 rule. A test set should be large enough that its metric standard error is operationally acceptable; otherwise use repeated or nested validation.

  • After selection, retrain the chosen pipeline on training plus validation data, then evaluate once on the untouched test set. Freeze the test set, version the split and feature code, and monitor the same metric offline and online to detect train/serve skew.

Worked example

For “How does blocked cross-validation prevent leakage in spatially correlated datasets?”, I would first clarify the production unit, spatial resolution, prediction horizon, correlation range, and whether the goal is interpolation near observed locations or extrapolation to new regions. I would state that randomly assigning samples is unsafe because nearby observations can share latent factors, labels, and engineered features even when their rows are distinct. I would organize the answer around four pillars: construct spatial blocks, assign whole blocks to folds, add a distance buffer when needed, and evaluate with a deployment-matched metric and uncertainty estimate. I would explicitly distinguish a blocked split from a buffered split: blocking separates regions, while buffering removes nearby training points around each validation region. The key tradeoff is between realism and data efficiency—large blocks and buffers reduce leakage but may leave fewer training examples and increase score variance. I would also mention fitting spatial preprocessing and any target-derived features within each training fold. I would close by saying that, with more time, I would compare random, blocked, and buffered estimates, inspect performance by geography, and validate on a genuinely future or held-out region.

A second angle

For “How is cross-validation used to choose between candidate models or hyperparameter settings?”, the same principle becomes fair model selection rather than primarily spatial leakage control. I would use identical folds for every candidate, place all learned preprocessing inside the pipeline, select using the mean validation metric, and quantify whether score differences are larger than fold-to-fold noise. If many configurations are searched, I would reserve an outer test loop or untouched test set because the best observed validation score is itself selected and therefore optimistic.

Common pitfalls

Analytical mistake: Saying “use random K-fold unless the data is small” ignores user, temporal, spatial, and duplicate dependence. A stronger answer names the production unit and chooses group, temporal, blocked, or stratified splitting accordingly.

Pitfall: Treating preprocessing leakage as harmless because the validation labels were not used; fitting a scaler, vocabulary, target encoder, or feature selector globally still lets validation features influence training.

Communication mistake: Listing 80/10/10 as a universal allocation sounds memorized and incomplete. Explain that absolute validation and test counts, rare classes, subgroup coverage, metric variance, and tuning intensity determine the split.

Depth mistake: Claiming OOB error is always unbiased, or always pessimistic, is too categorical. Explain that OOB predictions use fewer trees than the final ensemble and can be pessimistic, while grouped dependence, leakage, or hyperparameter tuning can invalidate its interpretation.

Connections

An interviewer may pivot to data drift, train/serve skew, calibration, class-imbalanced metrics, or nested model selection. They may also ask how to version split assignments and reproduce an evaluation inside a Kubeflow or MLflow training pipeline.

Further reading

Practice questions

Related concepts