The idea
Average precision summarises a ranking by walking down the scores from highest to lowest and asking, each time more positives are found, how precise the list is so far. Each step is weighted by the share of all positives it adds, so the result is the area under the precision-recall curve drawn as steps.
Tied scores cannot be put in order, so average_precision(labels, scores) treats each distinct score as one threshold. It groups the labels by score, visits the groups in descending order, updates tp and seen for a whole group at once, and adds added / total * tp / seen. Processing ties one row at a time would make the answer depend on input order.
How it works
- Validate the lists, count the positives in
total, and return 0.0 when there are none. - Group the labels by score in a dict, so every tied score forms one group.
- Visit the distinct scores from highest to lowest.
- For each group, add its positives to
tp and its size to seen. - Add
added / total * tp / seen to ap: the recall gained times the precision at this threshold. - Return
ap after the last group.
What it costs
- Time
- O(n log n)
- Space
- O(n)
Grouping is one pass over the n rows, and the sort covers only the distinct scores, so heavy ties make it cheaper.
Where it is used
- scikit-learn's
average_precision_score uses the same sum of recall gain times precision over score thresholds. - The PASCAL VOC and COCO benchmarks rank object detectors by mean average precision, computed with interpolated variants of this sum.
trec_eval, the scoring tool of the TREC retrieval conferences, reports mean average precision across queries.
Watch out for
- Stepping through tied rows one by one, which gives a different answer depending on which tied row happens to come first.
- Dividing by the number of rows instead of the number of positives when weighting each step.
- Comparing average precision across datasets with different positive rates: a random ranking scores about the positive rate, not 0.5.