Skip to content

Commit 2a982bd

Browse files
author
Maarten Grootendorst
authored
v0.2 (#23)
* Add similarity scores to the output * Add Flair as a possible back-end * Update documentation + improved testing
1 parent e66fc12 commit 2a982bd

11 files changed

Lines changed: 411 additions & 142 deletions

File tree

README.md

Lines changed: 77 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ Corresponding medium post can be found [here](https://towardsdatascience.com/key
2020
2.1. [Installation](#installation)
2121
2.2. [Basic Usage](#usage)
2222
2.3. [Max Sum Similarity](#maxsum)
23-
2.4. [Maximal Marginal Relevance](#maximal)
23+
2.4. [Maximal Marginal Relevance](#maximal)
24+
2.5. [Embedding Models](#embeddings)
2425
<!--te-->
2526

2627

@@ -58,15 +59,18 @@ Thus, the goal was a `pip install keybert` and at most 3 lines of code in usage.
5859

5960
<a name="installation"/></a>
6061
### 2.1. Installation
61-
**[PyTorch 1.2.0](https://pytorch.org/get-started/locally/)** or higher is recommended. If the install below gives an
62-
error, please install pytorch first [here](https://pytorch.org/get-started/locally/).
63-
64-
Installation can be done using [pypi](https://pypi.org/project/bertopic/):
62+
Installation can be done using [pypi](https://pypi.org/project/keybert/):
6563

6664
```
6765
pip install keybert
6866
```
6967

68+
To use Flair embeddings, install KeyBERT as follows:
69+
70+
```
71+
pip install keybert[flair]
72+
```
73+
7074
<a name="usage"/></a>
7175
### 2.2. Usage
7276

@@ -94,23 +98,23 @@ You can set `keyphrase_ngram_range` to set the length of the resulting keywords/
9498

9599
```python
96100
>>> model.extract_keywords(doc, keyphrase_ngram_range=(1, 1), stop_words=None)
97-
['learning',
98-
'training',
99-
'algorithm',
100-
'class',
101-
'mapping']
101+
[('learning', 0.4604),
102+
('algorithm', 0.4556),
103+
('training', 0.4487),
104+
('class', 0.4086),
105+
('mapping', 0.3700)]
102106
```
103107

104108
To extract keyphrases, simply set `keyphrase_ngram_range` to (1, 2) or higher depending on the number
105109
of words you would like in the resulting keyphrases:
106110

107111
```python
108112
>>> model.extract_keywords(doc, keyphrase_ngram_range=(1, 2), stop_words=None)
109-
['learning algorithm',
110-
'learning machine',
111-
'machine learning',
112-
'supervised learning',
113-
'learning function']
113+
[('learning algorithm', 0.6978),
114+
('machine learning', 0.6305),
115+
('supervised learning', 0.5985),
116+
('algorithm analyzes', 0.5860),
117+
('learning function', 0.5850)]
114118
```
115119

116120

@@ -128,11 +132,11 @@ that are the least similar to each other by cosine similarity.
128132
```python
129133
>>> model.extract_keywords(doc, keyphrase_ngram_range=(3, 3), stop_words='english',
130134
use_maxsum=True, nr_candidates=20, top_n=5)
131-
['set training examples',
132-
'generalize training data',
133-
'requires learning algorithm',
134-
'superivsed learning algorithm',
135-
'learning machine learning']
135+
[('set training examples', 0.7504),
136+
('generalize training data', 0.7727),
137+
('requires learning algorithm', 0.5050),
138+
('supervised learning algorithm', 0.3779),
139+
('learning machine learning', 0.2891)]
136140
```
137141

138142

@@ -144,26 +148,67 @@ keywords / keyphrases which is also based on cosine similarity. The results
144148
with **high diversity**:
145149

146150
```python
147-
>>> model.extract_keywords(doc, keyphrase_ngram_range=(3, 3), stop_words='english', use_mmr=True, diversity=0.7)
148-
['algorithm generalize training',
149-
'labels unseen instances',
150-
'new examples optimal',
151-
'determine class labels',
152-
'supervised learning algorithm']
151+
>>> model.extract_keywords(doc, keyphrase_ngram_range=(3, 3), stop_words='english',
152+
use_mmr=True, diversity=0.7)
153+
[('algorithm generalize training', 0.7727),
154+
('labels unseen instances', 0.1649),
155+
('new examples optimal', 0.4185),
156+
('determine class labels', 0.4774),
157+
('supervised learning algorithm', 0.7502)]
153158
```
154159

155160
The results with **low diversity**:
156161

157162
```python
158-
>>> model.extract_keywords(doc, keyphrase_ngram_range=(3, 3), stop_words='english', use_mmr=True, diversity=0.2)
159-
['algorithm generalize training',
160-
'learning machine learning',
161-
'learning algorithm analyzes',
162-
'supervised learning algorithm',
163-
'algorithm analyzes training']
163+
>>> model.extract_keywords(doc, keyphrase_ngram_range=(3, 3), stop_words='english',
164+
use_mmr=True, diversity=0.2)
165+
[('algorithm generalize training', 0.7727),
166+
('supervised learning algorithm', 0.7502),
167+
('learning machine learning', 0.7577),
168+
('learning algorithm analyzes', 0.7587),
169+
('learning algorithm generalize', 0.7514)]
164170
```
165171

166172

173+
<a name="embeddings"/></a>
174+
### 2.5. Embedding Models
175+
The parameter `model` takes in a string pointing to a sentence-transformers model,
176+
a SentenceTransformer, or a Flair DocumentEmbedding model.
177+
178+
**Sentence-Transformers**
179+
You can select any model from `sentence-transformers` [here](https://www.sbert.net/docs/pretrained_models.html)
180+
and pass it through KeyBERT with `model`:
181+
182+
```python
183+
from keybert import KeyBERT
184+
model = KeyBERT(model='distilbert-base-nli-mean-tokens')
185+
```
186+
187+
Or select a SentenceTransformer model with your own parameters:
188+
189+
```python
190+
from keybert import KeyBERT
191+
from sentence_transformers import SentenceTransformer
192+
193+
sentence_model = SentenceTransformer("distilbert-base-nli-mean-tokens", device="cpu")
194+
model = KeyBERT(model=sentence_model)
195+
```
196+
197+
**Flair**
198+
[Flair](https://github.com/flairNLP/flair) allows you to choose almost any embedding model that
199+
is publicly available. Flair can be used as follows:
200+
201+
```python
202+
from keybert import KeyBERT
203+
from flair.embeddings import TransformerDocumentEmbeddings
204+
205+
roberta = TransformerDocumentEmbeddings('roberta-base')
206+
model = KeyBERT(model=roberta)
207+
```
208+
209+
You can select any 🤗 transformers model [here](https://huggingface.co/models).
210+
211+
167212
## Citation
168213
To cite PolyFuzz in your work, please use the following bibtex reference:
169214

docs/guides/embeddings.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
## **Embedding Models**
2+
The parameter `model` takes in a string pointing to a sentence-transformers model,
3+
a SentenceTransformer, or a Flair DocumentEmbedding model.
4+
5+
### **Sentence-Transformers**
6+
You can select any model from `sentence-transformers` [here](https://www.sbert.net/docs/pretrained_models.html)
7+
and pass it through KeyBERT with `model`:
8+
9+
```python
10+
from keybert import KeyBERT
11+
model = KeyBERT(model='distilbert-base-nli-mean-tokens')
12+
```
13+
14+
Or select a SentenceTransformer model with your own parameters:
15+
16+
```python
17+
from keybert import KeyBERT
18+
from sentence_transformers import SentenceTransformer
19+
20+
sentence_model = SentenceTransformer("distilbert-base-nli-mean-tokens", device="cpu")
21+
model = KeyBERT(model=sentence_model)
22+
```
23+
24+
### **Flair**
25+
[Flair](https://github.com/flairNLP/flair) allows you to choose almost any embedding model that
26+
is publicly available. Flair can be used as follows:
27+
28+
```python
29+
from keybert import KeyBERT
30+
from flair.embeddings import TransformerDocumentEmbeddings
31+
32+
roberta = TransformerDocumentEmbeddings('roberta-base')
33+
model = KeyBERT(model=roberta)
34+
```
35+
36+
You can select any 🤗 transformers model [here](https://huggingface.co/models).

docs/guides/quickstart.md

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
## **Installation**
2+
Installation can be done using [pypi](https://pypi.org/project/bertopic/):
3+
4+
```
5+
pip install keybert
6+
```
7+
8+
To use Flair embeddings, install KeyBERT as follows:
9+
10+
```
11+
pip install keybert[flair]
12+
```
13+
14+
Or to install all additional dependencies:
15+
16+
17+
```
18+
pip install keybert[all]
19+
```
20+
21+
## **Usage**
22+
23+
The most minimal example can be seen below for the extraction of keywords:
24+
```python
25+
from keybert import KeyBERT
26+
27+
doc = """
28+
Supervised learning is the machine learning task of learning a function that
29+
maps an input to an output based on example input-output pairs.[1] It infers a
30+
function from labeled training data consisting of a set of training examples.[2]
31+
In supervised learning, each example is a pair consisting of an input object
32+
(typically a vector) and a desired output value (also called the supervisory signal).
33+
A supervised learning algorithm analyzes the training data and produces an inferred function,
34+
which can be used for mapping new examples. An optimal scenario will allow for the
35+
algorithm to correctly determine the class labels for unseen instances. This requires
36+
the learning algorithm to generalize from the training data to unseen situations in a
37+
'reasonable' way (see inductive bias).
38+
"""
39+
model = KeyBERT('distilbert-base-nli-mean-tokens')
40+
keywords = model.extract_keywords(doc)
41+
```
42+
43+
You can set `keyphrase_ngram_range` to set the length of the resulting keywords/keyphrases:
44+
45+
```python
46+
>>> model.extract_keywords(doc, keyphrase_ngram_range=(1, 1), stop_words=None)
47+
[('learning', 0.4604),
48+
('algorithm', 0.4556),
49+
('training', 0.4487),
50+
('class', 0.4086),
51+
('mapping', 0.3700)]
52+
```
53+
54+
To extract keyphrases, simply set `keyphrase_ngram_range` to (1, 2) or higher depending on the number
55+
of words you would like in the resulting keyphrases:
56+
57+
```python
58+
>>> model.extract_keywords(doc, keyphrase_ngram_range=(1, 2), stop_words=None)
59+
[('learning algorithm', 0.6978),
60+
('machine learning', 0.6305),
61+
('supervised learning', 0.5985),
62+
('algorithm analyzes', 0.5860),
63+
('learning function', 0.5850)]
64+
```
65+
66+
**NOTE**: For a full overview of all possible transformer models see [sentence-transformer](https://www.sbert.net/docs/pretrained_models.html).
67+
I would advise either `'distilbert-base-nli-mean-tokens'` or `'xlm-r-distilroberta-base-paraphrase-v1'` as they
68+
have shown great performance in semantic similarity and paraphrase identification respectively.
69+
70+
### Max Sum Similarity
71+
72+
To diversity the results, we take the 2 x top_n most similar words/phrases to the document.
73+
Then, we take all top_n combinations from the 2 x top_n words and extract the combination
74+
that are the least similar to each other by cosine similarity.
75+
76+
```python
77+
>>> model.extract_keywords(doc, keyphrase_ngram_range=(3, 3), stop_words='english',
78+
use_maxsum=True, nr_candidates=20, top_n=5)
79+
[('set training examples', 0.7504),
80+
('generalize training data', 0.7727),
81+
('requires learning algorithm', 0.5050),
82+
('supervised learning algorithm', 0.3779),
83+
('learning machine learning', 0.2891)]
84+
```
85+
86+
### Maximal Marginal Relevance
87+
88+
To diversify the results, we can use Maximal Margin Relevance (MMR) to create
89+
keywords / keyphrases which is also based on cosine similarity. The results
90+
with **high diversity**:
91+
92+
```python
93+
>>> model.extract_keywords(doc, keyphrase_ngram_range=(3, 3), stop_words='english',
94+
use_mmr=True, diversity=0.7)
95+
[('algorithm generalize training', 0.7727),
96+
('labels unseen instances', 0.1649),
97+
('new examples optimal', 0.4185),
98+
('determine class labels', 0.4774),
99+
('supervised learning algorithm', 0.7502)]
100+
```
101+
102+
The results with **low diversity**:
103+
104+
```python
105+
>>> model.extract_keywords(doc, keyphrase_ngram_range=(3, 3), stop_words='english',
106+
use_mmr=True, diversity=0.2)
107+
[('algorithm generalize training', 0.7727),
108+
('supervised learning algorithm', 0.7502),
109+
('learning machine learning', 0.7577),
110+
('learning algorithm analyzes', 0.7587),
111+
('learning algorithm generalize', 0.7514)]
112+
```

0 commit comments

Comments
 (0)