Skip to content

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 SupervisedTermExtractor.METHODS ('roger', 'features', 'token-classification', 'llm').

required
model_name str

Hugging Face model name for token classification, or the directory of a model saved with save.

'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 predict_proba (only for 'features').

'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 TermExtractor (only for 'features').

'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 LLMClient, such as a termxtract.llm.OpenAIClient, or the name of a model served at the OPENAI_BASE_URL environment variable.

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 termxtract.supervised.llm.TEMPLATES, from 1 to 8, or an (instruction, input marker, output marker) tuple (only for 'llm').

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 termxtract.embeddings.Encoder() (only for 'llm').

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 termxtract.stopwords.STOPWORD_LISTS, such as "english" (the default) or an ISO 639-1 code such as "fr", a list of words, or None to keep every term.

'english'
words_layer Optional[str]

For Teanga input, the span layer holding the words: None (the default) for words or, if the corpus has no words layer, tokens.

None
lemma_layer Optional[str]

For Teanga input, a sequence layer, based on the words layer, holding the lemma of each word, such as lemma. If given, each term is given by the lemmas of its words, so inflected forms such as "cell" and "cells" are one term, as for TermExtractor. Roger also computes its measures over the lemmas, while token classification tags the words as written. Labels given to fit are matched to the lemmas, so write them as lemmas; gold terms of terms_layer are read by their lemmas. None (the default) gives terms as written.

None
terms_layer str

For Teanga input, the span layer of gold terms that fit trains on when it is given no labels: terms by default, as in the corpora of termxtract.datasets.

GOLD_LAYER
sentences_layer Optional[str]

For Teanga input, the span layer of the sentences: None (the default) for sentences or, if the corpus has no such layer, splitting after each word that is ".", "!" or "?" (only for 'token-classification').

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 "<ADJ|NOUN>*<NOUN>", or use the name of a pattern in termxtract.pos.POS_PATTERNS, such as "noun_phrase". None (the default) keeps every term. Scores are unchanged, except for 'features', whose candidates are only the occurrences that match, as for TermExtractor, and which also takes "learned" for the tag sequences of the terms of the training corpus.

None
pos_layer Optional[str]

The part-of-speech layer used by pos_pattern, based on the words layer: None (the default) for upos or, if the corpus has no upos layer, pos.

None

Raises:

Type Description
ValueError

If the method is unknown, or pos_pattern is "learned" for a method other than 'features'.

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 terms_layer: token classification tags each occurrence of them, Roger takes them as the terms, and 'llm' gives each training sentence with its gold terms as a demonstration.

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 patience can stop training early.

None

Returns:

Name Type Description
SupervisedTermExtractor SupervisedTermExtractor

This extractor, trained, so that fit(...).predict(...)

SupervisedTermExtractor

can be chained.

Raises:

Type Description
ValueError

If the corpus is neither a Teanga Corpus nor a list of strings, pos_pattern is set and the corpus is a list of strings, a list of strings is given no labels, or validation is given for Roger.

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 pos_pattern is set and the corpus is a list of strings.

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 terms_layer, as for fit.

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 FeatureTermExtractor.feature_importances gives them.

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.