Conditional Permutation Importance for Random Forests
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement four functions that measure how much a fitted classifier's accuracy drops when one feature is shuffled. The shuffle is either global (standard permutation importance) or restricted to strata built from the feature's correlated features (conditional permutation importance). Importance is computed on the given `X` and `y` using `model.predict`, and accuracy is `mean(model.predict(X) == y)`.
The four functions:
- `make_strata(X, conditioning, n_bins)`: for each conditioning column `col`, take edges `np.quantile(col, np.linspace(0, 1, n_bins + 1)[1:-1])` and bin code `np.searchsorted(edges, col, side="right")`. A row's stratum id is the rank of its code tuple among the sorted unique tuples, as `int64`. An empty `conditioning` gives all zeros.
- `conditional_permute(column, strata, rng)`: return a copy where, for each stratum `s` in ascending order, `idx = np.flatnonzero(strata == s)` and `out[idx] = column[idx[rng.permutation(idx.size)]]`.
- `permutation_importance(model, X, y, feature, n_repeats, seed, strata=None)`: use one `np.random.default_rng(seed)` shared across all `n_repeats`. Each drop is baseline accuracy minus permuted accuracy. `strata=None` means a single stratum. Return `(mean, std)` of the drops as floats, using `np.std` (ddof 0).
- `compare_importances(model, X, y, conditioning, n_bins, n_repeats, seed)`: `conditioning` maps a feature index to a list of columns, and a missing key means `[]`. For every feature, compute the standard and the conditional mean importance with the same `seed`. Return a `DataFrame` with columns `["feature", "standard", "conditional"]`, one row per feature in column order, with `feature` as `int64`.
Example:
```python
a = [1, 2, 3, 4, 5, 6, 7, 8]
b = [1, 8, 2, 7, 3, 6, 4, 5]
X = np.column_stack([a, b, np.zeros(8)])
make_strata(X, [0], 4) # [0, 0, 1, 1, 2, 2, 3, 3]
make_strata(X, [0, 1], 2) # [0, 1, 0, 1, 2, 3, 2, 3]
make_strata(X, [], 3) # [0, 0, 0, 0, 0, 0, 0, 0]
```
With four bins, the interior quantiles of `a` are 2.75, 4.5 and 6.25, so the rows fall into bins in pairs. With two bins on both columns, each column splits at its median 4.5, and the four code tuples (0, 0), (0, 1), (1, 0), (1, 1) get ids 0 to 3 in sorted order.
```hint Stratum ids
Look at what `np.unique` can return for a 2-D array of bin codes when you pass an axis.
```
```hint Comparing the two scores
Count how many times the generator is called per repeat when there is a single stratum, and compare that with a plain global shuffle under the same seed.
```
### Constraints & Assumptions
- `X` is a numeric array of shape (n, d) and `y` has length n.
- `model` is already fitted and only needs `predict`.
- Feature and conditioning indices are 0-based column positions in `X`.
### What a Strong Answer Covers
- Strata that follow the binning rule exactly, with ids equal to the rank of each sorted unique code tuple, and the empty conditioning case.
- Within-stratum shuffles that visit strata in ascending order and draw from one shared generator, so a seed reproduces the result.
- A baseline computed once, drops defined as baseline minus permuted accuracy, and the mean and population standard deviation returned as floats.
- The output frame with the exact columns and dtype, and why a feature with no conditioning set gets the same score in both columns.
- Why the conditional score differs from the standard one for correlated features, and what the computation costs.
### Follow-up Questions
- Why does standard permutation importance overstate correlated features?
- How do you choose `n_bins` and the conditioning set?
- Should importance be computed on training data or held-out data?
Overview: Implement standard and conditional permutation importance for a fitted classifier, shuffling a feature either globally or only within quantile-bin strata of its correlated features. Tests reproducible random number handling, NumPy binning, and why correlated features look inflated under a global shuffle.