( model_body: Optional = None model_head: Union = None multi_target_strategy: Optional = None normalize_embeddings: bool = False labels: Optional = None model_card_data: Optional = None sentence_transformers_kwargs: Optional = None **kwargs )
A SetFit model with integration to the Hugging Face Hub.
Example:
>>> from setfit import SetFitModel
>>> model = SetFitModel.from_pretrained("tomaarsen/setfit-bge-small-v1.5-sst2-8-shot")
>>> model.predict([
... "It's a charming and often affecting journey.",
... "It's slow -- very, very slow.",
... "A sometimes tedious film.",
... ])
['positive', 'negative', 'negative']
( force_download: bool = False resume_download: Optional = None proxies: Optional = None token: Union = None cache_dir: Union = None local_files_only: bool = False revision: Optional = None **model_kwargs )
Parameters
Download a model from the Huggingface Hub and instantiate it.
( save_directory: Union config: Union = None repo_id: Optional = None push_to_hub: bool = False model_card_kwargs: Optional = None **push_to_hub_kwargs ) → str
or None
Parameters
str
or Path
) —
Path to directory in which the model weights and configuration will be saved. dict
or DataclassInstance
, optional) —
Model configuration specified as a key/value dictionary or a dataclass instance. bool
, optional, defaults to False
) —
Whether or not to push your model to the Huggingface Hub after saving it. str
, optional) —
ID of your repository on the Hub. Used only if push_to_hub=True
. Will default to the folder name if
not provided. Dict[str, Any]
, optional) —
Additional arguments passed to the model card template to customize the model card.
push_to_hub_kwargs —
Additional key word arguments passed along to the ~ModelHubMixin.push_to_hub
method. Returns
str
or None
url of the commit on the Hub if push_to_hub=True
, None
otherwise.
Save weights in local directory.
( repo_id: str config: Union = None commit_message: str = 'Push model using huggingface_hub.' private: bool = False token: Optional = None branch: Optional = None create_pr: Optional = None allow_patterns: Union = None ignore_patterns: Union = None delete_patterns: Union = None model_card_kwargs: Optional = None )
Parameters
str
) —
ID of the repository to push to (example: "username/my-model"
). dict
or DataclassInstance
, optional) —
Model configuration specified as a key/value dictionary or a dataclass instance. str
, optional) —
Message to commit while pushing. bool
, optional, defaults to False
) —
Whether the repository created should be private. str
, optional) —
The token to use as HTTP bearer authorization for remote files. By default, it will use the token
cached when running huggingface-cli login
. str
, optional) —
The git branch on which to push the model. This defaults to "main"
. boolean
, optional) —
Whether or not to create a Pull Request from branch
with that commit. Defaults to False
. List[str]
or str
, optional) —
If provided, only files matching at least one pattern are pushed. List[str]
or str
, optional) —
If provided, files matching any of the patterns are not pushed. List[str]
or str
, optional) —
If provided, remote files matching any of the patterns will be deleted from the repo. Dict[str, Any]
, optional) —
Additional arguments passed to the model card template to customize the model card. Upload model checkpoint to the Hub.
Use allow_patterns
and ignore_patterns
to precisely filter which files should be pushed to the hub. Use
delete_patterns
to delete existing remote files in the same commit. See upload_folder
reference for more
details.
( inputs: Union batch_size: int = 32 as_numpy: bool = False use_labels: bool = True show_progress_bar: Optional = None ) → Union[torch.Tensor, np.ndarray, List[str], int, str]
Parameters
Returns
Union[torch.Tensor, np.ndarray, List[str], int, str]
A list of string labels with equal length to the inputs if use_labels is True and SetFitModel.labels has been defined. Otherwise a vector with equal length to the inputs, denoting to which class each input is predicted to belong. If the inputs is a single string, then the output is a single label as well.
Predict the various classes.
Return a mapping from string labels to integer IDs.
Return a mapping from integer IDs to string labels.
( path: str model_name: Optional = 'SetFit Model' )
Creates and saves a model card for a SetFit model.
( inputs: List batch_size: int = 32 show_progress_bar: Optional = None ) → Union[torch.Tensor, np.ndarray]
Parameters
List[str]
) — The input sentences to embed. int
, defaults to 32
) — The batch size to use in encoding the sentences to embeddings.
Higher often means faster processing but higher memory usage. Optional[bool]
, defaults to None
) — Whether to show a progress bar while encoding. Returns
Union[torch.Tensor, np.ndarray]
A matrix with shape [INPUT_LENGTH, EMBEDDING_SIZE], as a torch Tensor if this model has a differentiable Torch head, or otherwise as a numpy array.
Convert input sentences to embeddings using the SentenceTransformer
body.
( x_train: List y_train: Union num_epochs: int batch_size: Optional = None body_learning_rate: Optional = None head_learning_rate: Optional = None end_to_end: bool = False l2_weight: Optional = None max_length: Optional = None show_progress_bar: bool = True )
Parameters
List[str]
) — A list of training sentences. Union[List[int], List[List[int]]]
) — A list of labels corresponding to the training sentences. int
) — The number of epochs to train for. int
, optional) — The batch size to use. float
, optional) — The learning rate for the SentenceTransformer
body
in the AdamW
optimizer. Disregarded if end_to_end=False
. float
, optional) — The learning rate for the differentiable torch head
in the AdamW
optimizer. bool
, defaults to False
) — If True, train the entire model end-to-end.
Otherwise, freeze the SentenceTransformer
body and only train the head. float
, optional) — The l2 weight for both the model body and head
in the AdamW
optimizer. int
, optional) — The maximum token length a tokenizer can generate. If not provided,
the maximum length for the SentenceTransformer
body is used. bool
, defaults to True
) — Whether to display a progress bar for the training
epochs and iterations. Train the classifier head, only used if a differentiable PyTorch head is used.
( component: Optional = None )
Freeze the model body and/or the head, preventing further training on that component until unfrozen.
Generate and return a model card string based on the model card data.
( inputs: Union batch_size: int = 32 as_numpy: bool = False use_labels: bool = True show_progress_bar: Optional = None ) → Union[torch.Tensor, np.ndarray, List[str], int, str]
Parameters
Returns
Union[torch.Tensor, np.ndarray, List[str], int, str]
A list of string labels with equal length to the inputs if use_labels is True and SetFitModel.labels has been defined. Otherwise a vector with equal length to the inputs, denoting to which class each input is predicted to belong. If the inputs is a single string, then the output is a single label as well.
Predict the various classes.
( inputs: Union batch_size: int = 32 as_numpy: bool = False show_progress_bar: Optional = None ) → Union[torch.Tensor, np.ndarray]
Parameters
Returns
Union[torch.Tensor, np.ndarray]
A matrix with shape [INPUT_LENGTH, NUM_CLASSES] denoting probabilities of predicting an input as a class. If the input is a string, then the output is a vector with shape [NUM_CLASSES,].
Predict the probabilities of the various classes.
Example:
>>> model = SetFitModel.from_pretrained(...)
>>> model.predict_proba(["What a boring display", "Exhilarating through and through", "I'm wowed!"])
tensor([[0.9367, 0.0633],
[0.0627, 0.9373],
[0.0890, 0.9110]], dtype=torch.float64)
>>> model.predict_proba("That was cool!")
tensor([0.8421, 0.1579], dtype=torch.float64)
( device: Union ) → SetFitModel
Move this SetFitModel to device, and then return self. This method does not copy.
( component: Optional = None keep_body_frozen: Optional = None )
Unfreeze the model body and/or the head, allowing further training on that component.
( in_features: Optional = None out_features: int = 2 temperature: float = 1.0 eps: float = 1e-05 bias: bool = True device: Union = None multitarget: bool = False )
Parameters
int
, optional) —
The embedding dimension from the output of the SetFit body. If None
, defaults to LazyLinear
. int
, defaults to 2
) —
The number of targets. If set out_features
to 1 for binary classification, it will be changed to 2 as 2-class classification. float
, defaults to 1.0
) —
A logits’ scaling factor. Higher values make the model less confident and lower values make
it more confident. float
, defaults to 1e-5
) —
A value for numerical stability when scaling logits. bool
, optional, defaults to True
) —
Whether to add bias to the head. torch.device
, str, optional) —
The device the model will be sent to. If None
, will check whether GPU is available. bool
, defaults to False
) —
Enable multi-target classification by making out_features
binary predictions instead
of a single multinomial prediction. A SetFit head that supports multi-class classification for end-to-end training. Binary classification is treated as 2-class classification.
To be compatible with Sentence Transformers, we inherit Dense
from:
https://github.com/UKPLab/sentence-transformers/blob/master/sentence_transformers/models/Dense.py
( features: Union temperature: Optional = None )
Parameters
Dict[str, torch.Tensor]
or torch.Tensor) -- The embeddings from the encoder. If using
dict` format,
make sure to store embeddings under the key: ‘sentence_embedding’
and the outputs will be under the key: ‘prediction’. float
, optional) —
A logits’ scaling factor. Higher values make the model less
confident and lower values make it more confident.
Will override the temperature given during initialization. SetFitHead can accept embeddings in:
dict
) from Sentence-Transformers.torch.Tensor
.( language: Union = None license: Optional = None tags: Optional = <factory> model_name: Optional = None model_id: Optional = None dataset_name: Optional = None dataset_id: Optional = None dataset_revision: Optional = None task_name: Optional = None st_id: Optional = None )
Parameters
A dataclass storing data used in the model card.
Install codecarbon
to automatically track carbon emission usage and
include it in your model cards.
Example:
>>> model = SetFitModel.from_pretrained(
... "sentence-transformers/paraphrase-mpnet-base-v2",
... labels=["negative", "positive"],
... # Model card variables
... model_card_data=SetFitModelCardData(
... model_id="tomaarsen/setfit-paraphrase-mpnet-base-v2-sst2",
... dataset_name="SST2",
... dataset_id="sst2",
... license="apache-2.0",
... language="en",
... ),
... )
( aspect_extractor: AspectExtractor aspect_model: AspectModel polarity_model: PolarityModel )
( model_id: str polarity_model_id: Optional = None spacy_model: Optional = None span_contexts: Tuple = (None, None) force_download: bool = None resume_download: bool = None proxies: Optional = None token: Union = None cache_dir: Optional = None local_files_only: bool = None use_differentiable_head: bool = None normalize_embeddings: bool = None **model_kwargs )
( inputs: Union ) → Union[List[Dict[str, Any]], Dataset]
Parameters
Returns
Union[List[Dict[str, Any]], Dataset]
Either a list of dictionaries with keys span and polarity if the input was a sentence or a list of sentences, or a dataset with columns text, span, ordinal, and pred_polarity.
Predicts aspects & their polarities of the given inputs.
Example:
>>> from setfit import AbsaModel
>>> model = AbsaModel.from_pretrained(
... "tomaarsen/setfit-absa-bge-small-en-v1.5-restaurants-aspect",
... "tomaarsen/setfit-absa-bge-small-en-v1.5-restaurants-polarity",
... )
>>> model.predict("The food and wine are just exquisite.")
[{'span': 'food', 'polarity': 'positive'}, {'span': 'wine', 'polarity': 'positive'}]
>>> from setfit import AbsaModel
>>> from datasets import load_dataset
>>> model = AbsaModel.from_pretrained(
... "tomaarsen/setfit-absa-bge-small-en-v1.5-restaurants-aspect",
... "tomaarsen/setfit-absa-bge-small-en-v1.5-restaurants-polarity",
... )
>>> dataset = load_dataset("tomaarsen/setfit-absa-semeval-restaurants", split="train")
>>> model.predict(dataset)
Dataset({
features: ['text', 'span', 'label', 'ordinal', 'pred_polarity'],
num_rows: 3693
})
( save_directory: Union polarity_save_directory: Union = None push_to_hub: bool = False **kwargs )
Get the Torch device that this model is on.
( )
Parameters
str
, Path
) —model_id
(string) of a model hosted on the Hub, e.g. bigscience/bloom
.directory
containing model weights saved using
save_pretrained, e.g., ../path/to/my_model_directory/
.str
, optional) —
Revision of the model on the Hub. Can be a branch name, a git tag or any commit id.
Defaults to the latest commit on main
branch. bool
, optional, defaults to False
) —
Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding
the existing cache. Dict[str, str]
, optional) —
A dictionary of proxy servers to use by protocol or endpoint, e.g., {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on every request. str
or bool
, optional) —
The token to use as HTTP bearer authorization for remote files. By default, it will use the token
cached when running huggingface-cli login
. str
, Path
, optional) —
Path to the folder where cached files are stored. bool
, optional, defaults to False
) —
If True
, avoid downloading the file and return the path to the local cached file if it exists. List[str]
, optional) —
If the labels are integers ranging from 0
to num_classes-1
, then these labels indicate
the corresponding labels. SetFitModelCardData
, optional) —
A SetFitModelCardData
instance storing data such as model language, license, dataset name,
etc. to be used in the automatically generated model cards. SetFitModelCardData
, optional) —
A SetFitModelCardData
instance storing data such as model language, license, dataset name,
etc. to be used in the automatically generated model cards. bool
, optional) —
Whether to load SetFit using a differentiable (i.e., Torch) head instead of Logistic Regression. bool
, optional) —
Whether to apply normalization on the embeddings produced by the Sentence Transformer body. int
, defaults to 0
) —
The number of words before and after the span candidate that should be prepended to the full sentence.
By default, 0 for Aspect models and 3 for Polarity models. Union[torch.device, str]
, optional) —
The device on which to load the SetFit model, e.g. "cuda:0"
, "mps"
or torch.device("cuda")
. Download a model from the Huggingface Hub and instantiate it.
( inputs: Union batch_size: int = 32 as_numpy: bool = False use_labels: bool = True show_progress_bar: Optional = None ) → Union[torch.Tensor, np.ndarray, List[str], int, str]
Parameters
Returns
Union[torch.Tensor, np.ndarray, List[str], int, str]
A list of string labels with equal length to the inputs if use_labels is True and SetFitModel.labels has been defined. Otherwise a vector with equal length to the inputs, denoting to which class each input is predicted to belong. If the inputs is a single string, then the output is a single label as well.
Predict the various classes.
( repo_id: str config: Union = None commit_message: str = 'Push model using huggingface_hub.' private: bool = False token: Optional = None branch: Optional = None create_pr: Optional = None allow_patterns: Union = None ignore_patterns: Union = None delete_patterns: Union = None model_card_kwargs: Optional = None )
Parameters
str
) —
ID of the repository to push to (example: "username/my-model"
). dict
or DataclassInstance
, optional) —
Model configuration specified as a key/value dictionary or a dataclass instance. str
, optional) —
Message to commit while pushing. bool
, optional, defaults to False
) —
Whether the repository created should be private. str
, optional) —
The token to use as HTTP bearer authorization for remote files. By default, it will use the token
cached when running huggingface-cli login
. str
, optional) —
The git branch on which to push the model. This defaults to "main"
. boolean
, optional) —
Whether or not to create a Pull Request from branch
with that commit. Defaults to False
. List[str]
or str
, optional) —
If provided, only files matching at least one pattern are pushed. List[str]
or str
, optional) —
If provided, files matching any of the patterns are not pushed. List[str]
or str
, optional) —
If provided, remote files matching any of the patterns will be deleted from the repo. Dict[str, Any]
, optional) —
Additional arguments passed to the model card template to customize the model card. Upload model checkpoint to the Hub.
Use allow_patterns
and ignore_patterns
to precisely filter which files should be pushed to the hub. Use
delete_patterns
to delete existing remote files in the same commit. See upload_folder
reference for more
details.
( save_directory: Union config: Union = None repo_id: Optional = None push_to_hub: bool = False model_card_kwargs: Optional = None **push_to_hub_kwargs ) → str
or None
Parameters
str
or Path
) —
Path to directory in which the model weights and configuration will be saved. dict
or DataclassInstance
, optional) —
Model configuration specified as a key/value dictionary or a dataclass instance. bool
, optional, defaults to False
) —
Whether or not to push your model to the Huggingface Hub after saving it. str
, optional) —
ID of your repository on the Hub. Used only if push_to_hub=True
. Will default to the folder name if
not provided. Dict[str, Any]
, optional) —
Additional arguments passed to the model card template to customize the model card.
push_to_hub_kwargs —
Additional key word arguments passed along to the ~ModelHubMixin.push_to_hub
method. Returns
str
or None
url of the commit on the Hub if push_to_hub=True
, None
otherwise.
Save weights in local directory.
( device: Union ) → SetFitModel
Move this SetFitModel to device, and then return self. This method does not copy.
Get the Torch device that this model is on.
( )
Parameters
str
, Path
) —model_id
(string) of a model hosted on the Hub, e.g. bigscience/bloom
.directory
containing model weights saved using
save_pretrained, e.g., ../path/to/my_model_directory/
.str
, optional) —
Revision of the model on the Hub. Can be a branch name, a git tag or any commit id.
Defaults to the latest commit on main
branch. bool
, optional, defaults to False
) —
Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding
the existing cache. Dict[str, str]
, optional) —
A dictionary of proxy servers to use by protocol or endpoint, e.g., {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
. The proxies are used on every request. str
or bool
, optional) —
The token to use as HTTP bearer authorization for remote files. By default, it will use the token
cached when running huggingface-cli login
. str
, Path
, optional) —
Path to the folder where cached files are stored. bool
, optional, defaults to False
) —
If True
, avoid downloading the file and return the path to the local cached file if it exists. List[str]
, optional) —
If the labels are integers ranging from 0
to num_classes-1
, then these labels indicate
the corresponding labels. SetFitModelCardData
, optional) —
A SetFitModelCardData
instance storing data such as model language, license, dataset name,
etc. to be used in the automatically generated model cards. SetFitModelCardData
, optional) —
A SetFitModelCardData
instance storing data such as model language, license, dataset name,
etc. to be used in the automatically generated model cards. bool
, optional) —
Whether to load SetFit using a differentiable (i.e., Torch) head instead of Logistic Regression. bool
, optional) —
Whether to apply normalization on the embeddings produced by the Sentence Transformer body. int
, defaults to 0
) —
The number of words before and after the span candidate that should be prepended to the full sentence.
By default, 0 for Aspect models and 3 for Polarity models. Union[torch.device, str]
, optional) —
The device on which to load the SetFit model, e.g. "cuda:0"
, "mps"
or torch.device("cuda")
. Download a model from the Huggingface Hub and instantiate it.
( inputs: Union batch_size: int = 32 as_numpy: bool = False use_labels: bool = True show_progress_bar: Optional = None ) → Union[torch.Tensor, np.ndarray, List[str], int, str]
Parameters
Returns
Union[torch.Tensor, np.ndarray, List[str], int, str]
A list of string labels with equal length to the inputs if use_labels is True and SetFitModel.labels has been defined. Otherwise a vector with equal length to the inputs, denoting to which class each input is predicted to belong. If the inputs is a single string, then the output is a single label as well.
Predict the various classes.
( repo_id: str config: Union = None commit_message: str = 'Push model using huggingface_hub.' private: bool = False token: Optional = None branch: Optional = None create_pr: Optional = None allow_patterns: Union = None ignore_patterns: Union = None delete_patterns: Union = None model_card_kwargs: Optional = None )
Parameters
str
) —
ID of the repository to push to (example: "username/my-model"
). dict
or DataclassInstance
, optional) —
Model configuration specified as a key/value dictionary or a dataclass instance. str
, optional) —
Message to commit while pushing. bool
, optional, defaults to False
) —
Whether the repository created should be private. str
, optional) —
The token to use as HTTP bearer authorization for remote files. By default, it will use the token
cached when running huggingface-cli login
. str
, optional) —
The git branch on which to push the model. This defaults to "main"
. boolean
, optional) —
Whether or not to create a Pull Request from branch
with that commit. Defaults to False
. List[str]
or str
, optional) —
If provided, only files matching at least one pattern are pushed. List[str]
or str
, optional) —
If provided, files matching any of the patterns are not pushed. List[str]
or str
, optional) —
If provided, remote files matching any of the patterns will be deleted from the repo. Dict[str, Any]
, optional) —
Additional arguments passed to the model card template to customize the model card. Upload model checkpoint to the Hub.
Use allow_patterns
and ignore_patterns
to precisely filter which files should be pushed to the hub. Use
delete_patterns
to delete existing remote files in the same commit. See upload_folder
reference for more
details.
( save_directory: Union config: Union = None repo_id: Optional = None push_to_hub: bool = False model_card_kwargs: Optional = None **push_to_hub_kwargs ) → str
or None
Parameters
str
or Path
) —
Path to directory in which the model weights and configuration will be saved. dict
or DataclassInstance
, optional) —
Model configuration specified as a key/value dictionary or a dataclass instance. bool
, optional, defaults to False
) —
Whether or not to push your model to the Huggingface Hub after saving it. str
, optional) —
ID of your repository on the Hub. Used only if push_to_hub=True
. Will default to the folder name if
not provided. Dict[str, Any]
, optional) —
Additional arguments passed to the model card template to customize the model card.
push_to_hub_kwargs —
Additional key word arguments passed along to the ~ModelHubMixin.push_to_hub
method. Returns
str
or None
url of the commit on the Hub if push_to_hub=True
, None
otherwise.
Save weights in local directory.
( device: Union ) → SetFitModel
Move this SetFitModel to device, and then return self. This method does not copy.