Datasets:

Modalities:
Text
Formats:
parquet
Languages:
French
ArXiv:
Libraries:
Datasets
pandas
License:
mciancone commited on
Commit
e40c8a6
1 Parent(s): 1cff9a2

Upload create_data_reranking.py

Browse files
Files changed (1) hide show
  1. create_data_reranking.py +82 -0
create_data_reranking.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datasets
2
+ from sentence_transformers import SentenceTransformer, util
3
+ import torch
4
+ from huggingface_hub import create_repo
5
+ from huggingface_hub.utils._errors import HfHubHTTPError
6
+
7
+ """
8
+ To create a reranking dataset from the initial retrieval dataset,
9
+ we use a model (sentence-transformers/all-MiniLM-L6-v2) to embed the queries and the documents.
10
+ We then compute the cosine similarity for each query and document.
11
+ For each query we get the topk articles, as we would for a retrieval task.
12
+ Each couple query-document is labeled as relevant if it was labeled like so in the retrieval dataset,
13
+ or irrelevant if it was not
14
+ """
15
+ # Download the documents (corpus)
16
+ corpus_raw = datasets.load_dataset("lyon-nlp/alloprof", "documents")
17
+ # Download the queries
18
+ queries_raw = datasets.load_dataset("lyon-nlp/alloprof", "queries")
19
+ # Get the model
20
+ model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
21
+
22
+ # Generate document text (title + content)
23
+ corpus = corpus_raw.map(lambda x: {"text": x["title"] + "\n\n" + x["text"]})
24
+ # Embed documents and queries
25
+ corpus = corpus.map(lambda x: {"embeddings": model.encode(x['text'])}, batched=True)
26
+ queries = queries_raw.map(lambda x: {"embeddings": model.encode(x["text"])}, batched=True)
27
+
28
+ # change document uuid with integer id
29
+ doc_name_id_mapping = {doc["uuid"]: i for i, doc in enumerate(corpus["documents"])}
30
+ corpus = corpus.map(lambda x: {"uuid" : doc_name_id_mapping[x["uuid"]]})
31
+ queries = queries.map(lambda x: {"relevant": [doc_name_id_mapping[r] for r in x["relevant"]]})
32
+
33
+ # Retrieve best documents by cosine similarity
34
+ def retrieve_documents(queries_embs, documents_embs, topk:int=10) -> torch.return_types.topk:
35
+ """Finds the topk documents for each embed query among all the embed documents
36
+
37
+ Args:
38
+ queries_embs (_type_): the embedings of all queries of the dataset (dataset["queries"]["embeddings"])
39
+ documents_embs (_type_): the embedings of all coprus of the dataset (dataset["corpus"]["embeddings"])
40
+ topk (int, optional): The amount of top documents to retrieve. Defaults to 5.
41
+
42
+ Returns:
43
+ torch.return_types.topk : The topk object, with topk.values being the cosine similarities
44
+ and the topk.indices being the indices of best documents for each queries
45
+ """
46
+ similarities = util.cos_sim(queries_embs, documents_embs)
47
+ tops = torch.topk(similarities, k=topk, axis=1)
48
+
49
+ return tops
50
+
51
+ top_docs_train = retrieve_documents(queries["train"]["embeddings"], corpus["documents"]["embeddings"])
52
+ top_docs_test = retrieve_documents(queries["test"]["embeddings"], corpus["documents"]["embeddings"])
53
+ queries["train"] = queries["train"].map(
54
+ lambda _, i: {"top_cosim_values": top_docs_train.values[i], "top_cosim_indexes": top_docs_train.indices[i]},
55
+ with_indices=True
56
+ )
57
+ queries["test"] = queries["test"].map(
58
+ lambda _, i: {"top_cosim_values": top_docs_test.values[i], "top_cosim_indexes": top_docs_test.indices[i]},
59
+ with_indices=True
60
+ )
61
+
62
+ # Remove id in best_indices if it corresponds to ground truth a relevant document
63
+ queries = queries.map(lambda x : {"top_cosim_indexes": [i for i in x["top_cosim_indexes"] if i not in x["relevant"]]})
64
+ # Convert document ids to document texts based on the corpus
65
+ queries = queries.map(lambda x: {"negative": [corpus["documents"][i]["text"] for i in x["top_cosim_indexes"]]})
66
+ queries = queries.map(lambda x: {"positive": [corpus["documents"][i]["text"] for i in x["relevant"]]})
67
+
68
+ # Format as the MTEB format
69
+ queries = queries.rename_column("text", "query")
70
+ dataset = queries.remove_columns(['embeddings', 'relevant', 'top_cosim_values', 'top_cosim_indexes', 'answer', 'subject', "id"])
71
+ # Rename the key of dataset key as "test"
72
+ # dataset["test"] = dataset.pop("queries")
73
+
74
+ # create HF repo
75
+ repo_id = "lyon-nlp/mteb-fr-reranking-alloprof-s2p"
76
+ try:
77
+ create_repo(repo_id, repo_type="dataset")
78
+ except HfHubHTTPError as e:
79
+ print("HF repo already exist")
80
+
81
+ # save dataset as json
82
+ dataset.push_to_hub(repo_id)