Hassanjr commited on
Commit
489bbf3
·
verified ·
1 Parent(s): 6da19f0

final commit

Browse files
.gitattributes CHANGED
@@ -1,35 +1,27 @@
1
  *.7z filter=lfs diff=lfs merge=lfs -text
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
 
4
  *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
  *.ftz filter=lfs diff=lfs merge=lfs -text
7
  *.gz filter=lfs diff=lfs merge=lfs -text
8
  *.h5 filter=lfs diff=lfs merge=lfs -text
9
  *.joblib filter=lfs diff=lfs merge=lfs -text
10
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
  *.model filter=lfs diff=lfs merge=lfs -text
13
  *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
  *.onnx filter=lfs diff=lfs merge=lfs -text
17
  *.ot filter=lfs diff=lfs merge=lfs -text
18
  *.parquet filter=lfs diff=lfs merge=lfs -text
19
  *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
  *.pt filter=lfs diff=lfs merge=lfs -text
23
  *.pth filter=lfs diff=lfs merge=lfs -text
24
  *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
  *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
  *.tflite filter=lfs diff=lfs merge=lfs -text
30
  *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
  *.xz filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
  *.7z filter=lfs diff=lfs merge=lfs -text
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bin.* filter=lfs diff=lfs merge=lfs -text
5
  *.bz2 filter=lfs diff=lfs merge=lfs -text
 
6
  *.ftz filter=lfs diff=lfs merge=lfs -text
7
  *.gz filter=lfs diff=lfs merge=lfs -text
8
  *.h5 filter=lfs diff=lfs merge=lfs -text
9
  *.joblib filter=lfs diff=lfs merge=lfs -text
10
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
 
11
  *.model filter=lfs diff=lfs merge=lfs -text
12
  *.msgpack filter=lfs diff=lfs merge=lfs -text
 
 
13
  *.onnx filter=lfs diff=lfs merge=lfs -text
14
  *.ot filter=lfs diff=lfs merge=lfs -text
15
  *.parquet filter=lfs diff=lfs merge=lfs -text
16
  *.pb filter=lfs diff=lfs merge=lfs -text
 
 
17
  *.pt filter=lfs diff=lfs merge=lfs -text
18
  *.pth filter=lfs diff=lfs merge=lfs -text
19
  *.rar filter=lfs diff=lfs merge=lfs -text
20
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
 
21
  *.tar.* filter=lfs diff=lfs merge=lfs -text
 
22
  *.tflite filter=lfs diff=lfs merge=lfs -text
23
  *.tgz filter=lfs diff=lfs merge=lfs -text
 
24
  *.xz filter=lfs diff=lfs merge=lfs -text
25
  *.zip filter=lfs diff=lfs merge=lfs -text
26
+ *.zstandard filter=lfs diff=lfs merge=lfs -text
27
  *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+
