Vectorised Gradient Boosted Ensemble Inference
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
A trained gradient-boosted ensemble is stored as a list of trees. Each tree is a dict of equal-length node arrays `left`, `right`, `feature`, `threshold`, `value` and `default_left`, and the root is node `0`. Implement `predict_leaf_indices`, `predict_raw`, `staged_predict_raw` and `predict` using NumPy operations over all rows at once, with no Python loop over rows.
```python
def predict_leaf_indices(X, tree): ...
def predict_raw(X, trees, base_score, learning_rate): ...
def staged_predict_raw(X, trees, base_score, learning_rate): ...
def predict(X, trees, base_score, learning_rate, objective="regression"): ...
```
The functions must follow these rules:
- A node is a leaf if and only if `left[node] == -1`. At an internal node, go left when `x[feature[node]] <= threshold[node]`. A NaN goes left if and only if `default_left[node]` is true.
- `predict_leaf_indices` returns an integer array of leaf node indices with shape `(n_samples,)`.
- `predict_raw` returns `base_score + learning_rate * Σ value[leaf]`, summed over all trees. An empty ensemble returns `base_score` for every row.
- `staged_predict_raw` returns the cumulative margins after each tree, with shape `(n_trees, n_samples)`.
- `predict` applies the identity for `"regression"` and a numerically stable sigmoid for `"binary:logistic"` that stays finite at margins of `1e4` and `-1e4`. Any other objective raises `ValueError`.
Node arrays may be Python lists or NumPy arrays, for example exported from a scikit-learn tree's `tree_` attribute. Results must match scikit-learn's `GradientBoostingRegressor` and `GradientBoostingClassifier` within `rtol=1e-6`.
For example:
```python
tree = {"left": [1, -1, -1], "right": [2, -1, -1], "feature": [0, -2, -2],
"threshold": [1.0, -2.0, -2.0], "value": [0.0, 0.3, -0.2],
"default_left": [True, True, True]}
X = [[0.0], [1.0], [3.0], [np.nan]]
predict_leaf_indices(X, tree) # [1, 1, 2, 1] (1.0 <= 1.0 goes left, NaN takes the default left)
predict_raw(X, [tree], 0.25, 0.1) # [0.28, 0.28, 0.23, 0.28]
```
```hint One pointer per row
Keep an array holding each row's current node, and move every row that is still at an internal node in a single step. Then ask how many steps that loop can take.
```
```hint Watch the exponent
Look at which sign of the margin makes `exp` overflow in `1 / (1 + exp(-z))`, and find an equivalent form to use on that side.
```
### Constraints & Assumptions
- `X` has shape `(n_samples, n_features)` and may contain NaN.
- Trees in one ensemble can have different depths and node counts. At leaves, `feature` and `threshold` hold placeholder values (such as -2) that are never read.
- Thresholds are float64. scikit-learn casts inputs to float32 before routing, so for the comparison with it, assume `X` holds values that are exactly representable in float32.
### Clarifying Questions to Ask
- When trees come from scikit-learn, is `value` already flattened to one number per node, or passed through with shape `(node_count, 1, 1)`?
- Should the functions cast `X` to float32 themselves so routing matches scikit-learn on arbitrary float64 input?
- Is a tree that is only a root leaf allowed?
### What a Strong Answer Covers
- Vectorised routing with a per-row node pointer, the `<=` tie rule and the per-node NaN direction
- Accumulating shrunk leaf values from `base_score`, including the empty ensemble and the staged output shape
- A sigmoid that avoids overflow for large positive and negative margins, and rejection of unknown objectives
- What agreement with scikit-learn depends on: the node layout, the shape of `value` and float32 input precision
- Time and memory cost in terms of trees, rows and depth
### Follow-up Questions
- How would you vectorise across trees as well as rows?
- How would you extend this to multiclass softmax?
- Why might predictions diverge from the training library near thresholds?
Overview: Implement batch inference for a gradient-boosted tree ensemble in NumPy, routing all rows through each tree without a per-row loop. It tests tree traversal with NaN default directions, staged margin accumulation, a numerically stable sigmoid and matching scikit-learn's predictions.