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
| index | label | prediction | cell |
|---|---|---|---|
| 0 | 1 | 1 | TP |
| 1 | 0 | 1 | FP |
| 2 | 1 | 0 | FN |
| 3 | 0 | 0 | TN |
- labels
- [1,0,1,0]
- predictions
- [1,1,0,0]
- masks
- (label==1)&(prediction==1) = true
| index | label | prediction | cell |
|---|---|---|---|
| 0 | 1 | 1 | TP |
| 1 | 0 | 1 | FP |
| 2 | 1 | 0 | FN |
| 3 | 0 | 0 | TN |
- masks
- (label==1)&(prediction==1) = true→(label==0)&(prediction==1) = true
- counts
- TP=1 FP=0 FN=0→TP=1 FP=1 FN=0
| index | label | prediction | cell |
|---|---|---|---|
| 0 | 1 | 1 | TP |
| 1 | 0 | 1 | FP |
| 2 | 1 | 0 | FN |
| 3 | 0 | 0 | TN |
- masks
- (label==0)&(prediction==1) = true→(label==1)&(prediction==0) = true
- counts
- TP=1 FP=1 FN=0→TP=1 FP=1 FN=1
| index | label | prediction | cell |
|---|---|---|---|
| 0 | 1 | 1 | TP |
| 1 | 0 | 1 | FP |
| 2 | 1 | 0 | FN |
| 3 | 0 | 0 | TN |
- masks
- (label==1)&(prediction==0) = true→TP=false, FP=false, FN=false
| metric | numerator | denominator meaning | total |
|---|---|---|---|
| precision | TP=1 | TP+FP | 2 |
| recall | TP=1 | TP+FN | 2 |
- arithmetic
- not shown→precision_total=2; recall_total=2
- labels
- [1,0,1,0]→not shown
- predictions
- [1,1,0,0]→not shown
| metric | guard | division | value |
|---|---|---|---|
| precision | 2 != 0 | 1 / 2 | 0.5 |
| recall | 2 != 0 | 1 / 2 | 0.5 |
- safe division
- not shown→use 0.0 only when its denominator is zero
- result
- not shown→{"precision":0.5,"recall":0.5}
- arithmetic
- precision_total=2; recall_total=2→not shown
- 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.
Reference drawing
Problem trace
Precision counts predicted positives; recall counts actual positives
Execution trace
| index | label | prediction | cell |
|---|---|---|---|
| 0 | 1 | 1 | TP |
| 1 | 0 | 1 | FP |
| 2 | 1 | 0 | FN |
| 3 | 0 | 0 | TN |
- labels
- [1,0,1,0]
- predictions
- [1,1,0,0]
- masks
- (label==1)&(prediction==1) = true
| index | label | prediction | cell |
|---|---|---|---|
| 0 | 1 | 1 | TP |
| 1 | 0 | 1 | FP |
| 2 | 1 | 0 | FN |
| 3 | 0 | 0 | TN |
- masks
- (label==1)&(prediction==1) = true→(label==0)&(prediction==1) = true
- counts
- TP=1 FP=0 FN=0→TP=1 FP=1 FN=0
| index | label | prediction | cell |
|---|---|---|---|
| 0 | 1 | 1 | TP |
| 1 | 0 | 1 | FP |
| 2 | 1 | 0 | FN |
| 3 | 0 | 0 | TN |
- masks
- (label==0)&(prediction==1) = true→(label==1)&(prediction==0) = true
- counts
- TP=1 FP=1 FN=0→TP=1 FP=1 FN=1
| index | label | prediction | cell |
|---|---|---|---|
| 0 | 1 | 1 | TP |
| 1 | 0 | 1 | FP |
| 2 | 1 | 0 | FN |
| 3 | 0 | 0 | TN |
- masks
- (label==1)&(prediction==0) = true→TP=false, FP=false, FN=false
| metric | numerator | denominator meaning | total |
|---|---|---|---|
| precision | TP=1 | TP+FP | 2 |
| recall | TP=1 | TP+FN | 2 |
- arithmetic
- not shown→precision_total=2; recall_total=2
- labels
- [1,0,1,0]→not shown
- predictions
- [1,1,0,0]→not shown
| metric | guard | division | value |
|---|---|---|---|
| precision | 2 != 0 | 1 / 2 | 0.5 |
| recall | 2 != 0 | 1 / 2 | 0.5 |
- safe division
- not shown→use 0.0 only when its denominator is zero
- result
- not shown→{"precision":0.5,"recall":0.5}
- arithmetic
- precision_total=2; recall_total=2→not shown
- 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.
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.