Online Feature Schema Enforcer
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `FeatureSchema`. `fit(df)` learns a schema from a training `DataFrame` and returns `self`. `transform(records)` converts an iterable of dicts into a `float64` array of shape `(n, len(feature_names_))`.
The class must meet these requirements:
- Numeric (non-bool) columns get `numeric_stats_[col] = {"min": ..., "max": ..., "default": ...}`, computed from the non-NaN values, where the default is the median. An all-NaN numeric column gets `0.0` for all three.
- Every other column is categorical. `categories_[col]` is the sorted list of its distinct non-null values converted with `str`. `modes_[col]` is the most frequent of those values (ties go to the smallest), or `None` if the column has no non-null values.
- `feature_names_` follows the training column order. A numeric column contributes one feature named `col`. A categorical column contributes `col=<cat>` for each sorted category, then `col=__unknown__`.
- A missing value (absent key, `None` or NaN) takes the column's default or mode. Numeric values are clipped to `[min, max]`. Categorical values are compared via `str(v)` and one-hot encoded as `1.0`. An unseen value, or a missing value in a column whose mode is `None`, sets `col=__unknown__`.
- Extra keys are ignored. Empty input returns shape `(0, width)`. Calling `transform` before `fit` raises `RuntimeError`. Neither method mutates its input, and `transform` never refits.
For example:
```python
df = pd.DataFrame({"age": [20.0, 35.0, 50.0, np.nan],
"city": ["NY", "LA", "NY", "SF"],
"score": [1, 4, 2, 3]})
fs = FeatureSchema().fit(df)
fs.feature_names_
# ['age', 'city=LA', 'city=NY', 'city=SF', 'city=__unknown__', 'score']
fs.transform([{"age": 60, "city": "Paris", "score": 0}, {}])
# [[50, 0, 0, 0, 1, 1.0],
# [35, 0, 1, 0, 0, 2.5]]
```
In the first record, age 60 is clipped to the training maximum of 50, Paris is unseen, and score 0 is clipped to the minimum of 1. The empty record takes the median age 35, the mode NY and the median score 2.5.
```hint Freeze the layout
Work out every output position in `fit`. Then `transform` only has to find a slot and write a value into it.
```
```hint What counts as missing
A record can signal a missing value three ways: no key, `None`, or a float NaN. `NaN == NaN` is false, so NaN needs its own check.
```
### Constraints & Assumptions
- `fit` receives a pandas DataFrame with unique column names. Bool columns are categorical, so `True` becomes the category `"True"`.
- `transform` receives any iterable of dicts, which may be a generator that can be consumed only once.
- When a numeric field is present and not missing, `float(v)` succeeds on it.
### Clarifying Questions to Ask
- If a numeric field arrives as a non-numeric string such as `"abc"`, should `transform` raise or treat it as missing?
- Can a training category be the literal string `__unknown__`, which would collide with the reserved slot?
- Is the latency budget per single record or per batch? That decides whether a per-record loop is enough or the batch path should be vectorized.
### What a Strong Answer Covers
- Column typing (numeric non-bool versus categorical) and every statistic (bounds, medians, sorted string categories, modes with the tie rule) frozen in `fit`.
- A fixed output layout: training column order, one slot per numeric column, sorted category slots followed by `__unknown__`, all `float64`.
- Missing-value detection for absent keys, `None` and NaN, with defaults, modes, clipping and the unknown slot applied as specified.
- The edge cases: empty input, extra keys, all-NaN numeric and all-null categorical columns, `transform` before `fit`, and inputs left unmodified.
- The per-record cost and how the lookups stay constant time.
### Follow-up Questions
- How would you monitor schema drift in production?
- How would you persist and version the fitted schema?
- How would you cut per-request latency for wide schemas?
Overview: Implement a feature schema that learns numeric bounds, medians, sorted categories and modes from a training DataFrame, then turns raw dict records into a fixed-width float64 matrix. It tests missing-value handling, clipping, unknown categories and avoiding training-serving skew at inference time.