Suppose a ticket classifier ranks tickets for manual review. At one threshold it finds the most urgent ticket, but lowering the threshold admits another urgent ticket and a routine one with exactly the same score. A threshold cannot separate those two tickets. If your metric counts them one at a time, changing their input order can make the classifier look better or worse without changing any prediction.
Calculate at distinct thresholds
Use Python 3 with its standard library. Save the following as ap.py. Each row is a pair of numeric score and integer label. Higher scores indicate stronger evidence for the positive label. The example uses exact fractions for the metric so that the tests check the result directly instead of relying on a rounding tolerance.
from fractions import Fraction
from itertools import groupby
from math import isfinite
def average_precision(rows):
rows = list(rows)
if any(type(y) is not int or y not in (0, 1) or not isfinite(s)
for s, y in rows):
raise ValueError("need finite scores and integer binary labels")
positives = sum(y for _, y in rows)
if not positives:
raise ValueError("no positives")
ranked = sorted(rows, key=lambda row: row[0], reverse=True)
seen = hits = 0
area = Fraction(0)
for _, group in groupby(ranked, key=lambda row: row[0]):
gained = 0
for _, y in group:
seen += 1
gained += y
hits += gained
area += Fraction(gained, positives) * Fraction(hits, seen)
return area
rows = [(0.9, 1), (0.8, 0), (0.8, 1), (0.1, 0)]
score = average_precision(rows)
assert score == Fraction(5, 6) == average_precision(reversed(rows))
assert average_precision([(3, 1), (3, 0)]) == Fraction(1, 2)
for bad in ([], [(1, 0)], [(float("nan"), 1)]):
try:
average_precision(bad)
except ValueError:
continue
raise AssertionError("invalid fixture accepted")
print(score)Run python3 ap.py. Expected output:
5/6Read the score by hand
At 0.9 the first positive contributes a recall increase of 1/2 at precision 1. At 0.8 both tied rows enter together. Recall increases by another 1/2 and precision becomes 2/3. The final negative does not increase recall and contributes nothing. The sum is 1/2 + 1/3. This is the non-interpolated definition, not the trapezoidal area under a line joining precision-recall points.
If every row has the same score, there is only one useful threshold and the result is simply the positive fraction. If there are no positives, this example raises an error so the caller can report that the evaluation window is unscorable. A library may use a different convention for that case. An empty window and a measured low score should not be stored as the same result.
Troubleshoot differences
When comparing two reports, check the positive label, score direction, and whether one pipeline rounded scores before computing the metric. The code groups exact score equality. If production emits rounded scores, evaluate those as a deliberate deployment contract rather than rounding only the exported report. Average precision summarizes a ranking across thresholds. To choose a review threshold, inspect precision and recall at the actual review capacity separately.
Primary reference and related tutorials: scikit-learn average precision definition · Java Samples AI tutorials.