Quantile Regression Forest Prediction
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Given leaf indices `train_leaves` (n_train, n_trees) and `test_leaves` (n_test, n_trees), plus optional bootstrap `inbag_counts`, implement `qrf_weights`, `weighted_quantile`, `qrf_predict_quantiles` (shape (n_test, n_quantiles)) and `qrf_prediction_interval` (returns `(lower, upper)`).
```python
def qrf_weights(train_leaves, test_leaves, inbag_counts=None): ...
def weighted_quantile(y, weights, q): ...
def qrf_predict_quantiles(train_leaves, test_leaves, y_train, quantiles, inbag_counts=None): ...
def qrf_prediction_interval(train_leaves, test_leaves, y_train, alpha, inbag_counts=None): ...
```
Requirements:
- Per tree, train row `i` gets `count[i,t]·1[same leaf] / Σ matching counts` (counts default to 1). Average over trees with a nonzero denominator only. A test point with no contributing tree gets a row of NaN.
- `weighted_quantile`: drop zero weights, normalize, return the smallest sorted `y` whose cumulative weight is `≥ q`. A scalar `q` returns a `float`.
- NaN weights or a weight sum `≤ 0` give NaN quantile(s).
- The interval uses levels `alpha/2` and `1 - alpha/2`.
- Raise `ValueError` for: tree-count mismatch, wrong `inbag_counts` shape, `q` outside [0, 1], `alpha` outside (0, 1), length mismatch of `y` and weights.
```hint One tree at a time
For a single tree, comparing a column of test leaf ids against a column of train leaf ids with broadcasting gives the whole (n_test, n_train) match matrix at once. Keep a per-test-point count of how many trees actually contributed.
```
```hint Rounding at the boundary
A cumulative sum of normalized weights can land one rounding step below a level it should equal. Decide how your comparison with `q` handles that, and check what happens at `q = 1`.
```
### Example
```python
train_leaves = [[1, 3], [1, 4], [2, 3], [2, 4]]
y_train = [1, 2, 3, 4]
test_leaves = [[1, 3], [2, 4]]
qrf_weights(train_leaves, test_leaves)
# [[0.5, 0.25, 0.25, 0.0],
# [0.0, 0.25, 0.25, 0.5]]
qrf_predict_quantiles(train_leaves, test_leaves, y_train, [0.1, 0.5, 0.6, 0.9, 1.0])
# [[1., 1., 2., 3., 3.],
# [2., 3., 4., 4., 4.]]
qrf_prediction_interval(train_leaves, [[1, 3]], y_train, 0.5)
# (array([1.]), array([2.]))
```
Test point 0 shares leaf 1 with train rows 0 and 1 in the first tree and leaf 3 with rows 0 and 2 in the second, so row 0 gets weight 0.5 and rows 1 and 2 get 0.25 each. Its cumulative weights over `y = 1, 2, 3` are 0.5, 0.75 and 1.0, so the 0.5 quantile is 1 and the 0.6 quantile is 2.
### Constraints & Assumptions
- Leaf ids are integers. `inbag_counts` are non-negative with shape (n_train, n_trees).
- Predicted quantiles are always values from `y_train` (no interpolation).
- `y_train` has one target per training row.
### What a Strong Answer Covers
- Per-tree normalization by the matching counts, averaging over contributing trees only, and the NaN row when no tree contributes.
- A quantile rule that always returns an actual training target, handles duplicate `y` values, and behaves correctly when a cumulative weight equals `q` up to rounding.
- Every listed `ValueError`, the NaN path for bad weights, and a scalar `q` returning a float.
- Vectorization across training rows, with the time and memory cost.
- How the weights relate to the forest's mean prediction when bootstrap counts are supplied.
### Follow-up Questions
- With bootstrap counts, why does `W @ y_train` reproduce the forest's mean prediction, and what changes when the counts are left at 1?
- How would you check whether the prediction intervals are calibrated?
- The weight matrix is `n_test × n_train`. How would you predict quantiles for a large test set without storing it?
Overview: Implement quantile regression forest prediction from leaf indices: per-tree co-membership weights over training rows, weighted quantiles that return actual training targets, and central prediction intervals. It tests careful normalization, input validation, floating-point boundaries and vectorized NumPy code.