Upload H2Retrieval_IYun.py
Browse files- H2Retrieval_IYun.py +60 -0
H2Retrieval_IYun.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# pip install pytrec-eval-terrier
|
2 |
+
import pytrec_eval
|
3 |
+
# conda install sentence-transformers -c conda-forge
|
4 |
+
from sentence_transformers import SentenceTransformer
|
5 |
+
import pandas as pd
|
6 |
+
from collections import defaultdict
|
7 |
+
import torch
|
8 |
+
from tqdm import tqdm
|
9 |
+
|
10 |
+
|
11 |
+
if torch.cuda.is_available():
|
12 |
+
device = torch.device('cuda')
|
13 |
+
else:
|
14 |
+
device = torch.device('cpu')
|
15 |
+
|
16 |
+
def load_dataset(path):
|
17 |
+
df = pd.read_parquet(path, engine="pyarrow")
|
18 |
+
return df
|
19 |
+
|
20 |
+
path = r'D:\datasets\H2Retrieval\data_sample5k'
|
21 |
+
qrels_pd = load_dataset(path + r'\qrels.parquet.gz')
|
22 |
+
corpus = load_dataset(path + r'\corpus.parquet.gz')
|
23 |
+
queries = load_dataset(path + r'\queries.parquet.gz')
|
24 |
+
|
25 |
+
qrels = defaultdict(dict)
|
26 |
+
for i, e in qrels_pd.iterrows():
|
27 |
+
qrels[e['qid']][e['cid']] = e['score']
|
28 |
+
|
29 |
+
model = SentenceTransformer(r'D:\models\IYun', device='cuda:0')
|
30 |
+
|
31 |
+
corpusEmbeds = model.encode(corpus['text'].values, normalize_embeddings=True, show_progress_bar=True, batch_size=24)
|
32 |
+
queriesEmbeds = model.encode(queries['text'].values, normalize_embeddings=True, show_progress_bar=True, batch_size=24)
|
33 |
+
|
34 |
+
queriesEmbeds = torch.tensor(queriesEmbeds, device=device)
|
35 |
+
corpusEmbeds = corpusEmbeds.T
|
36 |
+
corpusEmbeds = torch.tensor(corpusEmbeds, device=device)
|
37 |
+
|
38 |
+
def getTopK(corpusEmbeds, qEmbeds, k=10):
|
39 |
+
scores = qEmbeds @ corpusEmbeds
|
40 |
+
top_k_indices = torch.argsort(scores, descending=True)[:k]
|
41 |
+
scores = scores.cpu()
|
42 |
+
top_k_indices = top_k_indices.cpu()
|
43 |
+
retn = {}
|
44 |
+
for x in top_k_indices:
|
45 |
+
x = int(x)
|
46 |
+
retn[corpus['cid'][x]] = float(scores[x])
|
47 |
+
return retn
|
48 |
+
|
49 |
+
results = {}
|
50 |
+
for i in tqdm(range(len(queries)), desc="Converting"):
|
51 |
+
results[queries['qid'][i]] = getTopK(corpusEmbeds, queriesEmbeds[i])
|
52 |
+
|
53 |
+
evaluator = pytrec_eval.RelevanceEvaluator(qrels, {'ndcg'})
|
54 |
+
tmp = evaluator.evaluate(results)
|
55 |
+
ndcg = 0
|
56 |
+
for x in tmp.values():
|
57 |
+
ndcg += x['ndcg']
|
58 |
+
ndcg /= len(queries)
|
59 |
+
|
60 |
+
print(f'ndcg_10: {ndcg*100:.2f}%')
|