SupervisedTermExtractor
Entry point for the supervised methods, which are trained from a dictionary of labelled candidate terms.
SupervisedTermExtractor(method, model_name='xlm-roberta-base', n=None, population_size=20, offspring_size=100, generations=100, runs=21, random_state=None, max_negatives=10000, patience=None, n_jobs=None, classifier='random_forest', threshold=0.5, reference_corpus=None, min_frequency=1, word_pattern='alphanumeric', batch_size=8, epochs=3, learning_rate=2e-05, max_length=512, language='en', client=None, k=5, template=5, selection='knn', encoder=None, stopwords='english', words_layer=None, lemma_layer=None, terms_layer=GOLD_LAYER, sentences_layer=None, pos_pattern=None, pos_layer=None)
A wrapper class for selecting the supervised term extraction method.
SupervisedTermExtractor.METHODS maps each method name to a function returning its
extractor class and the parameters passed to it, so
list(SupervisedTermExtractor.METHODS) lists the available methods.
Initialize the TermExtractor with the desired supervised method and parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
The term extraction method, one of the keys of |
required |
model_name
|
str
|
Hugging Face model name for token classification, or the
directory of a model saved with |
'xlm-roberta-base'
|
n
|
Optional[int]
|
Maximum length of n-grams to consider, or None for the method's default: 2 for 'roger', 4 for 'features', 6 for 'token-classification' and 10 for 'llm', which drops longer terms. |
None
|
population_size
|
int
|
Number of parents in each generation (only for 'roger'). |
20
|
offspring_size
|
int
|
Number of offspring in each generation (only for 'roger'). |
100
|
generations
|
int
|
Number of generations in each run (only for 'roger'). |
100
|
runs
|
int
|
Number of independent runs to combine (only for 'roger'). |
21
|
random_state
|
Optional[int]
|
Seed for reproducible scores, or for 'features' and 'token-classification' for reproducible training, or for 'llm' for the random selection of demonstrations. |
None
|
max_negatives
|
Optional[int]
|
Train on at most this many candidates labelled 0, sampled for each run (only for 'roger'). |
10000
|
patience
|
Optional[int]
|
For 'roger', stop a run when it has not improved for this many generations; for 'token-classification', stop training when the F1 on the validation set has not improved for this many epochs. |
None
|
n_jobs
|
Optional[int]
|
Number of runs of 'roger', or trees of the random forest of 'features', trained in parallel, or of prompts of 'llm' sent at once, -1 for one per CPU. |
None
|
classifier
|
Union[str, Any]
|
"random_forest" (the default) or an unfitted
scikit-learn classifier with |
'random_forest'
|
threshold
|
Optional[float]
|
Keep the candidates that the classifier gives at least this probability of being a term, or None to rank every candidate (only for 'features'; 0.5 by default). |
0.5
|
reference_corpus
|
Optional[Union[Corpus, List[str], List[...]]]
|
A general-language reference corpus, of the same type as the corpora, whose comparison with them by relevance, domain pertinence and weirdness adds features (only for 'features'). |
None
|
min_frequency
|
int
|
Drop candidates that occur fewer times in the corpus (only for 'features'). |
1
|
word_pattern
|
Optional[str]
|
Drop candidates with a word that does not fully
match this regular expression or named pattern, as for |
'alphanumeric'
|
batch_size
|
int
|
Training batch size (only for 'token-classification'). |
8
|
epochs
|
int
|
Number of training epochs (only for 'token-classification'). |
3
|
learning_rate
|
float
|
Learning rate (only for 'token-classification'). |
2e-05
|
max_length
|
int
|
Maximum sequence length (only for 'token-classification'). |
512
|
language
|
str
|
Language code for tokenization (only for 'token-classification'). |
'en'
|
client
|
Union[LLMClient, str, None]
|
The large language model of 'llm': an
|
None
|
k
|
int
|
The number of demonstrations, training sentences with their terms, in each prompt (only for 'llm'). |
5
|
template
|
Union[int, Tuple[str, str, str]]
|
The number of a prompt template
of |
5
|
selection
|
str
|
"knn" (the default) for the demonstrations most similar to each sentence, or "random" (only for 'llm'). |
'knn'
|
encoder
|
Optional[Encoder]
|
The sentence encoder of the "knn" selection, or
None for |
None
|
stopwords
|
Union[str, Iterable[str], None]
|
Drop extracted terms that start or end
with a stopword: the name of a built-in list in
|
'english'
|
words_layer
|
Optional[str]
|
For Teanga input, the span layer holding the words:
None (the default) for |
None
|
lemma_layer
|
Optional[str]
|
For Teanga input, a sequence layer, based on the
words layer, holding the lemma of each word, such as |
None
|
terms_layer
|
str
|
For Teanga input, the span layer of gold terms that
|
GOLD_LAYER
|
sentences_layer
|
Optional[str]
|
For Teanga input, the span layer of the
sentences: None (the default) for |
None
|
pos_pattern
|
Optional[str]
|
For Teanga input, keep only the terms whose
part-of-speech tags match this pattern in at least one occurrence. Tags are
written in angle brackets, as in |
None
|
pos_layer
|
Optional[str]
|
The part-of-speech layer used by |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the method is unknown, or |
ImportError
|
If the method is 'token-classification' and the optional 'transformers' dependencies are not installed. |
fit(corpus, labels=None, validation=None)
Train the method on a corpus.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
corpus
|
Union[Corpus, List[str]]
|
Teanga Corpus object or list of strings. |
required |
labels
|
Optional[Dict[str, int]]
|
Dictionary with terms as keys and binary
labels {0, 1}. Roger needs examples of both; given only terms, it counts
every other candidate of the corpus as a non-term. None, for a Teanga
corpus, trains on the gold terms of |
None
|
validation
|
Optional[Union[Corpus, List[str]]]
|
For 'token-classification',
a corpus of the same kind, labelled in the same way, to compute the F1
of the tagged terms on after each epoch. The model of the best epoch is
kept, and |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
SupervisedTermExtractor |
SupervisedTermExtractor
|
This extractor, trained, so that |
SupervisedTermExtractor
|
can be chained. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the corpus is neither a Teanga Corpus nor a list of strings,
|
predict(corpus)
Extract terms from a corpus with the trained method.
The corpus can differ from the one the method was trained on, for example another domain or another split of a dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
corpus
|
Union[Corpus, List[str]]
|
Teanga Corpus object or list of strings. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ATEResults |
ATEResults
|
The terms of each document with their scores, and their offsets |
ATEResults
|
for a Teanga corpus. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the corpus is neither a Teanga Corpus nor a list of strings,
or |
extract(corpus, labels=None)
Train the method on a corpus and extract the terms of that same corpus.
To extract terms from another corpus, use fit and then predict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
corpus
|
Union[Corpus, List[str]]
|
Teanga Corpus object or list of strings. |
required |
labels
|
Optional[Dict[str, int]]
|
Dictionary with terms as keys and binary
labels {0, 1}, or None to train on the gold terms of |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ATEResults |
ATEResults
|
Object containing extracted terms with scores. |
feature_importances()
Get the importance of each feature to a trained 'features' classifier, to see which scores matter for a domain.
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Dict[str, float]: The importance of each feature, from the most to the |
dict[str, float]
|
least important, as |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the method is not 'features', or its classifier has not been trained or has no feature importances. |
save(directory)
Save a trained token-classification model, to pass the directory as
model_name to extract terms without training again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
Union[str, Path]
|
The directory to save to. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the method is not 'token-classification'. |
RuntimeError
|
If the model has not been trained. |