Leak-Free CV With In-Fold Target Encoding

Quick Overview

Implement k-fold cross-validation in Python where median imputation, standardization and smoothed target encoding are fit only on each training fold before a ridge model is trained. It tests whether you can prevent target leakage with high-cardinality categories and return correct out-of-fold predictions.

Leak-Free CV With In-Fold Target Encoding

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Given numeric features `X_num` (an `(n, d)` array that may contain `NaN`), a high-cardinality `categories` array of length `n` and regression targets `y`, implement k-fold cross-validation in which median imputation, standardization and smoothed target encoding are fit only on each training fold. Train scikit-learn's `Ridge(alpha=alpha)` on each fold and return `(table, oof)`. Implement these four functions with these names and signatures: ```python def kfold_indices(n_samples, n_splits): ... def fit_preprocessor(X_num, categories, y, smoothing=10.0): ... def transform(params, X_num, categories): ... def cross_validate(X_num, categories, y, n_splits=5, smoothing=10.0, alpha=1.0): ... ``` Requirements: - `kfold_indices(n_samples, n_splits)` builds contiguous, unshuffled folds, and the first `n_samples % n_splits` folds get one extra sample. It returns a list of `(train_idx, val_idx)` pairs of sorted integer arrays and raises `ValueError` when `n_splits < 2` or `n_splits > n_samples`. - `fit_preprocessor` returns a dict with the keys `medians` (the median of the non-NaN values in each column, `0.0` if a column is all NaN), `means` and `stds` (the mean and population standard deviation of the imputed data, with a standard deviation of `0` replaced by `1.0`), `global_mean` (the mean of the training `y`) and `encoding`. - `encoding[str(c)] = (sum_y_c + smoothing * global_mean) / (n_c + smoothing)`, where `sum_y_c` and `n_c` are the label sum and row count of category `c` in the rows passed in. - `transform` returns an `(n, d + 1)` array: the imputed and scaled numeric columns, then the encoded category column. A category the training rows never contained maps to `global_mean`. - `cross_validate` returns `table`, a DataFrame with one row per fold and columns `fold`, `n_train`, `n_val` (int64) and `mse` (float64), and `oof`, an array holding every row's prediction from the fold in which it was a validation row. - Category values are compared as strings. Example: ```python nan = float("nan") X = [[1, 10], [nan, 20], [3, nan], [5, 40]] cats = ["a", "b", "a", "c"] y = [1, 2, 3, 6] p = fit_preprocessor(X, cats, y, smoothing=2) # medians = [3, 20], means = [3, 22.5], stds = [sqrt(2), sqrt(118.75)] # global_mean = 3, encoding = {"a": 2.5, "b": 8/3, "c": 4.0} transform(p, [[nan, 30]], ["zzz"]) # -> [[0.0, 7.5 / sqrt(118.75), 3.0]] kfold_indices(11, 3) # validation folds: [0..3], [4..7], [8..10] ``` ```hint Where each number comes from List every value `transform` uses, including the fallback for unseen categories. Each one has to be computed from the training fold's rows and nothing else. ``` ```hint Order of the numeric steps Take the medians from the observed values first, then compute means and standard deviations on the imputed matrix. Computing them on the raw matrix gives `NaN`. ``` ```hint Standard deviation pitfall NumPy and pandas use different default degrees of freedom for the standard deviation. Check which one the requirement asks for. ``` ### Constraints & Assumptions - `X_num` is a float array of shape `(n, d)`; `NaN` marks a missing value, and a column can be entirely missing inside one training fold. - `categories` has length `n` and many distinct values, so plenty of categories appear in only one fold or only once. - `y` is a real-valued target of length `n`. - `2 <= n_splits <= n_samples`, and folds are never shuffled. ### What a Strong Answer Covers - Fold boundaries that match the uneven-split rule, plus the `ValueError` cases. - Fitting the medians, means, standard deviations, global mean and category encodings on the training fold only, and applying the same frozen parameters to both folds. - The edge cases: all-NaN columns, constant columns and categories that are missing from the training fold. - A per-fold table with the required dtypes and an OOF array in which every position is filled exactly once. - Why fitting the target encoding on all rows leaks validation labels into the features, and how to test that the pipeline does not. ### Follow-up Questions - The model still sees in-sample target encodings on the training fold. Why is that a problem, and how would you fix it? - What would change if rows were grouped (for example by customer) or the data were time-ordered? - How would you choose `smoothing` and `alpha` without leaking?

