TextRank, SingleRank and PositionRank
Used by TermExtractor with method="textrank".
TextRankTermExtractor(threshold=None, n=3, variant='plain', window_size=None, graph='corpus', stopwords='english', words_layer=None, lemma_layer=None, min_frequency=1, word_pattern='alphanumeric', pos_pattern=None, pos_layer=None)
Bases: ContextTermExtractor
Graph-based ranking: TextRank (Mihalcea & Tarau, 2004), SingleRank (Wan & Xiao, 2008) and PositionRank (Florescu & Caragea, 2017).
The words are the nodes of a graph, in which two words are linked if they occur
within window_size words of each other. Each word is scored by PageRank over the
graph, with a damping factor of 0.85, and each candidate by the sum of the scores of
its words. The variants differ in the graph:
- "plain", TextRank: the edges are unweighted.
- "single", SingleRank: each edge is weighted by how often its words co-occur.
- "position", PositionRank: the edges are weighted as in SingleRank, and the random walk jumps to each word in proportion to ( \sum 1 / p ) over its occurrences, where ( p ) is the position of the occurrence in its document, counting from 1, so words that occur early score better.
The nodes are the words that are not stopwords, that match word_pattern and, for
a Teanga corpus with a part-of-speech layer, whose tag is in NODE_TAGS: nouns and
adjectives. Other words, such as "of" in "degree of freedom", take up places in the
window but score 0. Windows cross sentences but not documents, and in a Teanga
corpus each punctuation token of the words layer takes up a place, as in pke.
By default, one graph is built over the whole corpus, so a term has the same score
in every document. With graph="document", each document has a graph of its own,
as in the papers, which rank the keyphrases of a single document.
The papers rank only the longest sequences of nouns and adjectives (TextRank and
SingleRank) or noun phrases (PositionRank). Here the candidates are those of the
other methods, set by n, stopwords, word_pattern, pos_pattern and
min_frequency, and TextRank's joining of adjacent top-ranked words is not done.
Given the same words, nodes and candidates, the scores are those of pke's
TextRank, SingleRank and PositionRank, run until PageRank converges: pke stops
it at networkx's tolerance of 1e-4, where the scores of low-ranked words can still
be several percent off.
Initialize the graph-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
|
"plain" for TextRank, "single" for SingleRank or "position" for PositionRank. |
'plain'
|
window_size
|
Optional[int]
|
Link the words that occur within this many
words of each other, or None for the variant's default in
|
None
|
graph
|
str
|
"corpus" to build one graph over the whole corpus, or "document" to build one for each document. |
'corpus'
|
stopwords
|
Union[str, Iterable[str], None]
|
Drop candidates that start or end
with a stopword, and leave stopwords out of the graph: 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 node and 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"), and leave such words out of the graph, 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 |
document_scores(docs, occurrences, tags=None)
Score the candidates of each document, over the graph of the corpus or, with
graph="document", of the document.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs
|
List[List[str]]
|
The words of each document. |
required |
occurrences
|
List[List[Tuple[str, int, int]]]
|
The occurrences of the
candidates in each document, from |
required |
tags
|
Optional[List[List[str]]]
|
The part-of-speech tag of each word of each
document, to restrict the nodes to |
None
|
Returns:
| Type | Description |
|---|---|
list[dict[str, float]]
|
List[Dict[str, float]]: The score of each candidate of each document. |
corpus_scores(docs, occurrences, tags=None)
Score the candidates over one graph of the given documents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs
|
List[List[str]]
|
The words of each document. |
required |
occurrences
|
List[List[Tuple[str, int, int]]]
|
The occurrences of the
candidates in each document, from |
required |
tags
|
Optional[List[List[str]]]
|
The part-of-speech tag of each word of each
document, to restrict the nodes to |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Dict[str, float]: The score of each candidate. |
extract_terms_teanga(corpus)
Extract terms from a Teanga corpus.
extract_terms_strings(corpus)
Extract terms from a plain list of strings.
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. |
content_words(docs, tags=None)
Find the words that can be context 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, or None. |
None
|
Returns:
| Type | Description |
|---|---|
list[list[bool]]
|
List[List[bool]]: For each word of each document, whether it is a content |
list[list[bool]]
|
word. |
cooccurrences(docs, occurrences, content, terms, words)
Count how often each content word occurs within window_size words of each
occurrence of each candidate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs
|
List[List[str]]
|
The words of each document. |
required |
occurrences
|
List[List[Tuple[str, int, int]]]
|
The occurrences of the candidates in each document. |
required |
content
|
List[List[bool]]
|
Which words are content words, from
|
required |
terms
|
Optional[Set[str]]
|
The candidates to count for, or None for every candidate. |
required |
words
|
Optional[Set[str]]
|
The content words to count, or None for every content word. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Counter[str]]
|
Dict[str, Counter[str]]: For each candidate, how often each word occurs in |
dict[str, Counter[str]]
|
its context. |
pagerank(weights, personalization)
Score the nodes of an undirected graph by PageRank, by power iteration.
The random walk follows an edge with probability DAMPING, choosing it in
proportion to its weight, and otherwise jumps to a node chosen by personalization.
From a node with no edges, it always jumps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
csr_matrix
|
The symmetric matrix of the weights of the edges. |
required |
personalization
|
ndarray
|
The probability of jumping to each node. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The score of each node. The scores sum to 1. |