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.
def 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.