KatInterview

Confusion Matrix Scorecard with Safe Division

Math & Bit ManipulationAuto-graded · 19 test cases
EasyAuto-gradedMath & Bit Manipulationmetricsconfusion-matrixedge-cases

Last 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 relevant
  • false_pos: shown items that were not relevant
  • true_neg: hidden items that were not relevant
  • false_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.

KeyDefinition
"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.