Implement CatBoost Ordered Target Statistics Encoding
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `ordered_target_statistics(categories, target, permutation, prior=None, prior_weight=1.0)`. Process rows in `permutation` order: each row's value is `(sum + a·p) / (count + a)` over rows of the same category that strictly precede it in the permutation (excluding itself). Return a float array in original row order.
Also implement `full_target_statistics(train_categories, train_target, query_categories, prior=None, prior_weight=1.0)`, which applies the same formula using all training rows for each query category.
In both functions, `p = prior`, or `mean(target)` when `prior is None` (the training target for the full variant), and `a = prior_weight`.
Example:
```python
cats = ["a", "b", "a", "a", "b"]
y = [1, 0, 0, 1, 1]
ordered_target_statistics(cats, y, [0, 1, 2, 3, 4], prior=0.5, prior_weight=1.0)
# [0.5, 0.5, 0.75, 0.5, 0.25]
ordered_target_statistics(cats, y, [4, 3, 2, 1, 0], prior=0.5, prior_weight=1.0)
# [0.5, 0.75, 0.75, 0.5, 0.5]
full_target_statistics(cats, y, ["a", "b", "c"], prior=0.5, prior_weight=1.0)
# [0.625, 0.5, 0.5]
```
```hint A row never sees itself
Look closely at the order in which you write a row's encoding and update the running totals for its category.
```
```hint Staying linear
Map categories to integer codes once and keep per-code arrays. Then check whether every other step, including validation, avoids a sort.
```
### Constraints & Assumptions
- Unseen categories (and each category's first occurrence) get exactly `p`.
- Raise `ValueError` if lengths differ, `permutation` is not a permutation of `range(n)`, or `prior_weight <= 0`.
- Categories may be strings or integers. Targets are real-valued.
- Ordered encoding must run in O(N) after category indexing.
### What a Strong Answer Covers
- Encoding each row before its own target enters the totals, so its value depends only on rows earlier in the permutation.
- Results written back in original row order, with first occurrences and unseen categories equal to the prior.
- Input validation in both functions.
- A linear encoding pass after category indexing, and the overall complexity including the indexing step.
- Why the full-data statistic is right at inference and leaks at training time.
### Follow-up Questions
- Why does CatBoost use a different permutation per tree or model, and what does it cost?
- Why not just use the full-data mean target per category during training?
- How would you extend this to multiclass targets or to combinations of categorical features?
Overview: Implement CatBoost-style ordered target statistics for a categorical feature, where each row is encoded only from rows that precede it in a permutation, plus the full-data version used at inference. It tests target leakage, prior smoothing, input validation and linear-time encoding.