Compute mean reciprocal rank

Why it matters Retrieval evals for RAG pipelines report MRR next to recall at k.

For search and RAG retrieval, MRR asks how high the first relevant result appears.

Write mrr(ranked, relevant). ranked is a list of result lists, relevant is a list of sets of relevant ids. For each query score 1 / rank of the first relevant item (rank starts at 1), or 0 if none appears. Return the mean.

Signaturedef mrr(ranked, relevant)

Example

mrr([["a", "b"], ["c", "d"]], [{"b"}, {"x"}]) is (0.5 + 0) / 2 = 0.25.

Understand the idea

Mean reciprocal rank asks one question per query: how far down the list was the first useful result? Finding it at position 1 scores 1, position 2 scores 1/2, position 3 scores 1/3, and never finding it scores 0. Later relevant items do not matter. Worked example with three queries: the first relevant result is at rank 1 for query A, at rank 3 for query B, and missing for query C. The scores are 1, 1/3 and 0, so MRR = (1 + 0.3333 + 0) / 3 = about 0.4444. Rule: for each query, walk the ranked list with rank starting at 1, stop at the first id found in that query's relevant set and score 1 / rank, or 0 if none appears; return the mean over all queries. Make sure you stop after the first hit; adding 1 / rank for every relevant item gives a different metric. Used in: evaluating search engines, RAG retrievers and question answering, where the user mostly reads the top result.

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

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplemrr([['a', 'b'], ['c', 'd']], [{'b'}, {'x'}])
  • Sample 2: first hitmrr([[1, 2, 3]], [{1, 3}])
  • Test 3: mixedmrr([[5, 4, 3], [9, 8], [1]], [{3}, {8, 9}, {2}])