Embeddings
Sentence embeddings, used by EmbedRank. They need the
optional transformers dependencies: pip install 'termxtract[transformers]'.
embeddings
DEFAULT_MODEL = 'sentence-transformers/all-MiniLM-L6-v2'
module-attribute
The default sentence encoder: a small English model.
Encoder(model_name=DEFAULT_MODEL, batch_size=32, max_length=256, device=None)
A sentence encoder: a Hugging Face model whose token embeddings are averaged over
each text, as in Sentence-BERT models such as all-MiniLM-L6-v2.
Texts are given as lists of words. Embeddings are normalised to unit length, so the dot product of two embeddings is their cosine similarity. The embeddings of texts without masked words are cached, so a text is only encoded once.
Load the encoder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name
|
str
|
A Hugging Face model with a fast tokenizer that has a mask token. |
DEFAULT_MODEL
|
batch_size
|
int
|
The number of texts encoded at once. |
32
|
max_length
|
int
|
The maximum number of tokens of a text, including the
special tokens. Longer texts are truncated; use |
256
|
device
|
Optional[str]
|
The torch device, or None for CUDA if it is available and the CPU otherwise. |
None
|
Raises:
| Type | Description |
|---|---|
ImportError
|
If the optional 'transformers' dependencies are missing. |
chunks(words)
Split a text into chunks that fit in max_length tokens, between words.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
words
|
List[str]
|
The words of the text. |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[int, int]]
|
List[Tuple[int, int]]: The index of the first word of each chunk and of the |
list[tuple[int, int]]
|
word after its last. A word too long to fit is a chunk of its own, and is |
list[tuple[int, int]]
|
truncated when it is encoded. |
encode(texts, masks=None)
Embed texts, with some of their words masked.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
texts
|
List[List[str]]
|
The words of each text. |
required |
masks
|
Optional[List[Set[int]]]
|
For each text, the indices of the words whose tokens are replaced by the mask token, or None to mask nothing. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The unit-length embedding of each text, one per row. |