File size: 1,802 Bytes
796ec76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8ca558
796ec76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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)
    # print(drels, dpredictions)
    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))