Confidence-Based Two-Stage Cascade Classifier
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `cascade_predict(cheap_proba, expensive_proba, threshold, classes=None)`. It predicts with the cheap model when that model's max probability is `>= threshold`, and otherwise defers to the expensive model's argmax. Return `(predictions, deferred_mask, deferral_rate)`. Also implement `cascade_average_cost(deferred, cheap_cost, expensive_cost)`, which returns `cheap_cost + mean(deferred) * expensive_cost` as a `float`.
Example:
```python
cheap = [[0.90, 0.05, 0.05], [0.40, 0.35, 0.25], [0.10, 0.75, 0.15], [0.30, 0.30, 0.40], [0.05, 0.15, 0.80]]
expensive = [[0.20, 0.70, 0.10], [0.10, 0.20, 0.70], [0.60, 0.30, 0.10], [0.25, 0.50, 0.25], [0.70, 0.20, 0.10]]
cascade_predict(cheap, expensive, 0.75)
# -> ([0, 2, 1, 1, 2], [False, True, False, True, False], 0.4)
cascade_average_cost([False, True, False, True, False], 1.0, 10.0) # -> 5.0
```
```hint Boundary rows
Look at the third row of the example: its top cheap probability equals the threshold exactly. Make sure your comparison sends it to the right model, and try to route every row at once with a boolean mask.
```
### Constraints & Assumptions
- Both matrices are 2-D `(n_samples, n_classes)` with identical shape and `n_samples ≥ 1`, else raise `ValueError`.
- `threshold` must lie in `[0, 1]`, else raise `ValueError`.
- Argmax ties resolve to the lowest column index.
- If `classes` is given, it must have length `n_classes` (else `ValueError`), and column indices map to those labels. Otherwise return indices `0..n_classes-1`.
- `deferral_rate` is a `float` equal to the mean of the boolean mask. `cascade_average_cost` raises `ValueError` on an empty mask.
### What a Strong Answer Covers
- Confidence as the cheap model's row max, with deferral only when confidence is strictly below the threshold.
- Per-row selection between the two argmaxes with lowest-index tie-breaking, and the optional mapping to class labels.
- Every validation case from the constraints, with return types as specified.
- Why the cost formula charges the cheap model on every sample and the expensive model only on deferred ones, plus the time and space complexity.
### Follow-up Questions
- How would you choose the threshold to hit a cost budget while maximizing accuracy?
- Is max probability the best confidence signal for routing?
- How would you extend this to a cascade of more than two models?
Overview: Implement a two-stage classifier cascade that keeps a cheap model's prediction when its top probability clears a threshold and defers the rest to an expensive model, then compute the average inference cost. Tests vectorized routing with numpy, boundary and tie handling, input validation, and how to pick a threshold under a cost budget.