TextEmbedder#
- class TextEmbedder(model='all-mpnet-base-v2', normalize=True, batch_size=32, device=None)[source]#
Bases:
TransformerMixin,BaseEstimatorRepresentation of texts as the embeddings of a sentence transformer (sentence-transformers), the representation used for the texts in the PivotTree paper (
all-mpnet-base-v2).- Parameters:
model (str, default='all-mpnet-base-v2') – Name or path of a model of sentence-transformers, e.g.
'all-MiniLM-L6-v2'(smaller and faster).normalize (bool, default=True) – Whether the embeddings have unit length: then the Euclidean distance orders the texts as the cosine distance.
batch_size (int, default=32) – Number of texts processed at once.
device (str, default=None) – Torch device, e.g.
'cpu'or'cuda'. If None, CUDA, Apple MPS or the CPU, the first available.
- Variables:
encoder (sentence_transformers.SentenceTransformer) – The model.
n_features_out (int) – Length of the embedding of a text.
See also
ImageEmbedderthe same for images.
Examples
>>> import numpy as np >>> from RuleTree import RuleTreeClassifier >>> from RuleTree.stumps.classification import PivotTreeStumpClassifier >>> from RuleTree.utils.embeddings import TextEmbedder >>> texts = np.array(["The striker scored a goal.", "The chef baked bread.", "The team won.", ... "Add garlic and oil."]) >>> stump = PivotTreeStumpClassifier(embedder=TextEmbedder("all-MiniLM-L6-v2")) >>> model = RuleTreeClassifier(max_depth=1, base_stumps=stump) >>> model = model.fit(X_txt=texts, y=["sport", "cooking", "sport", "cooking"])
- fit(X=None, y=None)[source]#
Load the model (it is downloaded the first time). The texts are not used.
- Parameters:
X (array-like of str, default=None) – Not used.
y (numpy.ndarray, default=None) – Not used.
- Returns:
self
- Return type:
- transform(X)[source]#
Embeddings of the texts.
- Parameters:
X (array-like of str of shape (n_texts,)) – Texts.
- Returns:
X_embedded
- Return type:
numpy.ndarray of shape (n_texts, n_features_out)