Overview: Implement k-fold cross-validation in Python where median imputation, standardization and smoothed target encoding are fit only on each training fold before a ridge model is trained. It tests whether you can prevent target leakage with high-cardinality categories and return correct out-of-fold predictions.

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

Given numeric features X_num (an (n, d) array that may contain NaN), a high-cardinality categories array of length n and regression targets y, implement k-fold cross-validation in which median imputation, standardization and smoothed target encoding are fit only on each training fold. Train scikit-learn's Ridge(alpha=alpha) on each fold and return (table, oof).

Implement these four functions with these names and signatures:

def kfold_indices(n_samples, n_splits): ...
def fit_preprocessor(X_num, categories, y, smoothing=10.0): ...
def transform(params, X_num, categories): ...
def cross_validate(X_num, categories, y, n_splits=5, smoothing=10.0, alpha=1.0): ...

Requirements:

  • kfold_indices(n_samples, n_splits) builds contiguous, unshuffled folds, and the first n_samples % n_splits folds get one extra sample. It returns a list of (train_idx, val_idx) pairs of sorted integer arrays and raises ValueError when n_splits < 2 or n_splits > n_samples .
  • fit_preprocessor returns a dict with the keys medians (the median of the non-NaN values in each column, 0.0 if a column is all NaN), means and stds (the mean and population standard deviation of the imputed data, with a standard deviation of 0 replaced by 1.0 ), global_mean (the mean of the training y ) and encoding .
  • encoding[str(c)] = (sum_y_c + smoothing * global_mean) / (n_c + smoothing) , where sum_y_c and n_c are the label sum and row count of category c in the rows passed in.
  • transform returns an (n, d + 1) array: the imputed and scaled numeric columns, then the encoded category column. A category the training rows never contained maps to global_mean .
  • cross_validate returns table , a DataFrame with one row per fold and columns fold , n_train , n_val (int64) and mse (float64), and oof , an array holding every row's prediction from the fold in which it was a validation row.
  • Category values are compared as strings.

Example:

nan = float("nan")
X = [[1, 10], [nan, 20], [3, nan], [5, 40]]
cats = ["a", "b", "a", "c"]
y = [1, 2, 3, 6]
p = fit_preprocessor(X, cats, y, smoothing=2)
# medians = [3, 20], means = [3, 22.5], stds = [sqrt(2), sqrt(118.75)]
# global_mean = 3, encoding = {"a": 2.5, "b": 8/3, "c": 4.0}
transform(p, [[nan, 30]], ["zzz"])  # -> [[0.0, 7.5 / sqrt(118.75), 3.0]]

kfold_indices(11, 3)  # validation folds: [0..3], [4..7], [8..10]

Constraints & Assumptions

  • X_num is a float array of shape (n, d) ; NaN marks a missing value, and a column can be entirely missing inside one training fold.
  • categories has length n and many distinct values, so plenty of categories appear in only one fold or only once.
  • y is a real-valued target of length n .
  • 2 <= n_splits <= n_samples , and folds are never shuffled.

What a Strong Answer Covers Guidance

  • Fold boundaries that match the uneven-split rule, plus the ValueError cases.
  • Fitting the medians, means, standard deviations, global mean and category encodings on the training fold only, and applying the same frozen parameters to both folds.
  • The edge cases: all-NaN columns, constant columns and categories that are missing from the training fold.
  • A per-fold table with the required dtypes and an OOF array in which every position is filled exactly once.
  • Why fitting the target encoding on all rows leaks validation labels into the features, and how to test that the pipeline does not.

Follow-up Questions Guidance

  • The model still sees in-sample target encodings on the training fold. Why is that a problem, and how would you fix it?
  • What would change if rows were grouped (for example by customer) or the data were time-ordered?
  • How would you choose smoothing and alpha without leaking?