Compute mean average precision at k
Why it matters Feed and search ranking offline evals report MAP or NDCG at k.
MAP at k rewards putting relevant items early, not just including them.
Write map_at_k(ranked, relevant, k). For each user, AP@k = (1 / min(len(relevant), k)) * sum over positions i (1-based, i <= k) where ranked[i] is relevant of precision@i. A user with no relevant items scores 0. Return the mean over users.
def map_at_k(ranked, relevant, k)Example
ranked [[1, 2, 3]], relevant [{1, 3}], k 3: hits at 1 and 3, AP = (1/1 + 2/3) / 2 = 0.8333.
Understand the idea
Mean average precision at k rewards a ranking for putting relevant items early. For each user you look at every position in the top k that holds a relevant item and record the precision so far at that position. Average those, then average over users. Worked example: ranked [5, 2, 8, 3], relevant {2, 3}, k = 4. Position 2 is a hit, precision 1/2 = 0.5. Position 4 is a hit, precision 2/4 = 0.5. The normaliser is min(2, 4) = 2, so AP = (0.5 + 0.5) / 2 = 0.5. With k = 2, only position 2 counts: AP = 0.5 / min(2, 2) = 0.25. Rule: AP@k = (1 / min(|relevant|, k)) * sum over 1-based positions i <= k with a relevant item of (hits so far / i). A user with no relevant items scores 0. MAP@k is the mean of AP@k over users. Dividing by min(|relevant|, k) lets a perfect top k score 1 even when there are more relevant items than slots. Used in: offline evaluation of recommenders and search ranking.