Re-ranking
Re-rankers that revise the scores of any unsupervised method, passed to
TermExtractor as rerank. They embed words with a sentence
encoder (see Embeddings), so they need the optional transformers
dependencies: pip install 'termxtract[transformers]'.
rerank
Semantic re-ranking of the terms of any extractor: AdaText (Zhang, Petrak & Maynard, 2018) and SemRe-Rank (Zhang, Gao & Ciravegna, 2018).
Both revise the score of each term with the scores of its words in a graph of the corpus's words, chosen or linked by how similar their embeddings are:
[ score(t) = \left(1 + \frac{1}{|words(t)|} \sum_{w \in words(t)} s(w)\right) \cdot ate(t) ]
where ( ate(t) ) is the score of the extractor and ( words(t) ) the distinct words
of the term that are not stopwords. A term with a negative score is divided by the same
factor instead, so that its words' scores move it up the ranking as they do a term with
a positive score. Pass a re-ranker to TermExtractor as rerank:
from termxtract import TermExtractor
from termxtract.rerank import SemReRank
extractor = TermExtractor(method="cvalue", n=3, rerank=SemReRank(seeds=200))
Words are compared, and terms re-scored, in lower case. Words are embedded one at a time
by a sentence encoder, by default all-MiniLM-L6-v2 (see
termxtract.embeddings.Encoder), so the transformers extra is needed.
BLOCK = 1024
module-attribute
The number of words whose similarities to the others are computed at once.
Reranker(seeds=200, encoder=None, model_name=DEFAULT_MODEL, stopwords='english')
Bases: ABC
Common interface of the re-rankers.
Subclasses implement word_scores, which scores the words of the corpus.
Initialize the re-ranker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seeds
|
Union[List[str], int]
|
Terms or phrases known to belong to the domain, or a number ( z ) to take the ( z ) most frequent terms of the extractor, as in the unsupervised variant of SemRe-Rank. |
200
|
encoder
|
Optional[Encoder]
|
A loaded |
None
|
model_name
|
str
|
The Hugging Face model of the sentence encoder. |
DEFAULT_MODEL
|
stopwords
|
Union[str, Iterable[str], None]
|
The words that are left out of
the graph and of the words of the terms: a name in |
'english'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
normalize = False
class-attribute
instance-attribute
Whether the extractor's scores are divided by their largest absolute value.
rerank(results, docs)
Re-score the terms of an extractor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
ATEResults
|
The terms of the extractor. |
required |
docs
|
List[List[str]]
|
The words of each document of the corpus, as the extractor read them, so that the terms are sequences of them. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ATEResults |
ATEResults
|
The same terms and offsets, with the revised scores. |
word_scores(docs, terms, seeds)
abstractmethod
Score the words of the corpus.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs
|
List[List[str]]
|
The lower-case words of each document. |
required |
terms
|
List[str]
|
The lower-case terms of the extractor. |
required |
seeds
|
List[str]
|
The lower-case seeds. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Dict[str, float]: The score of each word; the others score 0. |
is_word(word)
Whether a word can be a node: not a stopword, and with a letter or digit.
words(term)
The distinct words of a term or seed that can be nodes.
most_frequent(docs, terms, z)
staticmethod
Find the most frequent terms in the corpus.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs
|
List[List[str]]
|
The lower-case words of each document. |
required |
terms
|
List[str]
|
The lower-case terms. |
required |
z
|
int
|
The number of terms to return. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List[str]: The |
list[str]
|
ties in the order of |
embed(texts)
Embed texts, loading the encoder if it is not loaded yet.
AdaText(seeds=200, threshold=0.7, window=5, encoder=None, model_name=DEFAULT_MODEL, stopwords='english')
Bases: Reranker
AdaText (Zhang, Petrak & Maynard, 2018): TextRank over the words of the corpus that are similar to the seeds.
The nodes are the words of the corpus whose embeddings have a cosine similarity
above threshold with that of any seed, and two nodes are linked if they occur in
the same window of window words in any document, as in TextRank. The score of a
word ( s(w) ) is its PageRank score, with the scores scaled to unit length, as in
the TextRank implementation that the paper used (summa), and 0 for the words that
are not nodes.
The paper embedded words with GloVe and a seed of several words as the mean of their embeddings; here each word, and each seed, is embedded by the sentence encoder. Its seeds were a domain lexicon, which need not occur in the corpus.
Initialize AdaText.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seeds
|
Union[List[str], int]
|
Terms or phrases known to belong to the domain, or a number ( z ) to take the ( z ) most frequent terms. |
200
|
threshold
|
float
|
The cosine similarity to a seed that a word must exceed to be a node. The paper tried 0.5 to 0.85 with GloVe embeddings. |
0.7
|
window
|
int
|
Link the nodes that occur in the same window of this many words: 5 in the paper. |
5
|
encoder
|
Optional[Encoder]
|
A loaded encoder, or None to load |
None
|
model_name
|
str
|
The Hugging Face model of the sentence encoder. |
DEFAULT_MODEL
|
stopwords
|
Union[str, Iterable[str], None]
|
The words left out of the graph and of the words of the terms. |
'english'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
normalize = False
class-attribute
instance-attribute
Whether the extractor's scores are divided by their largest absolute value.
word_scores(docs, terms, seeds)
Score the words of the corpus by TextRank over the words similar to a seed.
rerank(results, docs)
Re-score the terms of an extractor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
ATEResults
|
The terms of the extractor. |
required |
docs
|
List[List[str]]
|
The words of each document of the corpus, as the extractor read them, so that the terms are sequences of them. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ATEResults |
ATEResults
|
The same terms and offsets, with the revised scores. |
is_word(word)
Whether a word can be a node: not a stopword, and with a letter or digit.
words(term)
The distinct words of a term or seed that can be nodes.
most_frequent(docs, terms, z)
staticmethod
Find the most frequent terms in the corpus.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs
|
List[List[str]]
|
The lower-case words of each document. |
required |
terms
|
List[str]
|
The lower-case terms. |
required |
z
|
int
|
The number of terms to return. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List[str]: The |
list[str]
|
ties in the order of |
embed(texts)
Embed texts, loading the encoder if it is not loaded yet.
SemReRank(seeds=200, rel_min=0.5, rel_top=0.15, encoder=None, model_name=DEFAULT_MODEL, stopwords='english')
Bases: Reranker
SemRe-Rank (Zhang, Gao & Ciravegna, 2018): personalised PageRank over graphs of semantically related words, one for each document.
The words are those of the terms. A word ( y ) is strongly related to a word
( x ) if the cosine similarity of their embeddings is above rel_min and among
the rel_top highest of ( x ) with the other words. Each document has a graph of
its words, in which each is linked to the words of the document strongly related
to it, and PageRank, with a damping factor of 0.85, jumps to each word of the seeds
with the same probability. The semantic importance of a word is the sum of its
scores over the documents, where a document without a word of the seeds counts 0,
and ( s(w) ) is its semantic importance divided by the largest. The extractor's
scores are divided by their largest absolute value too, as in the paper.
The paper trained word2vec on the corpus; here words are embedded by the sentence
encoder. In the paper, seeds are the terms that a person picks from the most
frequent ones; an int seeds takes all of them, as in its unsupervised variant. The
paper's PageRank lets the score of a word without links leak away, where here it
jumps to the seeds.
Initialize SemRe-Rank.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seeds
|
Union[List[str], int]
|
Terms known to belong to the domain, whose words are the seeds of PageRank, or a number ( z ) to take the ( z ) most frequent terms. |
200
|
rel_min
|
float
|
The cosine similarity above which words can be strongly related: 0.5 in the paper. |
0.5
|
rel_top
|
float
|
The fraction of the other words, the most similar, that a word can be strongly related to: 0.15 in the paper. |
0.15
|
encoder
|
Optional[Encoder]
|
A loaded encoder, or None to load |
None
|
model_name
|
str
|
The Hugging Face model of the sentence encoder. |
DEFAULT_MODEL
|
stopwords
|
Union[str, Iterable[str], None]
|
The words left out of the graph and of the words of the terms. |
'english'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
word_scores(docs, terms, seeds)
Score the words of the terms by their semantic importance.
cutoffs(vectors)
Find, for each word, the similarity of the least similar of its rel_top
most similar other words.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vectors
|
ndarray
|
The unit-length embedding of each word, one per row. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The cutoff of each word. |
rerank(results, docs)
Re-score the terms of an extractor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
ATEResults
|
The terms of the extractor. |
required |
docs
|
List[List[str]]
|
The words of each document of the corpus, as the extractor read them, so that the terms are sequences of them. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ATEResults |
ATEResults
|
The same terms and offsets, with the revised scores. |
is_word(word)
Whether a word can be a node: not a stopword, and with a letter or digit.
words(term)
The distinct words of a term or seed that can be nodes.
most_frequent(docs, terms, z)
staticmethod
Find the most frequent terms in the corpus.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs
|
List[List[str]]
|
The lower-case words of each document. |
required |
terms
|
List[str]
|
The lower-case terms. |
required |
z
|
int
|
The number of terms to return. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List[str]: The |
list[str]
|
ties in the order of |
embed(texts)
Embed texts, loading the encoder if it is not loaded yet.