Mean Average Precision: Every Class Counts

Metrics & EvaluationMedium+15 XP+15

Mean Average Precision: Every Class Counts

Average precision scores one ranking. An object detector produces one ranking per class — all its "dog" boxes ranked by confidence, all its "car" boxes, and so on — and you need a single number for the whole detector.

mAP is the plainest possible answer: compute average precision for each class separately, then take the mean of those scores.

Task: write mean_average_precision(y_true_per_class, scores_per_class) returning that mean, rounded to 4 decimal places.

  • Both arguments are lists of lists, one entry per class, lined up with each other. y_true_per_class[2] and scores_per_class[2] describe the same class.
  • For each class, rank its predictions by score (highest first) and average the precision measured at each real positive — exactly the average-precision recipe.
  • Then average across classes, giving every class equal weight no matter how many predictions it had.
  • Every class has at least one positive.

That last rule is the one worth remembering. A class with three examples counts as much as a class with three thousand, so a detector that nails the common classes and ignores a rare one cannot hide behind its own data volume.

Examples

y_true_per_class = [[1, 0, 1], [0, 1, 1]]
scores_per_class = [[0.9, 0.5, 0.4], [0.9, 0.8, 0.1]]
returns 0.7083
y_true_per_class = [[1, 1], [1, 0]]
scores_per_class = [[0.9, 0.8], [0.2, 0.7]]
returns 0.75

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run