Grade a search ranking with NDCG at k

RAG and search systems are judged on whether the best documents come first. NDCG rewards relevant results near the top and divides by the best possible ordering.

Write ndcg_at_k(relevances, k) where relevances lists the graded relevance of each returned result in ranked order.
DCG@k = sum over the first k positions i (starting at 1) of (2 ** rel_i - 1) / log2(i + 1).
IDCG@k is the same for the relevances sorted from high to low. Return DCG / IDCG, or 0.0 if IDCG is 0.

Signaturedef ndcg_at_k(relevances, k)

Understand the idea

NDCG grades a ranked list by giving more credit to relevant results near the top. Each result earns gain 2^rel - 1, divided by a discount log2(position + 1), so position 1 has discount 1 and position 3 has discount 2. To put every query on a 0 to 1 scale, divide by the score of the ideal ordering (relevances sorted high to low). Worked example: relevances [0, 2, 1], k = 3. DCG = 0/1 + 3/log2(3) + 1/2 = 0 + 1.893 + 0.5 = 2.393. Ideal order [2, 1, 0]: IDCG = 3/1 + 1/1.585 + 0 = 3.631. NDCG = 2.393 / 3.631 = 0.659. If all relevances are 0, IDCG is 0, so return 0.0. Rule: DCG@k = sum over i = 1..k of (2^rel_i - 1) / log2(i + 1); NDCG = DCG / IDCG, both cut at k. An off-by-one in the position changes every score. Search engines and RAG retrievers are evaluated with NDCG.

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

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

  • Sample 1: already idealndcg_at_k([3, 2, 1, 0], 4)
  • Sample 2: best result at rank 3ndcg_at_k([0, 1, 3, 2], 3)
  • Test 3: gradedndcg_at_k([2, 0, 3, 1, 0], 5)
  • Test 4: nothing relevantndcg_at_k([0, 0], 2)