Thomas De Decker commited on
Commit
5c8f45c
1 Parent(s): 0984956
README.md CHANGED
@@ -1,3 +1,259 @@
1
  ---
 
 
2
  license: mit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+
3
+ language: en
4
  license: mit
5
+ tags:
6
+ - keyphrase-extraction
7
+ datasets:
8
+ - midas/openkp
9
+ metrics:
10
+ - seqeval
11
+ widget:
12
+ - text: "Keyphrase extraction is a technique in text analysis where you extract the important keyphrases from a document.
13
+ Thanks to these keyphrases humans can understand the content of a text very quickly and easily without reading
14
+ it completely. Keyphrase extraction was first done primarily by human annotators, who read the text in detail
15
+ and then wrote down the most important keyphrases. The disadvantage is that if you work with a lot of documents,
16
+ this process can take a lot of time.
17
+
18
+ Here is where Artificial Intelligence comes in. Currently, classical machine learning methods, that use statistical
19
+ and linguistic features, are widely used for the extraction process. Now with deep learning, it is possible to capture
20
+ the semantic meaning of a text even better than these classical methods. Classical methods look at the frequency,
21
+ occurrence and order of words in the text, whereas these neural approaches can capture long-term semantic dependencies
22
+ and context of words in a text."
23
+ example_title: "Example 1"
24
+ - text: "FoodEx is the largest trade exhibition for food and drinks in Asia, with about 70,000 visitors checking out the products presented by hundreds of participating companies. I was lucky to enter as press; otherwise, visitors must be affiliated with the food industry— and pay ¥5,000 — to enter. The FoodEx menu is global, including everything from cherry beer from Germany and premium Mexican tequila to top-class French and Chinese dumplings. The event was a rare chance to try out both well-known and exotic foods and even see professionals making them. In addition to booths offering traditional Japanese favorites such as udon and maguro sashimi, there were plenty of innovative twists, such as dorayaki , a sweet snack made of two pancakes and a red-bean filling, that came in coffee and tomato flavors. While I was there I was lucky to catch the World Sushi Cup Japan 2013, where top chefs from around the world were competing … and presenting a wide range of styles that you would not normally see in Japan, like the flower makizushi above."
25
+ example_title: "Example 2"
26
+ model-index:
27
+ - name: ml6team/keyphrase-extraction-kbir-openkp
28
+ results:
29
+ - task:
30
+ type: keyphrase-extraction
31
+ name: Keyphrase Extraction
32
+ dataset:
33
+ type: midas/openkp
34
+ name: openkp
35
+ metrics:
36
+ - type: F1 (Seqeval)
37
+ value: 0.000
38
+ name: F1 (Seqeval)
39
+ - type: F1@M
40
+ value: 0.387
41
+ name: F1@M
42
  ---
