munishair commited on
Commit
d96bf69
·
verified ·
1 Parent(s): 74fe309

Upload 9 files

Browse files
README.md ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-distilbert-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.509
38
+ name: F1 (Seqeval)
39
+ - type: F1@M
40
+ value: 0.490
41
+ name: F1@M
42
+ ---
43
+ # 🔑 Keyphrase Extraction Model: distilbert-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
+ ## 📓 Model Description
50
+ This model uses [distilbert](https://huggingface.co/distilbert-base-uncased) as its base model and fine-tunes it on the [Inspec dataset](https://huggingface.co/datasets/midas/inspec).
51
+
52
+ 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.
53
+
54
+ | Label | Description |
55
+ | ----- | ------------------------------- |
56
+ | B-KEY | At the beginning of a keyphrase |
57
+ | I-KEY | Inside a keyphrase |
58
+ | O | Outside a keyphrase |
59
+
60
+ Kulkarni, Mayank, Debanjan Mahata, Ravneet Arora, and Rajarshi Bhowmik. "Learning Rich Representation of Keyphrases from Text." arXiv preprint arXiv:2112.08547 (2021).
61
+
62
+ 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.
63
+
64
+ ## ✋ Intended Uses & Limitations
65
+ ### 🛑 Limitations
66
+ * 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.
67
+ * Only works for English documents.
68
+
69
+ ### ❓ How To Use
70
+ ```python
71
+ from transformers import (
72
+ TokenClassificationPipeline,
73
+ AutoModelForTokenClassification,
74
+ AutoTokenizer,
75
+ )
76
+ from transformers.pipelines import AggregationStrategy
77
+ import numpy as np
78
+
79
+ # Define keyphrase extraction pipeline
80
+ class KeyphraseExtractionPipeline(TokenClassificationPipeline):
81
+ def __init__(self, model, *args, **kwargs):
82
+ super().__init__(
83
+ model=AutoModelForTokenClassification.from_pretrained(model),
84
+ tokenizer=AutoTokenizer.from_pretrained(model),
85
+ *args,
86
+ **kwargs
87
+ )
88
+
89
+ def postprocess(self, all_outputs):
90
+ results = super().postprocess(
91
+ all_outputs=all_outputs,
92
+ aggregation_strategy=AggregationStrategy.FIRST,
93
+ )
94
+ return np.unique([result.get("word").strip() for result in results])
95
+
96
+ ```
97
+
98
+ ```python
99
+ # Load pipeline
100
+ model_name = "ml6team/keyphrase-extraction-distilbert-inspec"
101
+ extractor = KeyphraseExtractionPipeline(model=model_name)
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
+ # Output
130
+ ['artificial intelligence' 'classical machine learning' 'deep learning'
131
+ 'keyphrase extraction' 'linguistic features' 'statistical'
132
+ 'text analysis']
133
+ ```
134
+
135
+ ## 📚 Training Dataset
136
+ [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.
137
+
138
+ You can find more information in the [paper](https://dl.acm.org/doi/10.3115/1119355.1119383).
139
+
140
+ ## 👷‍♂️ Training Procedure
141
+ ### Training Parameters
142
+
143
+ | Parameter | Value |
144
+ | --------- | ------|
145
+ | Learning Rate | 1e-4 |
146
+ | Epochs | 50 |
147
+ | Early Stopping Patience | 3 |
148
+
149
+ ### Preprocessing
150
+ 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.
151
+
152
+ ```python
153
+ from datasets import load_dataset
154
+ from transformers import AutoTokenizer
155
+
156
+ # Labels
157
+ label_list = ["B", "I", "O"]
158
+ lbl2idx = {"B": 0, "I": 1, "O": 2}
159
+ idx2label = {0: "B", 1: "I", 2: "O"}
160
+
161
+ # Tokenizer
162
+ tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
163
+ max_length = 512
164
+
165
+ # Dataset parameters
166
+ dataset_full_name = "midas/inspec"
167
+ dataset_subset = "raw"
168
+ dataset_document_column = "document"
169
+ dataset_biotags_column = "doc_bio_tags"
170
+
171
+ def preprocess_fuction(all_samples_per_split):
172
+ tokenized_samples = tokenizer.batch_encode_plus(
173
+ all_samples_per_split[dataset_document_column],
174
+ padding="max_length",
175
+ truncation=True,
176
+ is_split_into_words=True,
177
+ max_length=max_length,
178
+ )
179
+ total_adjusted_labels = []
180
+ for k in range(0, len(tokenized_samples["input_ids"])):
181
+ prev_wid = -1
182
+ word_ids_list = tokenized_samples.word_ids(batch_index=k)
183
+ existing_label_ids = all_samples_per_split[dataset_biotags_column][k]
184
+ i = -1
185
+ adjusted_label_ids = []
186
+
187
+ for wid in word_ids_list:
188
+ if wid is None:
189
+ adjusted_label_ids.append(lbl2idx["O"])
190
+ elif wid != prev_wid:
191
+ i = i + 1
192
+ adjusted_label_ids.append(lbl2idx[existing_label_ids[i]])
193
+ prev_wid = wid
194
+ else:
195
+ adjusted_label_ids.append(
196
+ lbl2idx[
197
+ f"{'I' if existing_label_ids[i] == 'B' else existing_label_ids[i]}"
198
+ ]
199
+ )
200
+
201
+ total_adjusted_labels.append(adjusted_label_ids)
202
+ tokenized_samples["labels"] = total_adjusted_labels
203
+ return tokenized_samples
204
+
205
+ # Load dataset
206
+ dataset = load_dataset(dataset_full_name, dataset_subset)
207
+
208
+ # Preprocess dataset
209
+ tokenized_dataset = dataset.map(preprocess_fuction, batched=True)
210
+
211
+ ```
212
+
213
+ ### Postprocessing (Without Pipeline Function)
214
+ 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.
215
+ ```python
216
+ # Define post_process functions
217
+ def concat_tokens_by_tag(keyphrases):
218
+ keyphrase_tokens = []
219
+ for id, label in keyphrases:
220
+ if label == "B":
221
+ keyphrase_tokens.append([id])
222
+ elif label == "I":
223
+ if len(keyphrase_tokens) > 0:
224
+ keyphrase_tokens[len(keyphrase_tokens) - 1].append(id)
225
+ return keyphrase_tokens
226
+
227
+
228
+ def extract_keyphrases(example, predictions, tokenizer, index=0):
229
+ keyphrases_list = [
230
+ (id, idx2label[label])
231
+ for id, label in zip(
232
+ np.array(example["input_ids"]).squeeze().tolist(), predictions[index]
233
+ )
234
+ if idx2label[label] in ["B", "I"]
235
+ ]
236
+
237
+ processed_keyphrases = concat_tokens_by_tag(keyphrases_list)
238
+ extracted_kps = tokenizer.batch_decode(
239
+ processed_keyphrases,
240
+ skip_special_tokens=True,
241
+ clean_up_tokenization_spaces=True,
242
+ )
243
+ return np.unique([kp.strip() for kp in extracted_kps])
244
+
245
+ ```
246
+
247
+ ## 📝 Evaluation Results
248
+
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 Inspec 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
+ | Inspec Test Set | 0.45 | 0.40 | 0.39 | 0.33 | 0.53 | 0.38 | 0.47 | 0.57 | 0.49 |
255
+
256
+ ## 🚨 Issues
257
+ Please feel free to start discussions in the Community Tab.
config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "distilbert-base-uncased",
3
+ "activation": "gelu",
4
+ "architectures": [
5
+ "DistilBertForTokenClassification"
6
+ ],
7
+ "attention_dropout": 0.1,
8
+ "dim": 768,
9
+ "dropout": 0.1,
10
+ "hidden_dim": 3072,
11
+ "id2label": {
12
+ "0": "B-KEY",
13
+ "1": "I-KEY",
14
+ "2": "O"
15
+ },
16
+ "initializer_range": 0.02,
17
+ "label2id": {
18
+ "B-KEY": 0,
19
+ "I-KEY": 1,
20
+ "O": 2
21
+ },
22
+ "max_position_embeddings": 512,
23
+ "model_type": "distilbert",
24
+ "n_heads": 12,
25
+ "n_layers": 6,
26
+ "pad_token_id": 0,
27
+ "qa_dropout": 0.1,
28
+ "seq_classif_dropout": 0.2,
29
+ "sinusoidal_pos_embds": false,
30
+ "tie_weights_": true,
31
+ "torch_dtype": "float32",
32
+ "transformers_version": "4.17.0",
33
+ "vocab_size": 30522
34
+ }
gitattributes ADDED
@@ -0,0 +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
+ *.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
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a98a219be45970a6d489a4ed2330d0b5006f1fe5e16375acfbe5f51a9737d7c9
3
+ size 265500533
special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"unk_token": "[UNK]", "sep_token": "[SEP]", "pad_token": "[PAD]", "cls_token": "[CLS]", "mask_token": "[MASK]"}
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"do_lower_case": true, "unk_token": "[UNK]", "sep_token": "[SEP]", "pad_token": "[PAD]", "cls_token": "[CLS]", "mask_token": "[MASK]", "tokenize_chinese_chars": true, "strip_accents": null, "model_max_length": 512, "special_tokens_map_file": null, "name_or_path": "distilbert-base-uncased", "tokenizer_class": "DistilBertTokenizer"}
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f7187e3e56d6824e3dfbbfff25e7b38a82dc998f97a066d504b91d3ceac5b002
3
+ size 3055
vocab.txt ADDED
The diff for this file is too large to render. See raw diff