3
+ language: en
4
+ license: mit
5
+ tags:
6
+ - keyphrase-extraction
7
+ datasets:
8
+ - midas/inspec
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: "In this work, we explore how to learn task specific language models aimed towards learning rich representation of keyphrases from text documents. We experiment with different masking strategies for pre-training transformer language models (LMs) in discriminative as well as generative settings. In the discriminative setting, we introduce a new pre-training objective - Keyphrase Boundary Infilling with Replacement (KBIR), showing large gains in performance (up to 9.26 points in F1) over SOTA, when LM pre-trained using KBIR is fine-tuned for the task of keyphrase extraction. In the generative setting, we introduce a new pre-training setup for BART - KeyBART, that reproduces the keyphrases related to the input text in the CatSeq format, instead of the denoised original input. This also led to gains in performance (up to 4.33 points inF1@M) over SOTA for keyphrase generation. Additionally, we also fine-tune the pre-trained language models on named entity recognition(NER), question answering (QA), relation extraction (RE), abstractive summarization and achieve comparable performance with that of the SOTA, showing that learning rich representation of keyphrases is indeed beneficial for many other fundamental NLP tasks."
25
+ example_title: "Example 2"
26
+ model-index:
27
+ - name: DeDeckerThomas/keyphrase-extraction-kbir-inspec
28
+ results:
29
+ - task:
30
+ type: keyphrase-extraction
31
+ name: Keyphrase Extraction
32
+ dataset:
33
+ type: midas/inspec
34
+ name: inspec
35
+ metrics:
36
+ - type: F1 (Seqeval)
37
+ value: 0.588
38
+ name: F1 (Seqeval)
39
+ - type: F1@M
40
+ value: 0.564
41
+ name: F1@M
42
+ ---
43
+ # 🔑 Keyphrase Extraction Model: KBIR-inspec
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
+
50
+ ## 📓 Model Description
51
+ This model uses [KBIR](https://huggingface.co/bloomberg/KBIR) as its base model and fine-tunes it on the [Inspec dataset](https://huggingface.co/datasets/midas/inspec). 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).
52
+ You can find more information about the architecture in this [paper](https://arxiv.org/abs/2112.08547).
53
+
54
+ 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.
55
+
56
+ | Label | Description |
57
+ | ----- | ------------------------------- |
58
+ | B-KEY | At the beginning of a keyphrase |
59
+ | I-KEY | Inside a keyphrase |
60
+ | O | Outside a keyphrase |
61
+
62
+ Kulkarni, Mayank, Debanjan Mahata, Ravneet Arora, and Rajarshi Bhowmik. "Learning Rich Representation of Keyphrases from Text." arXiv preprint arXiv:2112.08547 (2021).
63
+
64
+ Sahrawat, Dhruva, Debanjan Mahata, Haimin Zhang, Mayank Kulkarni, Agniv Sharma, Rakesh Gosangi, Amanda Stent, Yaman Kumar, Rajiv Ratn Shah, and Roger Zimmermann. "Keyphrase extraction as sequence labeling using contextualized embeddings." In European Conference on Information Retrieval, pp. 328-335. Springer, Cham, 2020.
65
+
66
+ ## ✋ Intended Uses & Limitations
67
+ ### 🛑 Limitations
68
+ * This keyphrase extraction model is very domain-specific and will perform very well on abstracts of scientific papers. It's not recommended to use this model for other domains, but you are free to test it out.
69
+ * Only works for English documents.
70
+
71
+ ### ❓ How To Use
72
+ ```python
73
+ from transformers import (
74
+ TokenClassificationPipeline,
75
+ AutoModelForTokenClassification,
76
+ AutoTokenizer,
77
+ )
78
+ from transformers.pipelines import AggregationStrategy
79
+ import numpy as np
80
+
81
+ # Define keyphrase extraction pipeline
82
+ class KeyphraseExtractionPipeline(TokenClassificationPipeline):
83
+ def __init__(self, model, *args, **kwargs):
84
+ super().__init__(
85
+ model=AutoModelForTokenClassification.from_pretrained(model),
86
+ tokenizer=AutoTokenizer.from_pretrained(model),
87
+ *args,
88
+ **kwargs
89
+ )
90
+
91
+ def postprocess(self, all_outputs):
92
+ results = super().postprocess(
93
+ all_outputs=all_outputs,
94
+ aggregation_strategy=AggregationStrategy.SIMPLE,
95
+ )
96
+ return np.unique([result.get("word").strip() for result in results])
97
+
98
+ ```
99
+
100
+ ```python
101
+ # Load pipeline
102
+ model_name = "ml6team/keyphrase-extraction-kbir-inspec"
103
+ extractor = KeyphraseExtractionPipeline(model=model_name)
104
+
105
+ ```
106
+ ```python
107
+ # Inference
108
+ text = """
109
+ Keyphrase extraction is a technique in text analysis where you extract the
110
+ important keyphrases from a document. Thanks to these keyphrases humans can
111
+ understand the content of a text very quickly and easily without reading it
112
+ completely. Keyphrase extraction was first done primarily by human annotators,
113
+ who read the text in detail and then wrote down the most important keyphrases.
114
+ The disadvantage is that if you work with a lot of documents, this process
115
+ can take a lot of time.
116
+
117
+ Here is where Artificial Intelligence comes in. Currently, classical machine
118
+ learning methods, that use statistical and linguistic features, are widely used
119
+ for the extraction process. Now with deep learning, it is possible to capture
120
+ the semantic meaning of a text even better than these classical methods.
121
+ Classical methods look at the frequency, occurrence and order of words
122
+ in the text, whereas these neural approaches can capture long-term
123
+ semantic dependencies and context of words in a text.
124
+ """.replace("\n", " ")
125
+
126
+ keyphrases = extractor(text)
127
+
128
+ print(keyphrases)
129
+
130
+ ```
131
+
132
+ ```
133
+ # Output
134
+ ['Artificial Intelligence' 'Keyphrase extraction' 'deep learning'
135
+ 'linguistic features' 'machine learning' 'semantic meaning'
136
+ 'text analysis']
137
+ ```
138
+
139
+ ## 📚 Training Dataset
140
+ [Inspec](https://huggingface.co/datasets/midas/inspec) is a keyphrase extraction/generation dataset consisting of 2000 English scientific papers from the scientific domains of Computers and Control and Information Technology published between 1998 to 2002. The keyphrases are annotated by professional indexers or editors.
141
+
142
+ You can find more information in the [paper](https://dl.acm.org/doi/10.3115/1119355.1119383).
143
+
144
+ ## 👷‍♂️ Training Procedure
145
+
146
+ ### Training Parameters
147
+
148
+ | Parameter | Value |
149
+ | --------- | ------|
150
+ | Learning Rate | 1e-4 |
151
+ | Epochs | 50 |
152
+ | Early Stopping Patience | 3 |
153
+
154
+ ### Preprocessing
155
+ 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.
156
+
157
+ ```python
158
+ from datasets import load_dataset
159
+ from transformers import AutoTokenizer
160
+
161
+ # Labels
162
+ label_list = ["B", "I", "O"]
163
+ lbl2idx = {"B": 0, "I": 1, "O": 2}
164
+ idx2label = {0: "B", 1: "I", 2: "O"}
165
+
166
+ # Tokenizer
167
+ tokenizer = AutoTokenizer.from_pretrained("bloomberg/KBIR", add_prefix_space=True)
168
+ max_length = 512
169
+
170
+ # Dataset parameters
171
+ dataset_full_name = "midas/inspec"
172
+ dataset_subset = "raw"
173
+ dataset_document_column = "document"
174
+ dataset_biotags_column = "doc_bio_tags"
175
+
176
+ def preprocess_fuction(all_samples_per_split):
177
+ tokenized_samples = tokenizer.batch_encode_plus(
178
+ all_samples_per_split[dataset_document_column],
179
+ padding="max_length",
180
+ truncation=True,
181
+ is_split_into_words=True,
182
+ max_length=max_length,
183
+ )
184
+ total_adjusted_labels = []
185
+ for k in range(0, len(tokenized_samples["input_ids"])):
186
+ prev_wid = -1
187
+ word_ids_list = tokenized_samples.word_ids(batch_index=k)
188
+ existing_label_ids = all_samples_per_split[dataset_biotags_column][k]
189
+ i = -1
190
+ adjusted_label_ids = []
191
+
192
+ for wid in word_ids_list:
193
+ if wid is None:
194
+ adjusted_label_ids.append(lbl2idx["O"])
195
+ elif wid != prev_wid:
196
+ i = i + 1
197
+ adjusted_label_ids.append(lbl2idx[existing_label_ids[i]])
198
+ prev_wid = wid
199
+ else:
200
+ adjusted_label_ids.append(
201
+ lbl2idx[
202
+ f"{'I' if existing_label_ids[i] == 'B' else existing_label_ids[i]}"
203
+ ]
204
+ )
205
+
206
+ total_adjusted_labels.append(adjusted_label_ids)
207
+ tokenized_samples["labels"] = total_adjusted_labels
208
+ return tokenized_samples
209
+
210
+ # Load dataset
211
+ dataset = load_dataset(dataset_full_name, dataset_subset)
212
+
213
+ # Preprocess dataset
214
+ tokenized_dataset = dataset.map(preprocess_fuction, batched=True)
215
+
216
+ ```
217
+
218
+ ### Postprocessing (Without Pipeline Function)
219
+ 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.
220
+ ```python
221
+ # Define post_process functions
222
+ def concat_tokens_by_tag(keyphrases):
223
+ keyphrase_tokens = []
224
+ for id, label in keyphrases:
225
+ if label == "B":
226
+ keyphrase_tokens.append([id])
227
+ elif label == "I":
228
+ if len(keyphrase_tokens) > 0:
229
+ keyphrase_tokens[len(keyphrase_tokens) - 1].append(id)
230
+ return keyphrase_tokens
231
+
232
+
233
+ def extract_keyphrases(example, predictions, tokenizer, index=0):
234
+ keyphrases_list = [
235
+ (id, idx2label[label])
236
+ for id, label in zip(
237
+ np.array(example["input_ids"]).squeeze().tolist(), predictions[index]
238
+ )
239
+ if idx2label[label] in ["B", "I"]
240
+ ]
241
+
242
+ processed_keyphrases = concat_tokens_by_tag(keyphrases_list)
243
+ extracted_kps = tokenizer.batch_decode(
244
+ processed_keyphrases,
245
+ skip_special_tokens=True,
246
+ clean_up_tokenization_spaces=True,
247
+ )
248
+ return np.unique([kp.strip() for kp in extracted_kps])
249
+
250
+ ```
251
+ ## 📝 Evaluation Results
252
+
253
+ 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.
254
+ The model achieves the following results on the Inspec test set:
255
+
256
+ | Dataset | P@5 | R@5 | F1@5 | P@10 | R@10 | F1@10 | P@M | R@M | F1@M |
257
+ |:-----------------:|:----:|:----:|:----:|:----:|:----:|:-----:|:----:|:----:|:----:|
258
+ | Inspec Test Set | 0.53 | 0.47 | 0.46 | 0.36 | 0.58 | 0.41 | 0.58 | 0.60 | 0.56 |
259
+
260
+ ## 🚨 Issues
261
+ 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.17.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:85631473963781c15e742b60724dac19acfd2e1415fe7db9a22ca8a0c92024d9
3
+ size 1417418225
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, "model_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:4da5deb41d8a2985b4418ac428a4c66f405b0914298a2b26b550c10a12b9327c
3
+ size 3055
vocab.json ADDED
The diff for this file is too large to render. See raw diff