| import numpy as np |
| import pandas as pd |
| from tqdm import tqdm |
|
|
|
|
| def dcg(scores): |
| log2_i = np.log2(np.arange(2, len(scores) + 2)) |
| return np.sum(scores / log2_i) |
|
|
|
|
| def idcg(rels, topk): |
| return dcg(np.sort(rels)[::-1][:topk]) |
|
|
|
|
| def odcg(rels, predictions): |
| indices = np.argsort(predictions)[::-1] |
| return dcg(rels[indices]) |
|
|
|
|
| def _ndcg(drels, dpredictions): |
| topk = len(dpredictions) |
| _idcg = idcg(np.array(drels['score']), topk) |
| tmp = drels[drels.index.isin(dpredictions.index)] |
| rels = dpredictions['score'].copy() |
| rels *= 0 |
| rels.update(tmp['score']) |
| _odcg = odcg(rels.values, dpredictions['score'].values) |
| return float(_odcg / _idcg) |
|
|
|
|
| def ndcg(qrels, results): |
| drels = qrels.set_index('cid', inplace=False) |
| dpredictions = results.set_index('cid', inplace=False) |
| |
| return _ndcg(drels, dpredictions) |
|
|
|
|
| def ndcg_in_all(qrels, results): |
| retn = {} |
| _qrels = {qid: group for qid, group in qrels.groupby('qid')} |
| _results = {qid: group for qid, group in results.groupby('qid')} |
| for qid in tqdm(_results, desc="计算 ndcg 中..."): |
| retn[qid] = ndcg(_qrels[qid], _results[qid]) |
| return retn |
|
|
|
|
| if __name__ == '__main__': |
| qrels = pd.DataFrame( |
| [ |
| ['q1', 'd1', 1], |
| ['q1', 'd2', 2], |
| ['q1', 'd3', 3], |
| ['q1', 'd4', 4], |
| ['q2', 'd1', 2], |
| ['q2', 'd2', 1] |
| ], |
| columns=['qid', 'cid', 'score'] |
| ) |
|
|
| results = pd.DataFrame( |
| [ |
| ['q1', 'd2', 1], |
| ['q1', 'd3', 2], |
| ['q1', 'd4', 3], |
| ['q2', 'd2', 1], |
| ['q2', 'd3', 2], |
| ['q2', 'd5', 2] |
| ], |
| columns=['qid', 'cid', 'score'] |
| ) |
| print(ndcg_in_all(qrels, results)) |
|
|