Recall@k of an approximate index

mediumRetrieval~25 min · 9 tests

Approximate vector indexes are fast because they skip most of the data. The price is that sometimes they skip a true neighbour. Recall@k measures that price, and it’s the number you tune an index against.

Write recall_at_k(queries, docs, approx, k):

  • queries and docs are lists of float vectors, all the same length.
  • approx[i] is the list of doc indices an approximate index returned for queries[i], best first. It can be shorter or longer than k.
  • For each query, compute the exact top k docs by cosine similarity. Ties go to the lower index. A zero vector has similarity 0 with everything. If k > len(docs), the exact list has every doc.
  • That query’s recall is the number of exact top-k indices that appear in the first k entries of approx[i], divided by the length of the exact list.
  • Return the mean recall over all queries, as a float. With no queries, return 0.0.
>>> docs = [[1, 0], [0, 1], [1, 1]]
>>> recall_at_k([[1, 0.1]], docs, [[0, 1]], 2)   # exact top-2 is [0, 2]
0.5
Learn the ideaRead the post →
solution.pyPython 3.14 · Pyodide

Press ⌘ ↵ or Run to check the visible tests. Submit runs the hidden ones too. Everything runs in your browser.

⌘ ↵ to run