KatInterview

Compute Precision and Recall from Confusion Counts

Math & Bit ManipulationAuto-graded · 20 test cases
EasyAuto-gradedMath & Bit Manipulationmathconfusion-matrixprecision-recall

Last updated

Compute precision and recall from the four confusion-matrix counts of a binary classifier, returning 0.0 for a metric whose denominator is zero.

Compute Precision and Recall from Confusion Counts

A binary classifier was evaluated on a labeled dataset, and its results were summarized as four counts:

  • tp: examples that are actually positive and were predicted positive.
  • fp: examples that are actually negative but were predicted positive.
  • tn: examples that are actually negative and were predicted negative.
  • fn: examples that are actually positive but were predicted negative.

Write a function that returns the classifier's precision and recall.

Definitions

  • Precision is the fraction of predicted positives that are truly positive: tp / (tp + fp).
  • Recall is the fraction of actual positives that the classifier found: tp / (tp + fn).

The count tn is part of the input, but neither metric depends on it.

Zero denominators

If a metric's denominator is zero, the metric is undefined. In that case, report that metric as 0.0.

  • If tp + fp == 0 (no positive predictions), precision is 0.0.
  • If tp + fn == 0 (no actual positives), recall is 0.0.

The two metrics are handled independently of each other.

Output

Return a list of two floats in the order [precision, recall]. Use ordinary true division, so integer inputs still give float results.

Constraints

  • tp, fp, tn, fn are non-negative integers.
  • All four values may be zero.
  • Do not raise an exception for zero denominators.
  • Return exactly two values: [precision, recall].

Examples

Example 1

Input: compute_precision_recall(40, 10, 45, 5)

Output: [0.8, 0.8888888888888888]

Example 2

Input: compute_precision_recall(0, 8, 12, 0)

Output: [0, 0]

Hints

Hint 1

Write down which cells of the confusion matrix each metric uses. Precision looks at everything predicted positive; recall looks at everything actually positive.

Hint 2

TN never appears in either formula, so you can ignore it.

Hint 3

Check each denominator before dividing, and return 0.0 for that metric alone when it is zero.