Skip to content
mlmentorship

Binary Precision and Recall

Compute precision and recall from binary labels and predictions.

Published · 17 min read ·Role-specific ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Binary Precision and Recall

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. Equal-length one-dimensional arrays labels and predictions, containing only 0 and 1, or Booleans. Output. Return a dictionary with floating-point precision and recall values. Precision is the fraction of predicted positives that are truly positive. Recall is the fraction of actual positives predicted positive. Rules. Label 1 is the positive class, and corresponding positions describe the same observation. Report 0.0 for a metric with a zero denominator, including empty inputs. Other shapes and labels are outside this contract. Preserve both arrays. Example. Labels [1, 0, 1] and predictions [1, 1, 0] return {"precision": 0.5, "recall": 0.5}. One of two positive predictions is correct; one of two actual positives is recovered.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Build TP, FP, and FN with elementwise Boolean masks, then divide TP by predicted-positive and actual-positive totals with zero-denominator guards.

Problem trace

Precision counts predicted positives; recall counts actual positives

Worked example: one hit count has two denominatorsRecall selects the actual positives and asks how many were found. Precision selects the predicted positives and asks how many were correct. Both selections contain the same eight hits, but their extra members differ. Misses lower recall; false alarms lower precision.Same cases. Same hits. Differentgroups.Actual +8 of 1080%Predicted +8 of 4020%8 green hits survive both selectionsChanging the denominator changes thequestion
Read it this way: Recall selects the actual positives and asks how many were found. Precision selects the predicted positives and asks how many were correct. Both selections contain the same eight hits, but their extra members differ. Misses lower recall; false alarms lower precision. Which thirty-two cases enter the precision denominator but not the recall denominator?
Full interview answer 17 min read
Reading depth

Report how often positive predictions are correct and how many actual positives the predictions recover.

Problem

Input. Equal-length one-dimensional arrays labels and predictions, containing only 0 and 1, or Booleans.

Output. Return a dictionary with floating-point precision and recall values. Precision is the fraction of predicted positives that are truly positive. Recall is the fraction of actual positives predicted positive.

Rules. Label 1 is the positive class, and corresponding positions describe the same observation. Report 0.0 for a metric with a zero denominator, including empty inputs. Other shapes and labels are outside this contract. Preserve both arrays.

Example. Labels [1, 0, 1] and predictions [1, 1, 0] return {"precision": 0.5, "recall": 0.5}. One of two positive predictions is correct; one of two actual positives is recovered.

Picture

For labels [1,0,1] and predictions [1,1,0], counts are TP=1, FP=1, FN=1. Both rates equal 1/2.

Problem trace

Separate coded fixture: Boolean masks construct the two denominators

Input and goalCompute precision and recall from binary labels and predictions.
Classify index 0 as true positiveBoth label and prediction equal one. TP increases from zero to one.
indexlabelpredictioncell
011TP
101FP
210FN
300TN
labels[1,0,1,0]predictions[1,1,0,0]masks(label==1)&(prediction==1) = truecountsTP=1 FP=0 FN=0
labels
[1,0,1,0]
predictions
[1,1,0,0]
masks
(label==1)&(prediction==1) = true

Recognize it
Use these masks when binary labels and predictions must be reduced into precision and recall, whose denominators answer different conditional questions.
Keep true
After each index, TP, FP, and FN equal the counts of their Boolean conjunctions over the processed prefix; TN affects neither precision nor recall numerator or denominator.
Reuse it
Define classification metrics as Boolean event counts first, then name each denominator population and guard empty populations before division.
Both label and prediction equal one. TP increases from zero to one. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Which two rows enter each denominator even though both final ratios happen to equal 0.5?
Reference drawing

Problem trace

Precision counts predicted positives; recall counts actual positives

Worked example: one hit count has two denominatorsRecall selects the actual positives and asks how many were found. Precision selects the predicted positives and asks how many were correct. Both selections contain the same eight hits, but their extra members differ. Misses lower recall; false alarms lower precision.Same cases. Same hits. Differentgroups.Actual +8 of 1080%Predicted +8 of 4020%8 green hits survive both selectionsChanging the denominator changes thequestion
Execution trace
Input and goalCompute precision and recall from binary labels and predictions.
Classify index 0 as true positiveBoth label and prediction equal one. TP increases from zero to one.
indexlabelpredictioncell
011TP
101FP
210FN
300TN
labels[1,0,1,0]predictions[1,1,0,0]masks(label==1)&(prediction==1) = truecountsTP=1 FP=0 FN=0
labels
[1,0,1,0]
predictions
[1,1,0,0]
masks
(label==1)&(prediction==1) = true

