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.
| Rank | Grade | Gain | Discount | Gain / discount |
|---|---|---|---|---|
| 1 | 3 | 7 | 1.00 | 7.00 |
| 2 | 1 | 1 | 1.58 | 0.63 |
| 3 | 2 | 3 | 2.00 | 1.50 |
| DCG@3 | 9.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 only the first row counts, so DCG@1 is 7.
In symbols:
In words: for each of the top results, divide its gain by its discount, then add them up. is the rank, counting from 1 at the top. is the grade of the result at rank . is the cutoff: only the top 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))
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