Out-of-Fold Target Encoder with Smoothing
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `OutOfFoldTargetEncoder(cols, m=1.0, n_splits=5)` with `fit(X, y)`, `transform(X)` and `fit_transform(X, y)`. Each category encodes to `(sum_y + m * prior) / (count + m)`, where `prior` is the mean of `y` over all fitting rows (including rows with a missing category).
The encoder must meet these requirements:
- `fit` sets `prior_` (a float) and `mappings_` (`{col: {category: float}}`, missing values excluded) from all rows, and returns `self`.
- In `fit_transform`, row `i` is in fold `i % n_splits` by position. Each fold uses a prior and category statistics from the other folds only, and a category absent from those folds gets that fold's prior. `fit_transform` then calls `fit` on the full data.
- `transform` encodes unseen or missing (`NaN`/`None`) values as `prior_`. Calling it before fitting raises `RuntimeError`.
- The result is a copy of `X` with each column in `cols` replaced in place by a `float64` column. Other columns, column order and index are unchanged. `X` is never mutated.
- `len(X) != len(y)` raises `ValueError`.
Example:
```python
X = pd.DataFrame({"city": ["a", "a", "b", "a", "b", "b"]})
y = [1, 0, 1, 1, 0, 0]
enc = OutOfFoldTargetEncoder(["city"], m=1.0, n_splits=2)
enc.fit_transform(X, y)["city"]
# [4/9, 5/6, 1/6, 5/6, 1/6, 5/9]
# row 0: fold-1 rows {1,3,5}, prior 1/3, a: (1 + 1/3) / (2 + 1)
enc.prior_ # 0.5
enc.mappings_["city"] # {'a': 0.625, 'b': 0.375}
enc.transform(pd.DataFrame({"city": ["a", "zzz", None]}))["city"]
# [0.625, 0.5, 0.5]
```
```hint What to keep per category
A sum of `y` and a row count per category are enough to build any of the encodings. Compute the prior before you drop the rows whose category is missing.
```
```hint Positions, not labels
Fold membership and the pairing of `X` with `y` are both defined by row position. Think about what happens if `X` arrives with a shuffled or string index.
```
### What a Strong Answer Covers
- How fold assignment and per-fold priors keep each row's own target out of its encoding.
- Where rows with a missing category count (the prior) and where they do not (category statistics).
- The fallback for unseen and missing values in both `fit_transform` and `transform`.
- The output contract: `float64` columns written into a copy with order and index kept, plus the two error cases.
- The time complexity of `fit_transform`, and whether the fold loop can be made linear.
### Follow-up Questions
- Why does in-sample target encoding leak, and does out-of-fold encoding fully remove it?
- How would you adapt this for time-ordered data?
- How would you extend this to multiclass targets, and how would you choose `m`?
Overview: Implement a K-fold out-of-fold target encoder in pandas that shrinks each category's mean target toward a prior with m-estimate smoothing. It tests target leakage, per-fold priors, handling of unseen and missing categories, and keeping the DataFrame contract intact.