Random Forest Per-Tree Prediction Spread for Uncertainty
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `forest_prediction_spread(forest, X)` for a fitted random forest regressor. Collect each tree's predictions from `forest.estimators_`, average them to reproduce the forest's prediction, and compute the per-sample spread across trees. Return the tuple `(per_tree_predictions, mean_prediction, spread)`.
- `per_tree_predictions`: float array of shape `(n_trees, n_samples)`, row `i` equal to `forest.estimators_[i].predict(X)`.
- `mean_prediction`: column mean, shape `(n_samples,)` (matches `forest.predict(X)` up to floating-point rounding).
- `spread`: population standard deviation (`ddof=0`) across trees, shape `(n_samples,)`.
Example:
```python
# tree predictions on 3 samples
[[1, 2, 3],
[3, 2, 5],
[5, 2, 7]]
mean -> [3.0, 2.0, 5.0]
spread -> [1.633, 0.0, 1.633] # sqrt(8/3)
```
```hint Axis and ddof
Check which axis each reduction runs over. If you reach for pandas, its `std` uses a different default `ddof` than NumPy's.
```
### Constraints & Assumptions
- `forest` exposes `estimators_` (at least 1 tree), each with `predict(X)` returning one value per row.
- `X` is array-like of shape `(n_samples, n_features)`.
- A single tree yields zero spread.
### What a Strong Answer Covers
- Stacking the per-tree predictions, in `estimators_` order, into a `(n_trees, n_samples)` float matrix.
- Reducing over the tree axis, with the population standard deviation the spec asks for.
- Why the column mean reproduces `forest.predict(X)`, and how exact that match is.
- What the spread measures and when it is zero.
### Follow-up Questions
- Is the across-tree spread a calibrated prediction interval?
- How would you avoid storing the full `(n_trees, n_samples)` matrix for large inputs?
- Why is the spread usually smaller on the training rows than on new data?
Overview: Implement a function that collects every tree's predictions from a fitted random forest regressor, reproduces the forest's average, and computes the per-sample standard deviation across trees. It tests how forests aggregate trees, NumPy axis and ddof handling, and what tree disagreement says about uncertainty.