Laplace-Smoothed Decision Tree Probabilities
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `predict_proba(tree, X, n_classes, alpha=1.0)`, which routes each row of `X` to a leaf and returns `(counts + alpha) / (counts.sum() + alpha * n_classes)` as a float array of shape `(n_samples, n_classes)`. Also implement `predict(tree, X, n_classes, alpha=1.0)`, which returns the argmax class per row as an `int` array, with the lowest label winning ties.
Internal nodes are dicts with `feature`, `threshold`, `left` and `right`. Go left when `x[feature] <= threshold`. Leaves are dicts with a `counts` list.
Example:
```python
tree = {"feature": 0, "threshold": 2.5,
"left": {"counts": [3, 1, 0]},
"right": {"counts": [0, 0, 5]}}
predict_proba(tree, [[2.5, 0.0], [3.0, 0.0]], 3, alpha=1.0)
# [[4/7, 2/7, 1/7], [1/8, 1/8, 6/8]]
predict(tree, [[2.5, 0.0], [3.0, 0.0]], 3) # [0, 2]
```
```hint The boundary case
The first example row has `x[0]` exactly equal to the threshold. Check which way your comparison sends it.
```
### What a Strong Answer Covers
- Routing each row to its leaf with the `<=` rule, including values equal to the threshold.
- Applying the smoothing per row so the output has shape `(n_samples, n_classes)` and every row sums to 1.
- Handling degenerate or invalid input: negative `alpha`, a leaf whose counts length differs from `n_classes`, and an empty leaf with `alpha = 0`.
- Breaking ties in `predict` toward the lowest label, and saying whether smoothing can change the predicted class.
- The time and space complexity.
### Follow-up Questions
- With one `alpha` for every class, smoothing never changes `predict`. Where does it change a decision or a metric?
- How would you choose `alpha`, and what would you use in place of a uniform pseudo-count when the classes are imbalanced?
- How would you vectorize the routing when `X` has millions of rows?
Overview: Implement predict_proba and predict for a decision tree stored as nested dicts, routing each row to a leaf and applying Laplace smoothing to that leaf's class counts. It tests tree traversal, the threshold boundary rule, the smoothing formula, tie-breaking and edge cases such as empty leaves.