4/31
Part 1 of 6 · DCGLearn

DCG is the sum of gain over discount for the top k

Put the two together, and you have DCG.

RankGradeGainDiscountGain / discount
1371.007.00
2111.580.63
3232.001.50
DCG@39.13

Take three results with grades 3, 1 and 2, in ranked order. Each row divides a gain by its rank's discount, and DCG@3 adds the rows: 9.13. At k=1k = 1 only the first row counts, so DCG@1 is 7.

In symbols:

DCG@k=∑i=1k2 reli−1log⁡2(i+1)\text{DCG@}k = \sum_{i=1}^{k} \frac{2^{\,rel_i} - 1}{\log_2(i + 1)}

In words: for each of the top kk results, divide its gain by its discount, then add them up. ii is the rank, counting from 1 at the top. relirel_i is the grade of the result at rank ii. kk is the cutoff: only the top kk results count.

In NumPy it's one line:

import numpy as np

def dcg_at_k(rels: list[int], k: int) -> float:
    """rels: grades in ranked order. The DCG of the top k, with gain 2^grade - 1."""
    r = np.asarray(rels, dtype=float)[:k]
    return float(np.sum((2 ** r - 1) / np.log2(np.arange(2, r.size + 2))))

print(round(dcg_at_k([3, 1, 2], 3), 4))
print(dcg_at_k([3, 1, 2], 1))
print(round(dcg_at_k([3, 1, 2], 5), 4))
Predict

The first two lines print the table's 9.1309 and 7.0. The list holds only 3 grades. What does the last line, at k = 5, print?

Pick one to see what it prints.
Pick an answer above to see the rest