Reduced-Error Post-Pruning of a Decision Tree
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
A tree is a nested dict. Internal nodes have `feature`, `threshold`, `left`, `right` and `value` (the node's training-majority class). Leaves are `{"value": c}`. Implement `predict(tree, X)`, `count_leaves(tree)` and `reduced_error_prune(tree, X_val, y_val)`, which returns a pruned copy.
The functions follow these rules:
- Routing: `x[feature] <= threshold` goes left. `predict` returns an int array of shape `(n,)`.
- Prune bottom-up: children first, using only validation rows that reach each node.
- Replace a node with `{"value": node["value"]}` when its leaf error ≤ the (already pruned) subtree error. Ties and nodes reached by no rows are pruned.
- Leaves in the output contain only `"value"` (an int). Kept internal nodes keep all five keys.
- Never mutate the input tree.
For example:
```python
tree = {"feature": 0, "threshold": 5.0, "value": 0,
"left": {"value": 0},
"right": {"feature": 1, "threshold": 2.0, "value": 1,
"left": {"value": 1}, "right": {"value": 0}}}
X_val = [[3, 0], [7, 1], [7, 3]]
y_val = [0, 1, 1]
predict(tree, X_val) # array([0, 1, 0])
count_leaves(tree) # 3
reduced_error_prune(tree, X_val, y_val)
# {"feature": 0, "threshold": 5.0, "value": 0,
# "left": {"value": 0}, "right": {"value": 1}}
# right subtree: 1 error vs leaf(1): 0 errors -> pruned
```
```hint Order of decisions
A node's subtree error has to be measured with its children already pruned. Choose the traversal order that guarantees this, and pass each call only the rows that reach it.
```
```hint Nodes no row reaches
Work out what the leaf error and the subtree error are when a node receives zero validation rows, and check that your comparison collapses it.
```
### Constraints & Assumptions
- `X_val` is a 2-D numeric array. `y_val` holds integer class labels of matching length.
- Every internal node stores a valid `value`.
### What a Strong Answer Covers
- Routing in `predict` that matches the `<=` rule and returns an int array of shape `(n,)`
- A bottom-up recursion that judges each node only on the validation rows reaching it
- The leaf-versus-subtree comparison, including ties and nodes no row reaches
- The output format (leaf dicts with only `"value"`, kept nodes with all five keys) and leaving the input tree untouched
- Time and space complexity
### Follow-up Questions
- Why does pruning ties (leaf error equal to subtree error) make sense?
- What are the risks of reduced-error pruning with a small validation set?
- How would you make pruning a single pass rather than re-predicting each subtree?
Overview: Implement prediction, leaf counting and bottom-up reduced-error pruning for a decision tree stored as nested dicts, using a validation set. It tests recursive tree handling, routing rows to each node, the leaf versus subtree error comparison, and copying a tree without mutating it.