Recognize it
Use these masks when binary labels and predictions must be reduced into precision and recall, whose denominators answer different conditional questions.
Keep true
After each index, TP, FP, and FN equal the counts of their Boolean conjunctions over the processed prefix; TN affects neither precision nor recall numerator or denominator.
Reuse it
Define classification metrics as Boolean event counts first, then name each denominator population and guard empty populations before division.
Both label and prediction equal one. TP increases from zero to one. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Which two rows enter each denominator even though both final ratios happen to equal 0.5?
Read it this way: Recall selects the actual positives and asks how many were found. Precision selects the predicted positives and asks how many were correct. Both selections contain the same eight hits, but their extra members differ. Misses lower recall; false alarms lower precision. Which thirty-two cases enter the precision denominator but not the recall denominator?

The confusion-count lesson explains these different denominator populations. Count first; averaging separate batch rates generally changes the estimand.

Code

import numpy as np

def binary_metrics(labels: np.ndarray, predictions: np.ndarray) -> dict[str, float]:
   true_positive = int(np.sum((labels == 1) & (predictions == 1)))
   false_positive = int(np.sum((labels == 0) & (predictions == 1)))
   false_negative = int(np.sum((labels == 1) & (predictions == 0)))

   precision_total = true_positive + false_positive
   recall_total = true_positive + false_negative
   precision = true_positive / precision_total if precision_total else 0.0
   recall = true_positive / recall_total if recall_total else 0.0
   return {"precision": precision, "recall": recall}

Cost: time and temporary Boolean arrays.

Change the Requirement

Combine Batches

New task: Report one global rate over disjoint batches.

Picture and change: Sum sufficient counts before dividing.

Code: Every pair retains the binary shape contract.

def binary_metrics_batches(batches):
   true_positive = false_positive = false_negative = 0
   for labels, predictions in batches:
      true_positive += int(np.count_nonzero((labels == 1) & (predictions == 1)))
      false_positive += int(np.count_nonzero((labels == 0) & (predictions == 1)))
      false_negative += int(np.count_nonzero((labels == 1) & (predictions == 0)))
   predicted = true_positive + false_positive
   actual = true_positive + false_negative
   return {
      "precision": true_positive / predicted if predicted else 0.0,
      "recall": true_positive / actual if actual else 0.0,
   }

Check: Batches (TP,FP)=(1,0),(0,3) give precision 1/4, not the unweighted rate average 1/2.

Use when: Batches describe the same reporting population; state is constant outside each batch.

Weight Observations

New task: Give examples nonnegative finite weights with representable totals.

Picture and change: Sum weighted events, not Boolean counts.

Code: Inputs retain the binary shape contract; weights have the same shape.

def weighted_binary_metrics(labels, predictions, weights):
   weights = np.asarray(weights, dtype=np.float64)
   if labels.ndim != 1 or labels.shape != predictions.shape or labels.shape != weights.shape:
      raise ValueError("one-dimensional shapes must match")
   if np.any(~np.isfinite(weights)) or np.any(weights < 0):
      raise ValueError("weights must be finite and nonnegative")
   if not np.isfinite(weights.sum()):
      raise ValueError("weight total is not representable")
   true_positive = float(weights[(labels == 1) & (predictions == 1)].sum())
   predicted = float(weights[predictions == 1].sum())
   actual = float(weights[labels == 1].sum())
   return {
      "precision": true_positive / predicted if predicted else 0.0,
      "recall": true_positive / actual if actual else 0.0,
   }

Check: Labels [1,0], predictions [1,1], weights [1,3] give precision 1/4 and recall 1.

Use when: Weights define the intended population. Both adaptations preserve linear arithmetic cost; masks need linear batch storage.

Reconstruct

Why not equate the chosen zero-reporting policy with a mathematically defined conditional probability?

Reasoned answer

With no predicted positives, precision has a zero denominator and is undefined as a conditional rate. Returning zero is a declared display convention, not evidence that a defined population rate equals zero. Keep population support available when interpreting or comparing reported values. Weights do not repair missing labels, selection bias, or an unidentified causal comparison.