161. 使用 NDCG@k 对搜索排名进行评分
RAG 和搜索系统的评估标准在于最佳文档是否排在前面。NDCG 会奖励排名靠前的相关结果,并除以最佳可能的排序得分。
编写 ndcg_at_k(relevances, k),其中 relevances 按排名顺序列出了每个返回结果的分级相关性。
DCG@k = 对前 k 个位置 i(从 1 开始)求和 (2 ** rel_i - 1) / log2(i + 1)。
IDCG@k 是将 relevances 从高到低排序后的相同计算结果。返回 DCG / IDCG,如果 IDCG 为 0,则返回 0.0。
def ndcg_at_k(relevances, k)示例 1
输入: relevances = [3, 2, 1, 0], k = 4
输出: 1.0
示例 2
输入: relevances = [0, 1, 3, 2], k = 3
输出: 0.439798
示例 3
输入: relevances = [2, 0, 3, 1, 0], k = 5
输出: 0.737872
约束条件
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
提示 1
NDCG is the DCG of your ranking divided by the DCG of the best possible ranking of the same relevances.
提示 2
Write a small dcg helper over the first k items, call it on the given order and on sorted(relevances, reverse=True), and divide.
提示 3
With 0-based enumerate index i, the discount is math.log2(i + 2), and you must return 0.0 when the ideal DCG is 0 to avoid dividing by zero.
常见错误
- 折扣计算中的 off-by-one 错误(如在错误版本中所示)会改变每一个得分。
理解思路
NDCG 通过给予排名靠前的相关结果更高的权重来对排序列表进行评分。每个结果获得增益 2^rel - 1,并除以折扣 log2(position + 1),因此 position 1 的折扣为 1,position 3 的折扣为 2。为了将每个查询归一化到 0 到 1 的范围内,需除以理想排序(relevances 从高到低排序)的得分。
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. 如果所有 relevances 均为 0,则 IDCG 为 0,返回 0.0。
DCG@k = sum over i = 1..k of (2^rel_i - 1) / log2(i + 1); NDCG = DCG / IDCG,两者均在 k 处截断。位置上的 off-by-one 错误会改变每一个得分。搜索引擎和 RAG 检索器通常使用 NDCG 进行评估。