Build an auditable precision–recall staircase from held-out scores, then read average precision against the actual event rate.
Precision–recall curves: preserve threshold ties and class prevalence
Start with the decision population
A precision–recall curve describes a ranked binary score across possible alert thresholds. Precision is true alerts divided by all alerts; recall is true alerts divided by all actual events. They answer different questions. If a maintenance team can inspect 47 machines per shift, the useful region may be the high-precision, low-recall end, while a safety review may tolerate many inspections to find nearly every fault. Define the event, prediction timestamp, outcome window, eligible population and positive class before plotting. Probability calibration answers whether a score of 0.30 corresponds to about 30% observed risk; a precision–recall curve asks how selected alerts trade false alarms for captured events. A ranking can be useful and still be poorly calibrated.
Sweep tied scores as one threshold
Sort records by decreasing score. At each distinct score, include all records with that score before measuring precision and recall. Splitting tied cases in arbitrary input order invents operating points that no threshold can achieve. Add a no-alert endpoint at recall zero and precision one only as a plotting convention: it does not mean the model has already found an event. At the opposite end, all eligible records are selected and precision equals the cohort event rate. The stepwise curve must retain its actual points; smoothing or interpolating precision can imply a threshold that never existed. An empirical CDF uses a similar idea of preserving observed steps rather than drawing a continuous story through discrete decisions.
Interpret area and baseline carefully
Average precision weights precision at each achieved recall increment. It is not always the same number as trapezoidal area under a line interpolated between curve points, and neither is classification accuracy. The event prevalence is a useful no-skill reference when scores are independent of labels; if prevalence changes from one plant to another, the apparent precision of the same ranking can change too. Put both event count and total eligible count beside every panel. Compare models on the same untouched evaluation cohort, outcome definition and time window. Shared small-multiple scales stop separate panels from hiding the difficult low-recall region. When costs matter, also show the selected operating threshold and its alert volume rather than publishing only a scalar summary.
Expose uncertainty and selection limits
Few positives produce large stair steps: one additional true event can move recall markedly. Bootstrap or another justified interval method may describe sampling uncertainty, but resample at the correct independent unit, such as machine or customer, when multiple records belong to one unit. Delayed outcomes, unreviewed alerts and selectively labeled negatives can bias the curve; an apparent negative is not a confirmed one merely because a record is old. Small-sample uncertainty and provisional periods need explicit treatment. A companion table should give threshold, true positives, false positives, precision, recall and selected count at a few operationally relevant cuts.
Worked contract
def precision_recall_steps(records: list[tuple[str, float, bool]]):
from math import isfinite
identifiers = [record_id for record_id, _, _ in records]
if len(identifiers) != len(set(identifiers)) or any(not key for key in identifiers):
raise ValueError("record identifiers must be unique and nonempty")
if any(not isfinite(score) or type(event) is not bool
for _, score, event in records):
raise ValueError("finite scores and boolean labels are required")
positives = sum(event for _, _, event in records)
if positives == 0:
raise ValueError("recall requires at least one positive")
ranked = sorted(records, key=lambda item: item[1], reverse=True)
points = []
true_positives = false_positives = cursor = 0
while cursor < len(ranked):
threshold = ranked[cursor][1]
while cursor < len(ranked) and ranked[cursor][1] == threshold:
true_positives += ranked[cursor][2]
false_positives += not ranked[cursor][2]
cursor += 1
selected = true_positives + false_positives
points.append((threshold, true_positives / selected,
true_positives / positives, selected))
average_precision = sum(
precision * (recall - (points[index - 1][2] if index else 0))
for index, (_, precision, recall, _) in enumerate(points))
return points, average_precision, positives / len(records)
inspection_scores = [("press-47", 0.91, True),
("press-59", 0.73, False),
("press-83", 0.73, True),
("press-97", 0.22, False)]
steps, average_precision, prevalence = precision_recall_steps(inspection_scores)
assert len(steps) == 3
assert steps[1] == (0.73, 2 / 3, 1.0, 3)
assert abs(average_precision - 5 / 6) < 1e-12
assert prevalence == 0.5Performance and operating cost
Sorting N records takes O(N log N) time. The threshold sweep is O(N), while the sorted copy and output need O(N) space; unique-ID validation also needs O(N) space. The sample's average precision is 5/6 because recall rises first by one half at precision one and then by one half at precision two thirds. Four records demonstrate arithmetic and tie handling, not a credible model comparison. The function assumes labels are complete and the evaluation cohort has already been held out.
Common Mistakes
- Breaking equal scores in row order and presenting unreachable thresholds.
- Calling trapezoidal interpolation average precision without defining the calculation.
- Comparing curves built from cohorts with different prevalence or outcome windows.
- Reading the no-alert plotting endpoint as measured model performance.
Validation drill
Evaluate 470 held-out inspection scores with 59 confirmed events. Print every attainable tied-score threshold, mark the 47-alert operating point, and compare its event capture with the full curve.
Read next
- Probability calibration plots: compare predicted risk with observed frequency
- Uncertainty on charts: show denominators and intervals beside estimates
- Small multiples: compare groups with honest scales and facet order
- Time-series charts: distinguish missing days, zeros and provisional periods
