Build a precision recall curve and average precision with tied scores

Average precision summarises a ranking or a detector in one number, and it is the core of mAP in retrieval and object detection. Real scores often tie, for example rounded probabilities or a reranker that outputs a few levels. A correct curve treats tied scores as one threshold, because no threshold can separate them.

Write pr_curve(y_true, scores). y_true holds 0/1 labels, scores holds floats (higher means more likely positive). Use every distinct score as a threshold, from highest to lowest. At threshold t, everything with score >= t is predicted positive. Record precision = TP / (TP + FP) and recall = TP / (total positives) at each threshold.

Average precision is AP = sum over thresholds of (R_k - R_(k-1)) * P_k, with R_0 = 0.

Return a dict {"thresholds": [...], "precision": [...], "recall": [...], "ap": float}, with the three lists in threshold order (highest score first). If there are no positive labels, return all three lists empty and ap = 0.0.

Signaturedef pr_curve(y_true, scores)

Example

y_true = [1, 0, 1, 0], scores = [0.9, 0.5, 0.5, 0.1]. Thresholds [0.9, 0.5, 0.1], precision [1.0, 0.6667, 0.5], recall [0.5, 1.0, 1.0], ap = 0.5 * 1.0 + 0.5 * 0.6667 = 0.8333.

Understand the idea

A precision recall curve asks: if I accept everything scored at least t, how clean is the accepted set (precision) and how much of the real positives did I catch (recall)? When two items share the same score, no threshold can split them, so they must enter the accepted set together as one step. Worked example: y_true = [0, 1, 1], scores = [0.9, 0.6, 0.6]. Threshold 0.9: TP 0, FP 1, so P = 0, R = 0. Threshold 0.6: both tied items join, TP 2, FP 1, so P = 0.667, R = 1. AP = (0 - 0) * 0 + (1 - 0) * 0.667 = 0.667. Rule: walk the distinct scores from high to low, keep running TP and FP, record P = TP / (TP + FP) and R = TP / total positives, then AP = sum of (R_k - R_(k-1)) * P_k with R_0 = 0. With no positives, return empty lists and AP 0. Average precision is the building block of mAP in search ranking and object detection.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplepr_curve([1, 0, 1, 0], [0.9, 0.5, 0.5, 0.1])
  • Sample 2: rounded scorespr_curve(_y, _s)