Leaf-Wise Best-First Tree Growth for Gradient Boosting
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Implement `best_split`, `grow_leaf_wise` and `predict_tree` for a second-order (gradient/hessian) regression tree of the kind used in gradient boosting. Grow the tree best-first: repeatedly split the current leaf with the largest gain, using a priority queue, until `max_leaves` leaves exist or no leaf has a valid split.
Signatures:
```python
def best_split(X, grad, hess, idx, reg_lambda=1.0, gamma=0.0, min_child_weight=0.0): ...
def grow_leaf_wise(X, grad, hess, max_leaves, reg_lambda=1.0, gamma=0.0, min_child_weight=0.0): ...
def predict_tree(tree, X): ...
```
Requirements:
- `best_split` looks at the samples in `idx` and tries midpoints between consecutive distinct sorted values of each feature (left is `x <= t`). With $G_L, H_L$ and $G_R, H_R$ the gradient and hessian sums of the two children and $G, H$ those of the node, the gain is
$$
\text{gain} = \frac{1}{2}\left(\frac{G_L^2}{H_L + \lambda} + \frac{G_R^2}{H_R + \lambda} - \frac{G^2}{H + \lambda}\right) - \gamma
$$
where $\lambda$ is `reg_lambda` and $\gamma$ is `gamma`. Both children need a hessian sum `>= min_child_weight`. Return `(feature, threshold, gain)` for the strictly highest gain, scanning features in index order and thresholds in ascending order so that the first candidate wins ties. Return `None` if no gain is `> 0`.
- Node ids follow creation order: the root is `0`, and each split appends its left child, then its right child. Equal gains pop the smaller node id first.
- `grow_leaf_wise` returns a dict with arrays `feature`, `left`, `right` (int, `-1` for leaves), `threshold` (`nan` for leaves) and `gain` (`0.0` for leaves). It also includes `split_order`, a list of split node ids in expansion order.
- `value` is stored for every node and equals `-G / (H + reg_lambda)` over that node's samples.
- `predict_tree` routes each row from node `0` (`<=` goes left) and returns the leaf `value`.
Example:
```python
X = [[1], [2], [3], [4], [5], [6]]
grad = [-5, -5, -5, 2, 8, 8]
hess = [1] * 6
tree = grow_leaf_wise(X, grad, hess, max_leaves=3, reg_lambda=1.0)
tree["split_order"] # [0, 2]
tree["feature"] # [0, -1, 0, -1, -1]
tree["threshold"][[0, 2]] # [3.5, 4.5]
predict_tree(tree, X) # [3.75, 3.75, 3.75, -1.0, -5.333, -5.333]
```
```hint Scoring every threshold in one pass
After sorting a node's samples by one feature, prefix sums of `grad` and `hess` give $G_L$ and $H_L$ for every boundary at once. Only boundaries where the next sorted value is different are real candidates.
```
```hint When gains need computing
Ask whether splitting one leaf can change the best split of a different leaf. The answer tells you when to compute a leaf's gain and whether heap entries can ever go stale.
```
```hint Heap ordering
Python's `heapq` is a min-heap. Choose the tuple you push so that the largest gain comes out first and equal gains come out by smaller node id.
```
### Constraints & Assumptions
- `X` is a 2-D numeric array of shape `(n_samples, n_features)`. `grad` and `hess` are 1-D arrays of length `n_samples`.
- `max_leaves` counts leaves, so a tree with `max_leaves = 1` is just the root.
- Defaults are `reg_lambda = 1.0`, `gamma = 0.0` and `min_child_weight = 0.0`.
### What a Strong Answer Covers
- A split search that sorts each feature per node, uses prefix sums, and applies the distinct-value, `min_child_weight`, `gamma` and strictly-positive rules with first-candidate-wins ties.
- Best-first expansion with a priority queue keyed on gain, node ids in creation order, and equal gains broken by the smaller node id.
- Correct stopping on the leaf count or an empty queue, and output arrays with the leaf sentinels and a Newton value on every node.
- A `predict_tree` that uses the same `<=` routing as the split, plus the time complexity of the whole procedure.
### Follow-up Questions
- How does leaf-wise growth compare with depth-wise growth in training loss, overfitting risk and speed, and which settings keep a leaf-wise tree from overfitting?
- How would a histogram-based split search change the complexity, and how can a node's sibling histogram be obtained cheaply?
- Where do the leaf value $-G/(H+\lambda)$ and the gain formula come from?
- How would you extend `best_split` to handle missing feature values?
Overview: Implement best-first, leaf-wise growth of a gradient and hessian regression tree with a priority queue, a regularized split gain and exact tie rules. Tests split search with prefix sums, heap ordering, stopping on a leaf budget and how leaf-wise growth differs from depth-wise growth.