Compute hyperparameter importance with a random forest surrogate
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `param_importance(trials, space, score_col="score", n_estimators=100, seed=0)`. `trials` is a DataFrame of trial parameters and scores. `space` maps each parameter name to a kind, one of `"float"`, `"int"`, `"log"` or `"categorical"`; any other kind raises `ValueError`. Fit a random forest surrogate of the score on the encoded parameters and return each parameter's relative importance.
The function must:
- Drop rows whose `score_col` is NaN (failed trials) before encoding.
- Encode in `space` order: `float` and `int` as float, `log` as `log10(value)`, and `categorical` as one 0/1 column per unique value (cast to str, in sorted string order).
- Fit `RandomForestRegressor(n_estimators=n_estimators, random_state=seed)` with all other arguments at their defaults.
- Sum the `feature_importances_` of one-hot columns back to their parameter, then normalise so the importances sum to 1 (all zeros if the forest never splits).
- Return a float64 `pd.Series` named `"importance"` with its index named `"param"`, sorted by descending importance, with ties kept in `space` order.
Example 1, constant scores, so the forest never splits:
```python
df = pd.DataFrame({
"a": [1, 2, 3, 4],
"b": [0.1, 0.2, 0.3, 0.4],
"c": ["x", "y", "x", "y"],
"score": 0.7,
})
param_importance(df, {"b": "float", "c": "categorical", "a": "float"}, n_estimators=10)
# param
# b 0.0
# c 0.0
# a 0.0
# Name: importance, dtype: float64
```
All three importances are zero, so they tie and keep the `space` order b, c, a.
Example 2, one failed trial and only one parameter that varies:
```python
df = pd.DataFrame({
"a": [5, 5, 5, 5, 5, 5],
"b": [0.1, 0.2, 0.3, 0.4, 0.5, 0.6],
"c": ["x", "x", "x", "x", "x", "x"],
"score": [0.1, 0.2, 0.3, 0.4, 0.5, float("nan")],
})
param_importance(df, {"b": "float", "c": "categorical", "a": "float"}, n_estimators=10)
# param
# b 1.0
# c 0.0
# a 0.0
# Name: importance, dtype: float64
```
The NaN row is dropped before fitting. Columns `a` and `c` are constant, so no tree can split on them and they get exactly zero, which leaves all of the importance on `b`.
```hint Bookkeeping for encoded columns
A categorical parameter turns into several columns. Decide how you will know, after the fit, which parameter each entry of `feature_importances_` belongs to.
```
```hint Degenerate cases
Work through Example 1 by hand. What does the forest report when no tree splits, what does your normalisation do with a total of zero, and which kind of sort keeps tied parameters in `space` order?
```
### Constraints & Assumptions
- `trials` has a column for every key of `space` plus `score_col`; other columns are ignored.
- Values of a `log` parameter are positive.
### What a Strong Answer Covers
- Validates every kind and drops failed trials before encoding, so the forest never sees a NaN target.
- Encodes each kind as specified (log10, one-hot in sorted string order) and tracks which parameter owns each encoded column.
- Folds one-hot importances back per parameter and handles a zero total without dividing by zero.
- Returns a float64 Series with the right name and index name, sorted descending with ties in `space` order.
- Explains what impurity importance measures and when it misleads.
### Follow-up Questions
- Impurity importances are biased. How would you get a more reliable estimate?
- How would you quantify uncertainty in the ranking?
- How would you capture interaction effects between hyperparameters?
Overview: Implement a function that fits a random forest surrogate on hyperparameter tuning trials and returns each parameter's relative importance. It tests encoding log-scale and categorical parameters, folding one-hot importances back to their parameter, and handling failed trials, zero importances and tie order.