Upload build_reranking_dataset_BM25.py
Browse files- build_reranking_dataset_BM25.py +174 -0
build_reranking_dataset_BM25.py
ADDED
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from rank_bm25 import BM25Plus
|
2 |
+
import datasets
|
3 |
+
from sklearn.base import BaseEstimator
|
4 |
+
from sklearn.model_selection import GridSearchCV
|
5 |
+
|
6 |
+
from huggingface_hub import create_repo
|
7 |
+
from huggingface_hub.utils._errors import HfHubHTTPError
|
8 |
+
|
9 |
+
|
10 |
+
N_NEGATIVE_DOCS = 10
|
11 |
+
|
12 |
+
# Prepare documents
|
13 |
+
def create_text(example:dict) -> str:
|
14 |
+
return "\n".join([example["section"], example["title"], example["content"]])
|
15 |
+
|
16 |
+
documents = datasets.load_dataset("lyon-nlp/mteb-fr-retrieval-syntec-s2p", "documents")["test"]
|
17 |
+
documents = documents.add_column("text", [create_text(x) for x in documents])
|
18 |
+
documents = documents.rename_column("id", "doc_id")
|
19 |
+
documents = documents.remove_columns(["url", "title", "section", "content"])
|
20 |
+
|
21 |
+
# Prepare queries
|
22 |
+
queries = datasets.load_dataset("lyon-nlp/mteb-fr-retrieval-syntec-s2p", "queries")["test"]
|
23 |
+
queries = queries.rename_columns({"Question": "queries", "Article": "doc_id"})
|
24 |
+
queries = queries.map(lambda x: {"doc_id": [x["doc_id"]]})
|
25 |
+
|
26 |
+
# Optimize BM25 parameters
|
27 |
+
### Build sklearn estimator feature BM25
|
28 |
+
class BM25Estimator(BaseEstimator):
|
29 |
+
|
30 |
+
def __init__(self, corpus_dataset:datasets.Dataset, *, k1:float=1.5, b:float=.75, delta:int=1):
|
31 |
+
"""Initialize BM25 estimator using the coprus dataset.
|
32 |
+
The dataset must contain 2 columns:
|
33 |
+
- "doc_id" : the documents ids
|
34 |
+
- "text" : the document texts
|
35 |
+
|
36 |
+
Args:
|
37 |
+
corpus_dataset (datasets.Dataset): _description_
|
38 |
+
k1 (float, optional): _description_. Defaults to 1.5.
|
39 |
+
b (float, optional): _description_. Defaults to .75.
|
40 |
+
delta (int, optional): _description_. Defaults to 1.
|
41 |
+
"""
|
42 |
+
self.is_fitted_ = False
|
43 |
+
|
44 |
+
self.corpus_dataset = corpus_dataset
|
45 |
+
self.k1 = k1
|
46 |
+
self.b = b
|
47 |
+
self.delta=delta
|
48 |
+
self.bm25 = None
|
49 |
+
|
50 |
+
def tokenize_corpus(self, corpus:list[str]) -> list[str]:
|
51 |
+
"""Tokenize a corpus of strings
|
52 |
+
|
53 |
+
Args:
|
54 |
+
corpus (list[str]): the list of string to tokenize
|
55 |
+
|
56 |
+
Returns:
|
57 |
+
list[str]: the tokeinzed corpus
|
58 |
+
"""
|
59 |
+
if isinstance(corpus, str):
|
60 |
+
return corpus.lower().split()
|
61 |
+
|
62 |
+
return [c.lower().split() for c in corpus]
|
63 |
+
|
64 |
+
def fit(self, X=None, y=None):
|
65 |
+
"""Fits the BM25 using the dataset of documents
|
66 |
+
Args are placeholders required by sklearn
|
67 |
+
"""
|
68 |
+
tokenized_corpus = self.tokenize_corpus(self.corpus_dataset["text"])
|
69 |
+
self.bm25 = BM25Plus(
|
70 |
+
corpus=tokenized_corpus,
|
71 |
+
k1=self.k1,
|
72 |
+
b=self.b,
|
73 |
+
delta=self.delta
|
74 |
+
)
|
75 |
+
self.is_fitted_ = True
|
76 |
+
|
77 |
+
return self
|
78 |
+
|
79 |
+
def predict(self, query:str, topN:int=10) -> list[str]:
|
80 |
+
"""Returns the best doc ids in order of best relevance first
|
81 |
+
|
82 |
+
Args:
|
83 |
+
query (str): _description_
|
84 |
+
topN (int, optional): _description_. Defaults to 10.
|
85 |
+
|
86 |
+
Returns:
|
87 |
+
list[str]: _description_
|
88 |
+
"""
|
89 |
+
if not self.is_fitted_:
|
90 |
+
self.fit()
|
91 |
+
|
92 |
+
tokenized_query = self.tokenize_corpus(query)
|
93 |
+
best_docs = self.bm25.get_top_n(tokenized_query, self.corpus_dataset["text"], n=topN)
|
94 |
+
best_docs_ids = [self.corpus_dataset["doc_id"][self.corpus_dataset["text"].index(doc)] for doc in best_docs]
|
95 |
+
|
96 |
+
return best_docs_ids
|
97 |
+
|
98 |
+
def score(self, queries:list[str], relevant_docs:list[list[str]]):
|
99 |
+
"""Scores the bm25 using the queries and relevant docs,
|
100 |
+
using MRR as the metric.
|
101 |
+
|
102 |
+
Args:
|
103 |
+
queries (list[str]): list of queries
|
104 |
+
relevant_docs (list[list[str]]): list of relevant documents ids for each query
|
105 |
+
"""
|
106 |
+
best_docs_ids_preds = [self.predict(q, len(self.corpus_dataset)) for q in queries]
|
107 |
+
best_docs_isrelevant = [
|
108 |
+
[
|
109 |
+
doc in rel_docs for doc in best_docs_ids_pred
|
110 |
+
]
|
111 |
+
for best_docs_ids_pred, rel_docs in zip(best_docs_ids_preds, relevant_docs)
|
112 |
+
]
|
113 |
+
mrrs = [self._compute_mrr(preds) for preds in best_docs_isrelevant]
|
114 |
+
mrr = sum(mrrs)/len(mrrs)
|
115 |
+
|
116 |
+
return mrr
|
117 |
+
|
118 |
+
def _compute_mrr(self, predictions:list[bool]) -> float:
|
119 |
+
"""Compute the mrr considering a list of boolean predictions.
|
120 |
+
Example:
|
121 |
+
if predictions = [False, False, True, False], it would indicate
|
122 |
+
that only the third document was labeled as relevant to the query
|
123 |
+
|
124 |
+
Args:
|
125 |
+
predictions (list[bool]): the binarized relevancy of predictions
|
126 |
+
|
127 |
+
Returns:
|
128 |
+
float: the mrr
|
129 |
+
"""
|
130 |
+
if any(predictions):
|
131 |
+
mrr = [1/(i+1) for i, pred in enumerate(predictions) if pred]
|
132 |
+
mrr = sum(mrr)/len(mrr)
|
133 |
+
return mrr
|
134 |
+
else:
|
135 |
+
return 0
|
136 |
+
|
137 |
+
### Perform gridSearch to find best parameters for BM25
|
138 |
+
print("Optimizing BM25 parameters...")
|
139 |
+
|
140 |
+
params = {
|
141 |
+
"k1":[1., 1.25, 1.5, 1.75],
|
142 |
+
"b": [.5, .75, 1.],
|
143 |
+
"delta": [0, 1, 2]
|
144 |
+
}
|
145 |
+
|
146 |
+
gscv = GridSearchCV(BM25Estimator(documents), params)
|
147 |
+
gscv.fit(queries["queries"], queries["doc_id"])
|
148 |
+
|
149 |
+
print("Best parameterss :", gscv.best_params_)
|
150 |
+
print("Best MRR score :", gscv.best_score_)
|
151 |
+
|
152 |
+
|
153 |
+
# Build reranking dataset with positives and negative queries using best estimator
|
154 |
+
reranking_dataset = datasets.Dataset.from_dict(
|
155 |
+
{
|
156 |
+
"query": queries["queries"],
|
157 |
+
"positive": queries["doc_id"],
|
158 |
+
"negative": [
|
159 |
+
[doc_id for doc_id in gscv.estimator.predict(q, N_NEGATIVE_DOCS) if doc_id not in relevant_ids]
|
160 |
+
for q, relevant_ids in zip(queries["queries"], queries["doc_id"])
|
161 |
+
]
|
162 |
+
})
|
163 |
+
|
164 |
+
# Push dataset to hub
|
165 |
+
### create HF repo
|
166 |
+
repo_id = "lyon-nlp/mteb-fr-reranking-syntec-s2p"
|
167 |
+
try:
|
168 |
+
create_repo(repo_id, repo_type="dataset")
|
169 |
+
except HfHubHTTPError as e:
|
170 |
+
print("HF repo already exist")
|
171 |
+
|
172 |
+
### push to hub
|
173 |
+
reranking_dataset.push_to_hub(repo_id, config_name="queries", split="test")
|
174 |
+
documents.push_to_hub(repo_id, config_name="documents", split="test")
|