Confusion Matrix Scorecard with Safe Division
Math & Bit ManipulationAuto-graded · 19 test casesLast updated
Compute precision, recall, specificity, F1 and accuracy from confusion-matrix counts, returning 0.0 for any metric whose denominator is zero.
A binary classifier decides whether each suggested item should be shown to a user. After scoring a holdout set at a fixed cutoff, you have four counts:
true_pos: shown items that were relevantfalse_pos: shown items that were not relevanttrue_neg: hidden items that were not relevantfalse_neg: hidden items that were relevant
Write a function that turns these four counts into a scorecard of five metrics.
Metrics
Let total = true_pos + false_pos + true_neg + false_neg.
| Key | Definition |
|---|---|
"precision" | true_pos / (true_pos + false_pos) |
"recall" | true_pos / (true_pos + false_neg) |
"specificity" | true_neg / (true_neg + false_pos) |
"f1" | 2 * precision * recall / (precision + recall) |
"accuracy" | (true_pos + true_neg) / total |
Zero-denominator rule
If the denominator of any metric is zero, that metric is 0.0. For F1, the denominator is precision + recall, using the precision and recall values you computed above (after their own zero-denominator handling).
Output
Return a dictionary with exactly the five keys above, each mapped to a Python float. Compute F1 using the formula exactly as written, from the computed precision and recall, so that floating-point results match the expected values.
Constraints
- All four inputs are non-negative integers.
- The counts may be zero in any combination, including all four being zero.
- Time and extra space should be O(1).
Examples
Example 1
Input: confusion_scorecard(120, 30, 820, 30)
Output: {'precision': 0.8, 'recall': 0.8, 'specificity': 0.9647058823529412, 'f1': 0.8000000000000002, 'accuracy': 0.94}
Hints
Hint 1
Each metric is a simple ratio of the counts. Write a tiny helper that returns 0.0 when the denominator is 0.
Hint 2
F1 should be built from the precision and recall values you already computed, not from the raw counts, and it needs its own zero check on precision + recall.
Hint 3
Use the formula 2 * p * r / (p + r) literally, in that order of operations, to match the expected floating-point output.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each metric is a ratio of sums of the four counts, so the whole task is careful arithmetic with one guard per ratio.
- Compute precision, recall and specificity as ratios of the relevant counts, returning
0.0when the denominator is zero. - Compute F1 from the precision and recall just obtained. Its denominator is
precision + recall; it is zero only when both are zero, which avoids a division error. - Compute accuracy as correct decisions over all decisions, again guarding against an empty total.
- Return the five values in a dictionary.
Why it is correct
The formulas are the standard definitions. The zero-denominator rule maps degenerate slices (no items shown, no relevant items, no negatives, or no data at all) to 0.0 rather than raising an error. Computing F1 from the already computed precision and recall, using 2 * p * r / (p + r) in that exact order, reproduces the expected floating-point values (for example 0.8000000000000002 for the sample).
A note on interpretation: with a low positive rate, accuracy can look high simply because of many easy true negatives, whereas precision directly measures how many shown items were relevant.
Complexity
O(1) time and O(1) space.
Reference solution
from typing import Dict
def confusion_scorecard(true_pos: int, false_pos: int, true_neg: int, false_neg: int) -> Dict[str, float]:
tp, fp, tn, fn = true_pos, false_pos, true_neg, false_neg
precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0
recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0
specificity = tn / (tn + fp) if (tn + fp) > 0 else 0.0
f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0.0
total = tp + fp + tn + fn
accuracy = (tp + tn) / total if total > 0 else 0.0
return {
"precision": precision,
"recall": recall,
"specificity": specificity,
"f1": f1,
"accuracy": accuracy,
}