Frequency Encoder with Unseen Indicator
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `FrequencyEncoder` with `fit`, `transform` and `fit_transform`. `fit` learns per-column category frequencies from a training DataFrame. `transform` replaces each column with its learned frequency plus a binary unseen flag.
The encoder must meet these requirements:
- `normalize=True` (the default) gives the count divided by the number of training rows. `normalize=False` gives the raw count. Both are `float64`.
- For each fitted column `col` (in fit order), the output has `{col}_freq` then `{col}_is_unseen` (`int64` 0/1).
- Categories not seen in training get freq `0.0` and `is_unseen = 1`.
- Missing values (`NaN`/`None`) form one shared category, which is unseen if it was absent in training.
- Preserve the input index, never mutate inputs, and have `fit` return `self`.
Example:
```python
train = pd.DataFrame({"c": ["a", "a", "a", "b"]})
test = pd.DataFrame({"c": ["b", "z", None]})
FrequencyEncoder().fit(train).transform(test)
# c_freq c_is_unseen
# 0 0.25 0
# 1 0.00 1
# 2 0.00 1
```
```hint Watch the missing values
Check how `NaN` behaves as a dictionary key, and whether `None` and `NaN` end up as the same key, before you count missing values as one category.
```
### What a Strong Answer Covers
- Counting categories per column on the training data only, with the normalized and raw options both stored as `float64`.
- Treating every kind of missing value as one category that can be counted and looked up.
- Filling unseen categories with `0.0` and setting the `int64` indicator from the same lookup.
- Output column names and order, the preserved index, and an unchanged input.
- The cost of fit and transform in rows and columns.
### Follow-up Questions
- Why fit frequencies only on the training partition?
- Two categories share the same frequency. Is that a problem?
- A category appears once in training and thousands of times in production. How does the encoding behave, and what would you monitor?
- How would you vectorize `transform` for a column with millions of rows?
Overview: Implement a frequency encoder that replaces each categorical column with its training frequency and adds a flag for categories never seen in training. It tests the split between fit and transform, treating missing values as one category, dtype and column-order rules, and avoiding leakage.