Metrics ยท Medium
NDCG
Normalize discounted gain against the best possible ranking.
Task
Implement ndcg(relevance: list[float], scores: list[float], k: int) -> float. Rank examples by descending score, compute discounted cumulative gain through rank k, and normalize it by the ideal ranking of the same relevance labels.
Requirements
- Use gain 2^relevance - 1 and discount log2(rank + 1), with ranks starting at 1.
- Return 0.0 when k <= 0 or the ideal DCG is zero.
- When k exceeds the dataset size, use every example.
- Preserve original input order when scores tie.
Example
relevance = [3, 2, 0, 1]
scores = [0.8, 0.9, 0.7, 0.6]
ndcg(relevance, scores, 3)
# 0.7895959410