Find the cost-optimal classification threshold from an ROC curve
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Write `expected_cost_curve(y_true, y_proba, cost_fp, cost_fn)` that returns `(best_threshold, min_cost)` as two Python floats: the threshold that minimizes the per-sample cost `(fp * cost_fp + fn * cost_fn) / n`, and that cost. A sample is predicted positive when its probability is at or above the threshold.
Requirements:
- Get `fpr, tpr, thresholds` from `roc_curve(y_true, y_proba, drop_intermediate=False)` and sweep `thresholds[1:]`. `thresholds[0]` is `np.inf` and is not a returnable value.
- Reconstruct the counts from the curve (no re-thresholding): `P = y_true.sum()`, `N = len(y_true) - P`, `fp = fpr * N`, `fn = (1 - tpr) * P`.
- On ties, return the lowest threshold.
- Vectorize the sweep with no per-threshold loop, so the work after `roc_curve` is O(n).
Example:
```python
y_true = [1, 0, 1, 0, 1, 0, 1, 0]
y_proba = [0.9, 0.6, 0.8, 0.3, 0.7, 0.5, 0.4, 0.2]
expected_cost_curve(y_true, y_proba, 1, 1) # (0.7, 0.125)
expected_cost_curve(y_true, y_proba, 1, 10) # (0.4, 0.25)
```
At unit costs, threshold 0.7 catches three of the four positives with no false positives. When a false negative costs 10, catching the fourth positive at 0.4 is worth the two false positives it brings.
```hint Array order
Check which direction `roc_curve` orders its thresholds before deciding how `argmin` should break ties.
```
```hint Exact counts
A rate multiplied back by a class total is a float. Ask whether two operating points with the same true cost are guaranteed to compare equal.
```
### Constraints & Assumptions
- `y_true` is binary {0, 1} with at least one positive and one negative.
- scikit-learn 1.3 or later, where `thresholds[0]` is `np.inf`.
### What a Strong Answer Covers
- Why the distinct scores returned by `roc_curve` are a complete set of candidate thresholds
- Reconstructing false positive and false negative counts from the ROC rates and class totals
- Breaking ties toward the lowest threshold given the order `roc_curve` uses
- The real complexity: the sort inside `roc_curve` and the linear sweep after it
- Why raising the false-negative cost can only move the chosen threshold down
### Follow-up Questions
- Why is sweeping `thresholds[1:]` sufficient, compared with a dense grid of thresholds?
- How would you handle the all-negative operating point if it were truly optimal?
- How does the ratio `cost_fn / cost_fp` relate to the optimal threshold analytically?
- This threshold is tuned and scored on the same data. How would you pick one that holds up on new data?
Overview: Write a vectorized Python function that picks the classification threshold minimizing a weighted cost of false positives and false negatives, using the operating points of an ROC curve. It tests reading confusion counts off ROC rates, tie-breaking, complexity, and how unequal error costs move the threshold.