Practice in Lab: Compute average precision at tied score boundaries →
Compute average precision at tied score boundaries
Precision-recall metrics expose failure under class imbalance that accuracy can hide. Average precision weights each precision value by the increase in recall at a score threshold. It is not the trapezoidal area obtained by linearly interpolating precision between thresholds.
Rows with equal scores must enter together. Breaking ties by input order can produce different metrics for the same model predictions. The contract returns zero for no positive labels, a deliberate reporting convention that should accompany the metric. It rejects invalid labels and mismatched lengths rather than silently truncating pairs.
labels=[1,0,1]
precision_at_positive=[1,2/3]
print(sum(precision_at_positive)/sum(labels))Review the design
Average precision depends on prevalence and the evaluation population. Compare models on the same test population and retain class counts; a number alone does not establish business value.
Your task
Implement average_precision(labels,scores). Group equal scores descending, accumulate TP and seen count, and sum (new positives/total positives)*precision at each group. Return 0 with no positives; validate nonempty equal lengths, binary labels and finite scores.
The explanation opens here once every check passes.