Cost-Optimal Threshold Selection for a Binary Classifier
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `cost_optimal_threshold(y_true, y_proba, cost_fp, cost_fn, candidates)` for a binary classifier. `y_true` holds integer labels (0 or 1) and `y_proba` holds predicted probabilities of the positive class; both are 1-D NumPy arrays of shape `(n,)`. `cost_fp` and `cost_fn` are floats. Sweep `candidates` in the given order and return the threshold with the lowest total cost.
Requirements:
- For each candidate `t`, predict positive where `p >= t`, then count false positives and false negatives (sklearn's confusion matrix layout is `[[tn, fp], [fn, tp]]`).
- The cost of a threshold is `fp * cost_fp + fn * cost_fn`. True positives and true negatives cost 0.
- Return the lowest-cost candidate. When several candidates tie on cost, return the smallest threshold value.
- Return a Python `float`. Tests compare it with `assert_allclose(rtol=1e-9)`.
- On the same input, raising `cost_fn` while `cost_fp` stays fixed must never return a higher threshold. It returns a strictly lower one when the data allows it, as in the second example.
For example:
```python
candidates = np.array([0.3, 0.5, 0.7])
y_true = np.array([0, 0, 1, 1])
y_proba = np.array([0.2, 0.6, 0.4, 0.8])
cost_optimal_threshold(y_true, y_proba, 1, 1, candidates) # 0.3 (costs 1, 2, 1; the tie goes to 0.3)
cost_optimal_threshold(y_true, y_proba, 1, 10, candidates) # 0.3 (costs 1, 11, 10)
y_true = np.array([0, 0, 1, 1, 0])
y_proba = np.array([0.2, 0.6, 0.4, 0.8, 0.5])
cost_optimal_threshold(y_true, y_proba, 1, 1, candidates) # 0.7 (costs 2, 3, 1)
cost_optimal_threshold(y_true, y_proba, 1, 10, candidates) # 0.3 (costs 2, 12, 10)
```
```hint Count only what costs money
Only false positives and false negatives enter the cost. Two boolean masks per threshold are enough; the TP and TN counts are never needed.
```
```hint Check the tie rule
`np.argmin` returns the first minimum in array order. Ask whether that is always the smallest threshold value for the inputs you might receive.
```
### Constraints & Assumptions
- `y_true` and `y_proba` have the same length `n >= 1`, and `candidates` holds `k >= 1` floats.
- `candidates` is not guaranteed to be sorted, so apply the tie rule to threshold values. Position in the array does not decide a tie.
- Costs are non-negative floats.
- A score exactly equal to `t` counts as a positive prediction.
### What a Strong Answer Covers
- Correct FP and FN counts under the `p >= t` rule, computed with vectorized masks.
- A tie rule that returns the smallest threshold value whether or not `candidates` is sorted.
- Why a higher false-negative cost can only move the chosen threshold down, and why the move need not be strict.
- Time and space complexity, and a faster approach when there are many candidates.
- Edge cases: empty candidates, mismatched shapes, labels from one class only, and the return type.
### Follow-up Questions
- How would you find the true cost-optimal threshold without a candidate list?
- Why can a threshold tuned on one dataset generalize poorly in production?
- If the model is perfectly calibrated, what threshold does decision theory give for these costs, and why might the swept threshold differ from it?
Overview: Implement a NumPy function that sweeps candidate probability thresholds for a binary classifier and returns the one with the lowest total cost of false positives and false negatives. It tests confusion matrix counting, tie-breaking, and how asymmetric error costs move the decision threshold.