Quantile Rank Normalizer With Uniform or Normal Output
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement a `QuantileNormalizer` class with `fit(X)`, `transform(X)` and `fit_transform(X)` that works on a numeric `pd.DataFrame`. Per column, it maps each value to its training percentile in `[0, 1]`, optionally passed through the inverse normal CDF. The constructor is `QuantileNormalizer(output_distribution="uniform", eps=1e-7)`.
Requirements:
- `fit` drops NaNs and stores `knots_[col] = (sorted unique values, p)` with `p = (avg_rank - 1) / (n - 1)`, where `n` is the number of non-NaN training values and tied values share their average 1-based rank. A column with a single unique value stores `p = [0.5]`.
- `transform` interpolates linearly between the knots. Values strictly below the training minimum map to `0` and values strictly above the maximum map to `1`. Every non-NaN value of a constant column maps to `0.5`. NaN stays NaN.
- With `output_distribution="normal"`, return `norm.ppf(clip(p, eps, 1 - eps))`. Any value other than `"uniform"` or `"normal"` raises `ValueError` in `__init__`.
- `transform` returns a new `float64` DataFrame with the input's index and the columns in fit order. It never mutates the input.
- A column seen at fit time but absent at transform time raises `KeyError`.
- `fit` returns `self`, and `fit_transform(X)` equals `fit(X).transform(X)`.
Example:
```text
train a = [1, 2, 2, 3, 5]
knots_['a'] -> ([1, 2, 3, 5], [0.0, 0.375, 0.75, 1.0])
transform a = [2, 4, 2.5, 1, 5]
Output: [0.375, 0.875, 0.5625, 0.0, 1.0]
```
The two 2s hold ranks 2 and 3, so both get rank 2.5 and `p = 1.5 / 4 = 0.375`. The value 4 lies halfway between the knots 3 and 5, so it maps halfway between 0.75 and 1.0.
Example with a tied minimum and maximum:
```text
train b = [1, 1, 2, 3, 3]
knots_['b'] -> ([1, 2, 3], [0.125, 0.5, 0.875])
transform b = [0, 1, 1.5, 3, 4]
Output: [0.0, 0.125, 0.3125, 0.875, 1.0]
```
The values 0 and 4 lie outside the training range, so they map to 0 and 1, while the training minimum and maximum themselves keep their mid-rank percentiles.
```hint Ranks from counts
With the sorted unique values and their counts, the first 1-based rank of each value is one cumulative sum away.
```
```hint Check the edges
Test what your interpolation returns just outside the training range when the minimum is tied, and what the normal output does at exactly 0 and 1.
```
### Constraints & Assumptions
- `X` is a numeric `pd.DataFrame`, and any column may contain NaN.
- `scipy.stats.norm` is available for the inverse normal CDF.
### Clarifying Questions to Ask
- What should `transform` return for a column that was entirely NaN at fit time?
- Should extra columns present at transform time be dropped or passed through?
- Can the data contain infinite values, and should they count as training values?
### What a Strong Answer Covers
- Mid-rank percentiles for tied values that match the formula and both examples.
- A transform that uses only the fitted knots, with the out-of-range, constant-column and NaN rules applied.
- The `eps` clip before `norm.ppf`, and the error cases (`ValueError` in the constructor, `KeyError` for a missing column).
- An output frame with the input index, the fit column order and `float64` dtype, leaving the input untouched.
- Fit and transform cost per column, and the memory held by the knots.
### Follow-up Questions
- How would this scale to a column with 100 million training rows?
- Why must the knots come from the training split only, and what breaks if you fit on train and test together?
- Which model families gain from this transform, and which see almost no change?
- How would you implement `inverse_transform`, and where does it lose information?
Overview: Implement a quantile normalizer for a pandas DataFrame that maps each value to its mid-rank training percentile, with an optional normal output. It tests tie handling, interpolation between fitted knots, clipping outside the training range and NaN rules.