Mean Reciprocal Rank for Retrieval
Problem Statement
Report the Mean Reciprocal Rank (MRR) of a batch of retrieval queries: the average of 1/rank where rank is the 1-based position of the first correct hit in each query's ranked result list.
Background
For a query whose correct item first appears at rank r (1-indexed), the reciprocal rank is 1/r; if the correct item never appears, the reciprocal rank is 0. MRR averages this over all queries:
MRR rewards putting the right answer near the top, unlike Recall@K which only checks membership.
Your Task
Implement:
def mean_reciprocal_rank(rankings, relevant):
- rankings[q]: the ranked list of retrieved item ids for query q (best first).
- relevant[q]: the single correct item id for query q.
Return the MRR as a float rounded to 4 decimals.
Input Format
- rankings: list of lists of ids.
- relevant: list of ids, one per query.
Output Format
- A float rounded to 4 decimals.
Sample
print(mean_reciprocal_rank([[3, 1, 2], [0, 5, 4]], [1, 4]))
Output:
0.4167
Example
print(mean_reciprocal_rank([[3, 1, 2], [0, 5, 4]], [1, 4]))
0.4167
Query 0: correct id 1 is at rank 2 -> 0.5. Query 1: correct id 4 is at rank 3 -> 0.3333. Mean = (0.5+0.3333)/2 = 0.4167.
Constraints
len(rankings) == len(relevant),1 <= Q <= 5000.- Rank is 1-based; a missing correct item contributes 0.
- Round to 4 decimals.