EmbedRank and MDERank
Used by TermExtractor with method="embedrank". It needs the
optional transformers dependencies: pip install 'termxtract[transformers]'.
EmbedRankTermExtractor(threshold=None, n=3, variant='embedrank', corpus_aggregation='max', model_name=DEFAULT_MODEL, encoder=None, diversity=None, stopwords='english', words_layer=None, lemma_layer=None, min_frequency=1, word_pattern='alphanumeric', pos_pattern=None, pos_layer=None)
Bases: BaseTermExtractor
Embedding-based ranking: EmbedRank (Bennani-Smires et al., 2018) and MDERank (Zhang et al., 2022), which score candidates by how close their meaning is to that of the documents they occur in.
Documents and candidates are embedded by a sentence encoder, by default
all-MiniLM-L6-v2 (see termxtract.embeddings.Encoder). A document longer than
the encoder's max_length is split into chunks between words, and its embedding
( d ) is the mean of the embeddings of its chunks.
- "embedrank" scores a candidate ( c ) in a document by the cosine similarity of its embedding to ( d ).
- "mderank" masks every occurrence of ( c ) in the document, replacing the tokens of its words by the mask token, and re-embeds the chunks it occurs in. The score is ( 1 - \cos(d, d_c) ), where ( d_c ) is the embedding of the masked document, so candidates whose removal changes the document most score best. It encodes each chunk once per candidate in it, so it is much slower than "embedrank".
The scores of a term in the documents it occurs in are combined by
corpus_aggregation. With "centroid", "embedrank" scores each candidate by its
similarity to the mean of the document embeddings instead.
The papers rank the noun phrases of a single document, with other encoders: sent2vec
and doc2vec for EmbedRank, and BERT for MDERank. Here the candidates are those of
the other methods, set by n, stopwords, word_pattern, pos_pattern and
min_frequency. Documents are embedded from their words as written, and candidates
from their words, or with lemma_layer their lemmas.
With diversity, "embedrank" re-ranks the candidates by Maximal Marginal Relevance,
as in EmbedRank++, so that a candidate similar to better ones ranks lower (see
marginal_relevance). "mderank" does not, since its scores are on another scale
from the similarities: in long documents, masking a candidate changes few chunks,
and its scores can all be below 0.03, so the similarities would decide the ranking. The candidates of each document are re-ranked by their scores
in it, or with a corpus_aggregation all candidates together by their combined
scores. It compares each candidate with every other, so it takes time quadratic in
their number: about 20 seconds for 16,000 candidates.
Initialize the embedding-based extractor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
threshold
|
Optional[float]
|
Minimum score for term inclusion. |
None
|
n
|
int
|
Maximum n-gram size for candidate terms. |
3
|
variant
|
str
|
"embedrank" or "mderank". |
'embedrank'
|
corpus_aggregation
|
Optional[str]
|
How a term's scores in the documents it occurs in are combined into one score, which it gets in all of them: "max" (the default) for its best score, "mean" for the mean, "centroid" for its similarity to the mean of the document embeddings ("embedrank" only), or None to keep the score of each document. |
'max'
|
model_name
|
str
|
The Hugging Face model of the sentence encoder, if
|
DEFAULT_MODEL
|
encoder
|
Optional[Encoder]
|
A loaded encoder, to share one between
extractors or set its batch size, maximum length or device, or None to
load |
None
|
diversity
|
Optional[float]
|
Re-rank the candidates by Maximal Marginal Relevance with this weight on their redundancy, from 0 to 1 ("embedrank" only), or None to keep the ranking by score. |
None
|
stopwords
|
Union[str, Iterable[str], None]
|
Drop candidates that start or end
with a stopword: a name in |
'english'
|
words_layer
|
Optional[str]
|
For Teanga input, the span layer holding the
words, or None for |
None
|
lemma_layer
|
Optional[str]
|
For Teanga input, a sequence layer holding the lemma of each word, to count inflected forms such as "cell" and "cells" as one term, or None to use the words as written. |
None
|
min_frequency
|
int
|
Drop candidates that occur fewer times in the corpus. |
1
|
word_pattern
|
Optional[str]
|
Drop candidates with a word that does not fully match this regular expression or named pattern ("alphanumeric", "atr4s"), or None to keep every word. |
'alphanumeric'
|
pos_pattern
|
Optional[str]
|
For Teanga input, count only the occurrences whose part-of-speech tags match this pattern, or None. |
None
|
pos_layer
|
Optional[str]
|
The part-of-speech layer for |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ImportError
|
If an encoder is to be loaded and the optional 'transformers' dependencies are missing. |
extract_terms_teanga(corpus)
Extract terms from a Teanga corpus.
extract_terms_strings(corpus)
Extract terms from a plain list of strings.
document_scores(docs, occurrences)
Score the candidates of each document, combined by corpus_aggregation and
re-ranked by diversity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs
|
List[List[str]]
|
The words of each document as written. |
required |
occurrences
|
List[List[Tuple[str, int, int]]]
|
The occurrences of the
candidates in each document, from |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, float]]
|
List[Dict[str, float]]: The score of each candidate of each document, where |
list[dict[str, float]]
|
higher is better. |
diversify(scores)
Re-rank candidates by Maximal Marginal Relevance, with diversity as the weight
on their redundancy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
Dict[str, float]
|
The score of each candidate. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Dict[str, float]: The score of each candidate after re-ranking. |
masked_scores(docs, occurrences, spans, chunk_vectors)
Score the candidates of each document by MDERank.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs
|
List[List[str]]
|
The words of each document as written. |
required |
occurrences
|
List[List[Tuple[str, int, int]]]
|
The occurrences of the candidates in each document. |
required |
spans
|
List[List[Tuple[int, int]]]
|
The chunks of each document, from
|
required |
chunk_vectors
|
List[ndarray]
|
The embeddings of the chunks of each document. |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, float]]
|
List[Dict[str, float]]: The score of each candidate of each document. |
teanga_words(doc)
Get the words of a Teanga document with their offsets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
doc
|
Document
|
A Teanga document with a words layer (see |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[int, int, str]]
|
List[Tuple[int, int, str]]: A (start, end, text) tuple for each word, where |
list[tuple[int, int, str]]
|
text is the word's lemma if |
candidate_ngrams_teanga(corpus)
Find the occurrences of the candidates in a Teanga corpus.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
corpus
|
Corpus
|
A Teanga corpus with a words layer (see |
required |
Returns:
| Type | Description |
|---|---|
dict[str, list[tuple[str, tuple[int, int]]]]
|
Dict[str, List[Tuple[str, Tuple[int, int]]]]: For each document ID, every |
dict[str, list[tuple[str, tuple[int, int]]]]
|
occurrence of a candidate, with its start and end character offsets. |
candidate_ngrams_strings(docs)
Find the occurrences of the candidates in documents split into words.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs
|
List[List[str]]
|
The words of each document. |
required |
Returns:
| Type | Description |
|---|---|
list[list[str]]
|
List[List[str]]: Every occurrence of a candidate in each document. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
candidate_occurrences(docs, tags=None)
Find the occurrences of the candidates in documents split into words.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs
|
List[List[str]]
|
The words of each document. |
required |
tags
|
Optional[List[List[str]]]
|
The part-of-speech tag of each word of each
document, needed if |
None
|
Returns:
| Type | Description |
|---|---|
list[list[tuple[str, int, int]]]
|
List[List[Tuple[str, int, int]]]: Every occurrence of a candidate in each |
list[list[tuple[str, int, int]]]
|
document, with its start and end (exclusive) word index. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
frequent_candidates(ngrams)
Find the candidates that occur at least min_frequency times.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ngrams
|
Iterable[str]
|
Every occurrence of a candidate in the corpus. |
required |
Returns:
| Type | Description |
|---|---|
set[str]
|
Set[str]: The candidates that occur often enough. |
generate_ngrams_teanga(words_with_offsets)
Generate n-grams with offsets for a Teanga corpus.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
words_with_offsets
|
List[Tuple[int, int, str]]
|
List of (start, end, text) tuples for words. |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[str, tuple[int, int]]]
|
List[Tuple[str, Tuple[int, int]]]: List of n-grams with their start and end offsets. |
generate_ngrams_strings(words)
Generate n-grams for a plain list of strings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
words
|
List[str]
|
List of words in the document. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List[str]: List of n-grams. |
compute_tf(ngrams, total=None)
Compute the relative frequency of each n-gram in a document.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ngrams
|
List[str]
|
The n-grams in the document. |
required |
total
|
Optional[int]
|
The number to divide the counts by, or None for the
number of |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Dict[str, float]: Count of each n-gram divided by the total number of n-grams. |
ngram_total(num_words)
Count the n-grams of up to n words in a document, candidates or not.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_words
|
int
|
The number of words of the document. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The number of n-grams. |
compute_idf(corpus_ngrams)
Compute the inverse document frequency of each n-gram as log(N / (1 + df)).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
corpus_ngrams
|
List[List[str]]
|
The n-grams of each document. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Dict[str, float]: IDF score for each n-gram, where N is the number of documents |
dict[str, float]
|
and df is the number of documents containing the n-gram. |
doc_terms(doc_id, scores)
Build one document's entry in ATEResults.terms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
doc_id
|
str
|
The document ID. |
required |
scores
|
Dict[str, float]
|
The score of each candidate term. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict[str, Any]: |
dict[str, Any]
|
terms below the threshold or starting or ending with a stopword removed, and the rest ranked from highest to lowest score. |
doc_offsets(doc_id, ngrams_with_offsets, doc_terms)
staticmethod
Build one document's entry in ATEResults.offsets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
doc_id
|
str
|
The document ID. |
required |
ngrams_with_offsets
|
Iterable[Tuple[str, Tuple[int, int]]]
|
Every n-gram occurrence in the document with its (start, end) character offsets. |
required |
doc_terms
|
Dict[str, Any]
|
The document's entry in |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict[str, Any]: |
dict[str, Any]
|
listing each occurrence of an extracted term in document order. |