Compute confusion matrix counts from predicted probabilities at a threshold
Role: Data Scientist
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `confusion_counts_at_threshold(y_true, y_proba, threshold)`. Given positive-class probabilities `y_proba` (1-D float, shape `(n,)`) and labels `y_true` (1-D int of 0/1, shape `(n,)`), threshold the probabilities and return the four confusion-matrix counts.
Requirements:
- Predict positive when `p >= threshold`, negative otherwise.
- Return a 4-tuple in the order `(tn, fp, fn, tp)`. This is sklearn's `[[tn, fp], [fn, tp]]` raveled row-major, and it differs from the textbook `(tp, fp, fn, tn)`.
- Each element is a plain Python `int`, never a NumPy scalar or a 2x2 array.
- Either `sklearn.metrics.confusion_matrix(...).ravel()` or counting by hand is allowed.
Examples:
```python
y_true = [0, 0, 1, 1]
y_proba = [0.2, 0.7, 0.4, 0.9]
confusion_counts_at_threshold(y_true, y_proba, 0.5)
# predictions: [0, 1, 0, 1]
# (1, 1, 1, 1) # (tn, fp, fn, tp)
```
```python
y_true = [0, 0, 0, 1, 1, 1, 1]
y_proba = [0.1, 0.5, 0.3, 0.8, 0.2, 0.5, 0.9]
confusion_counts_at_threshold(y_true, y_proba, 0.5)
# predictions: [0, 1, 0, 1, 0, 1, 1]
# (2, 1, 1, 3) # (tn, fp, fn, tp)
```
```hint A degenerate input
Check what `confusion_matrix(...).ravel()` returns when only one class appears in both the labels and the predictions.
```
### What a Strong Answer Covers
- Thresholding with the inclusive `>=` rule, so a probability equal to the threshold counts as positive
- Returning the counts in `(tn, fp, fn, tp)` order and explaining where that order comes from
- Converting every count to a plain Python `int`
- Inputs where a class is missing from the labels or the predictions
- A vectorized count that runs in O(n)
### Follow-up Questions
- Why cast to `int` instead of returning NumPy scalars?
- How would you handle a class missing entirely from `y_true` or the predictions?
- How would you compute the counts at many thresholds without rescanning the data for each one?
- How do you get precision, recall and F1 from these four counts, and what do you return when a denominator is zero?
Overview: Write a Python function that thresholds predicted probabilities and returns the true negative, false positive, false negative and true positive counts in a fixed order. It tests tie handling at the threshold, the sklearn confusion matrix layout, native return types and missing-class edge cases.