43
+ # 🔑 Keyphrase Extraction Model: distilbert-openkp
44
+ Keyphrase extraction is a technique in text analysis where you extract the important keyphrases from a document. Thanks to these keyphrases humans can understand the content of a text very quickly and easily without reading it completely. Keyphrase extraction was first done primarily by human annotators, who read the text in detail and then wrote down the most important keyphrases. The disadvantage is that if you work with a lot of documents, this process can take a lot of time ⏳.
45
+
46
+ Here is where Artificial Intelligence 🤖 comes in. Currently, classical machine learning methods, that use statistical and linguistic features, are widely used for the extraction process. Now with deep learning, it is possible to capture the semantic meaning of a text even better than these classical methods. Classical methods look at the frequency, occurrence and order of words in the text, whereas these neural approaches can capture long-term semantic dependencies and context of words in a text.
47
+
48
+
49
+ ## 📓 Model Description
50
+ This model uses [KBIR](https://huggingface.co/distilbert-base-uncased) as its base model and fine-tunes it on the [OpenKP dataset](https://huggingface.co/datasets/midas/openkp). KBIR or Keyphrase Boundary Infilling with Replacement is a pre-trained model which utilizes a multi-task learning setup for optimizing a combined loss of Masked Language Modeling (MLM), Keyphrase Boundary Infilling (KBI) and Keyphrase Replacement Classification (KRC).
51
+ You can find more information about the architecture in this [paper](https://arxiv.org/abs/2112.08547).
52
+
53
+ Keyphrase extraction models are transformer models fine-tuned as a token classification problem where each word in the document is classified as being part of a keyphrase or not.
54
+
55
+ | Label | Description |
56
+ | ----- | ------------------------------- |
57
+ | B-KEY | At the beginning of a keyphrase |
58
+ | I-KEY | Inside a keyphrase |
59
+ | O | Outside a keyphrase |
60
+
61
+ ## ✋ Intended Uses & Limitations
62
+ ### 🛑 Limitations
63
+ * Limited amount of predicted keyphrases.
64
+ * Only works for English documents.
65
+ * For a custom model, please consult the [training notebook]() for more information.
66
+
67
+ ### ❓ How To Use
68
+ ```python
69
+ from transformers import (
70
+ TokenClassificationPipeline,
71
+ AutoModelForTokenClassification,
72
+ AutoTokenizer,
73
+ )
74
+ from transformers.pipelines import AggregationStrategy
75
+ import numpy as np
76
+
77
+ # Define keyphrase extraction pipeline
78
+ class KeyphraseExtractionPipeline(TokenClassificationPipeline):
79
+ def __init__(self, model, *args, **kwargs):
80
+ super().__init__(
81
+ model=AutoModelForTokenClassification.from_pretrained(model),
82
+ tokenizer=AutoTokenizer.from_pretrained(model),
83
+ *args,
84
+ **kwargs
85
+ )
86
+
87
+ def postprocess(self, model_outputs):
88
+ results = super().postprocess(
89
+ model_outputs=model_outputs,
90
+ aggregation_strategy=AggregationStrategy.FIRST,
91
+ )
92
+ return np.unique([result.get("word").strip() for result in results])
93
+
94
+ ```
95
+
96
+ ```python
97
+ # Load pipeline
98
+ model_name = "ml6team/keyphrase-extraction-kbir-openkp"
99
+ extractor = KeyphraseExtractionPipeline(model=model_name)
100
+
101
+ ```
102
+
103
+ ```python
104
+ # Inference
105
+ text = """
106
+ Keyphrase extraction is a technique in text analysis where you extract the
107
+ important keyphrases from a document. Thanks to these keyphrases humans can
108
+ understand the content of a text very quickly and easily without reading it
109
+ completely. Keyphrase extraction was first done primarily by human annotators,
110
+ who read the text in detail and then wrote down the most important keyphrases.
111
+ The disadvantage is that if you work with a lot of documents, this process
112
+ can take a lot of time.
113
+
114
+ Here is where Artificial Intelligence comes in. Currently, classical machine
115
+ learning methods, that use statistical and linguistic features, are widely used
116
+ for the extraction process. Now with deep learning, it is possible to capture
117
+ the semantic meaning of a text even better than these classical methods.
118
+ Classical methods look at the frequency, occurrence and order of words
119
+ in the text, whereas these neural approaches can capture long-term
120
+ semantic dependencies and context of words in a text.
121
+ """.replace("\n", " ")
122
+
123
+ keyphrases = extractor(text)
124
+
125
+ print(keyphrases)
126
+
127
+ ```
128
+
129
+ ```
130
+ # Output
131
+ ['keyphrase extraction' 'text analysis']
132
+ ```
133
+
134
+ ## 📚 Training Dataset
135
+ [OpenKP](https://github.com/microsoft/OpenKP) is a large-scale, open-domain keyphrase extraction dataset with 148,124 real-world web documents along with 1-3 most relevant human-annotated keyphrases.
136
+
137
+ You can find more information in the [paper](https://arxiv.org/abs/1911.02671).
138
+
139
+ ## 👷‍♂️ Training Procedure
140
+ For more in detail information, you can take a look at the [training notebook]().
141
+
142
+ ### Training Parameters
143
+
144
+ | Parameter | Value |
145
+ | --------- | ------|
146
+ | Learning Rate | 1e-4 |
147
+ | Epochs | 50 |
148
+ | Early Stopping Patience | 3 |
149
+
150
+ ### Preprocessing
151
+ The documents in the dataset are already preprocessed into list of words with the corresponding labels. The only thing that must be done is tokenization and the realignment of the labels so that they correspond with the right subword tokens.
152
+
153
+ ```python
154
+ from datasets import load_dataset
155
+ from transformers import AutoTokenizer
156
+
157
+ # Labels
158
+ label_list = ["B", "I", "O"]
159
+ lbl2idx = {"B": 0, "I": 1, "O": 2}
160
+ idx2label = {0: "B", 1: "I", 2: "O"}
161
+
162
+ # Tokenizer
163
+ tokenizer = AutoTokenizer.from_pretrained("bloomberg/KBIR")
164
+ max_length = 512
165
+
166
+ # Dataset parameters
167
+ dataset_full_name = "midas/openkp"
168
+ dataset_subset = "raw"
169
+ dataset_document_column = "document"
170
+ dataset_biotags_column = "doc_bio_tags"
171
+
172
+ def preprocess_fuction(all_samples_per_split):
173
+ tokenized_samples = tokenizer.batch_encode_plus(
174
+ all_samples_per_split[dataset_document_column],
175
+ padding="max_length",
176
+ truncation=True,
177
+ is_split_into_words=True,
178
+ max_length=max_length,
179
+ )
180
+ total_adjusted_labels = []
181
+ for k in range(0, len(tokenized_samples["input_ids"])):
182
+ prev_wid = -1
183
+ word_ids_list = tokenized_samples.word_ids(batch_index=k)
184
+ existing_label_ids = all_samples_per_split[dataset_biotags_column][k]
185
+ i = -1
186
+ adjusted_label_ids = []
187
+
188
+ for wid in word_ids_list:
189
+ if wid is None:
190
+ adjusted_label_ids.append(lbl2idx["O"])
191
+ elif wid != prev_wid:
192
+ i = i + 1
193
+ adjusted_label_ids.append(lbl2idx[existing_label_ids[i]])
194
+ prev_wid = wid
195
+ else:
196
+ adjusted_label_ids.append(
197
+ lbl2idx[
198
+ f"{'I' if existing_label_ids[i] == 'B' else existing_label_ids[i]}"
199
+ ]
200
+ )
201
+
202
+ total_adjusted_labels.append(adjusted_label_ids)
203
+ tokenized_samples["labels"] = total_adjusted_labels
204
+ return tokenized_samples
205
+
206
+ # Load dataset
207
+ dataset = load_dataset(dataset_full_name, dataset_subset)
208
+
209
+ # Preprocess dataset
210
+ tokenized_dataset = dataset.map(preprocess_fuction, batched=True)
211
+
212
+ ```
213
+
214
+ ### Postprocessing (Without Pipeline Function)
215
+ If you do not use the pipeline function, you must filter out the B and I labeled tokens. Each B and I will then be merged into a keyphrase. Finally, you need to strip the keyphrases to make sure all unnecessary spaces have been removed.
216
+ ```python
217
+ # Define post_process functions
218
+ def concat_tokens_by_tag(keyphrases):
219
+ keyphrase_tokens = []
220
+ for id, label in keyphrases:
221
+ if label == "B":
222
+ keyphrase_tokens.append([id])
223
+ elif label == "I":
224
+ if len(keyphrase_tokens) > 0:
225
+ keyphrase_tokens[len(keyphrase_tokens) - 1].append(id)
226
+ return keyphrase_tokens
227
+
228
+
229
+ def extract_keyphrases(example, predictions, tokenizer, index=0):
230
+ keyphrases_list = [
231
+ (id, idx2label[label])
232
+ for id, label in zip(
233
+ np.array(example["input_ids"]).squeeze().tolist(), predictions[index]
234
+ )
235
+ if idx2label[label] in ["B", "I"]
236
+ ]
237
+
238
+ processed_keyphrases = concat_tokens_by_tag(keyphrases_list)
239
+ extracted_kps = tokenizer.batch_decode(
240
+ processed_keyphrases,
241
+ skip_special_tokens=True,
242
+ clean_up_tokenization_spaces=True,
243
+ )
244
+ return np.unique([kp.strip() for kp in extracted_kps])
245
+
246
+ ```
247
+
248
+ ## 📝 Evaluation Results
249
+ Traditional evaluation methods are the precision, recall and F1-score @k,m where k is the number that stands for the first k predicted keyphrases and m for the average amount of predicted keyphrases.
250
+ The model achieves the following results on the OpenKP test set:
251
+
252
+ | Dataset | P@5 | R@5 | F1@5 | P@10 | R@10 | F1@10 | P@M | R@M | F1@M |
253
+ |:-----------------:|:----:|:----:|:----:|:----:|:----:|:-----:|:----:|:----:|:----:|
254
+ | OpenKP Test Set | 0.13 | 0.38 | 0.19 | 0.07 | 0.38 | 0.11 | 0.45 | 0.38 | 0.39 |
255
+
256
+ For more information on the evaluation process, you can take a look at the keyphrase extraction evaluation notebook.
257
+
258
+ ## 🚨 Issues
259
+ Please feel free to start discussions in the Community Tab.
config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "bloomberg/KBIR",
3
+ "architectures": [
4
+ "RobertaForTokenClassification"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "bos_token_id": 0,
8
+ "classifier_dropout": null,
9
+ "eos_token_id": 2,
10
+ "gradient_checkpointing": false,
11
+ "hidden_act": "gelu",
12
+ "hidden_dropout_prob": 0.1,
13
+ "hidden_size": 1024,
14
+ "id2label": {
15
+ "0": "B-KEY",
16
+ "1": "I-KEY",
17
+ "2": "O"
18
+ },
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 4096,
21
+ "label2id": {
22
+ "B-KEY": 0,
23
+ "I-KEY": 1,
24
+ "O": 2
25
+ },
26
+ "layer_norm_eps": 1e-05,
27
+ "max_position_embeddings": 514,
28
+ "model_type": "roberta",
29
+ "num_attention_heads": 16,
30
+ "num_hidden_layers": 24,
31
+ "pad_token_id": 1,
32
+ "position_embedding_type": "absolute",
33
+ "torch_dtype": "float32",
34
+ "transformers_version": "4.18.0",
35
+ "type_vocab_size": 1,
36
+ "use_cache": true,
37
+ "vocab_size": 50265
38
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bfc0bb5dfcc579fa06a06bf9eddffe3695c61cf48de5de5c4792f8d066ba1d85
3
+ size 1417389425
special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"bos_token": {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "eos_token": {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "unk_token": {"content": "<unk>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "sep_token": {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "pad_token": {"content": "<pad>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "cls_token": {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, "mask_token": {"content": "<mask>", "single_word": false, "lstrip": true, "rstrip": false, "normalized": true}}
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"errors": "replace", "bos_token": {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "eos_token": {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "sep_token": {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "cls_token": {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "unk_token": {"content": "<unk>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "pad_token": {"content": "<pad>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "mask_token": {"content": "<mask>", "single_word": false, "lstrip": true, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "add_prefix_space": true, "trim_offsets": true, "use_fast": true, "max_length": 512, "special_tokens_map_file": null, "name_or_path": "bloomberg/KBIR", "tokenizer_class": "RobertaTokenizer"}
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d7547c3e1ff4fb7082fe53db7750ee8d250be273c213939b0bbc9be1da979176
3
+ size 3055
vocab.json ADDED
The diff for this file is too large to render. See raw diff