Leakage-Safe Tabular Preprocessor With Target Encoding
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Implement a `TabularPreprocessor` class that prepares a pandas `DataFrame` for a model. It handles three groups of columns (numeric, low-cardinality categorical and high-cardinality categorical) and learns every statistic it uses from training data only. It exposes `fit(X, y)`, `transform(X)`, `fit_transform(X, y)` and `get_feature_names_out()`.
The constructor takes the column groups and three parameters:
```python
TabularPreprocessor(numeric_cols, low_card_cols, high_card_cols,
smoothing=10.0, n_folds=5, seed=0)
```
The class must behave as follows.
- Each numeric column is imputed with its training median (use `0` when the column is entirely missing in training), then standardized with the training mean and population standard deviation (`ddof=0`) of the imputed column. A standard deviation of 0 is replaced by `1`.
- In a low-cardinality column, a missing value becomes the category `"__missing__"` and any other value `v` becomes `str(v)`. The output has one indicator column named `{col}={cat}` per training category, in sorted order. A category not seen in training encodes as all zeros.
- Each high-cardinality column becomes one column `{col}_te`, built from string categories formed the same way. A category's value is `(sum_y + m*prior) / (count + m)`, where `sum_y` and `count` are that category's label sum and row count in training, `m = smoothing`, and `prior` is the training mean of `y`. A category not seen in training gets `prior`.
- The output is a `float64` DataFrame with the input's index. Its columns are ordered numeric, then one-hot, then `_te`, each group following the order of its constructor list, and that list equals `get_feature_names_out()`. Calling `transform` before `fit` raises `RuntimeError`.
- `fit_transform(X, y)` fits on all rows, but each row's `_te` values use a mapping and prior learned from the other folds only. Every other column equals `transform(X)`.
Assign rows to folds exactly like this, with `n = len(X)`, so the out-of-fold values are reproducible:
```python
perm = np.random.default_rng(seed).permutation(n)
folds = np.empty(n, dtype=int)
folds[perm] = np.arange(n) % n_folds
```
```hint Where the state lives
Have `fit` store everything `transform` needs (medians, means, scales, sorted categories, per-category target values and the prior), so `transform` never touches `y` or recomputes a statistic.
```
```hint Reuse transform
After fitting, `fit_transform` can start from `transform(X)` and overwrite only the `_te` columns, one held-out fold at a time.
```
```hint Two pandas traps
`Series.std()` defaults to `ddof=1`, and assigning a `Series` into a DataFrame aligns on the index while a NumPy array is placed by position. Check both when `X` has a non-default index.
```
### Constraints & Assumptions
- `X` is a pandas `DataFrame` with at least one row. `y` is numeric (a 0/1 label or a continuous target) with one value per row of `X`, matched by position.
- The three column lists name columns of `X` and do not overlap. Any of them may be empty.
- `n_folds` is at least 2 and `smoothing` is non-negative.
- `fit`, `transform` and `fit_transform` must not mutate their input frames.
- Using scikit-learn is optional. NumPy and pandas are enough.
### Clarifying Questions to Ask
- Can `y` contain missing values, and if so, should those rows be left out of the target statistics?
- Will `transform` see the same column dtypes as `fit`? `str(1)` is `"1"` but `str(1.0)` is `"1.0"`, so a column that switches from integer to float stops matching its training categories.
- How large can `n_folds` be relative to `n`? Some folds are empty when `n < n_folds`.
### What a Strong Answer Covers
- Every statistic (median, mean, scale, category list, per-category target value, prior) is learned in `fit` and only read in `transform`.
- The edge cases the spec names: an all-missing numeric column, a zero standard deviation, unseen categories in both encodings, and `transform` before `fit`.
- The output contract: `float64` values, the input index, the numeric then one-hot then `_te` column order, and agreement with `get_feature_names_out()`.
- Out-of-fold target encoding in `fit_transform` with the pinned fold assignment, refitting both the mapping and the prior per fold, while the other columns equal `transform(X)`.
- Why in-sample target encoding leaks the label, and inputs that are never mutated.
### Follow-up Questions
- Why can't `fit_transform` just return `fit(X, y).transform(X)` for the target-encoded columns?
- How would you extend the target encoding to multiclass or regression targets?
- How does this preprocessor interact with cross-validation of the downstream model?
Overview: Implement a pandas preprocessor that imputes and standardizes numeric columns, one-hot encodes low-cardinality categories and applies smoothed target encoding to high-cardinality ones. It tests whether you learn every statistic from training data only and produce out-of-fold target encodings that do not leak labels.