( model_body: typing.Optional[sentence_transformers.SentenceTransformer.SentenceTransformer] = None model_head: typing.Union[setfit.modeling.SetFitHead, sklearn.linear_model._logistic.LogisticRegression, NoneType] = None multi_target_strategy: typing.Optional[str] = None normalize_embeddings: bool = False labels: typing.Optional[typing.List[str]] = None model_card_data: typing.Optional[setfit.model_card.SetFitModelCardData] = <factory> )
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']
( pretrained_model_name_or_path: typing.Union[str, pathlib.Path] force_download: bool = False resume_download: bool = False proxies: typing.Optional[typing.Dict] = None token: typing.Union[str, bool, NoneType] = None cache_dir: typing.Union[str, pathlib.Path, NoneType] = None local_files_only: bool = False revision: typing.Optional[str] = None **model_kwargs )
Parameters
Download a model from the Huggingface Hub and instantiate it.
( save_directory: typing.Union[str, pathlib.Path] config: typing.Optional[dict] = None repo_id: typing.Optional[str] = None push_to_hub: bool = False **kwargs )
Parameters
str
or Path
) —
Path to directory in which the model weights and configuration will be saved. dict
, optional) —
Model configuration specified as a key/value dictionary. 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.
kwargs —
Additional key word arguments passed along to the SetFitModel.push_to_hub()
method. Save weights in local directory.
( repo_id: str config: typing.Optional[dict] = None commit_message: str = 'Push model using huggingface_hub.' private: bool = False api_endpoint: typing.Optional[str] = None token: typing.Optional[str] = None branch: typing.Optional[str] = None create_pr: typing.Optional[bool] = None allow_patterns: typing.Union[str, typing.List[str], NoneType] = None ignore_patterns: typing.Union[str, typing.List[str], NoneType] = None delete_patterns: typing.Union[str, typing.List[str], NoneType] = None )
Parameters
str
) —
ID of the repository to push to (example: "username/my-model"
). dict
, optional) —
Configuration object to be saved alongside the model weights. str
, optional) —
Message to commit while pushing. bool
, optional, defaults to False
) —
Whether the repository created should be private. str
, optional) —
The API endpoint to use when pushing the model to the hub. 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. 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: typing.Union[str, typing.List[str]] batch_size: int = 32 as_numpy: bool = False use_labels: bool = True show_progress_bar: typing.Optional[bool] = 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: typing.Optional[str] = 'SetFit Model' )
Creates and saves a model card for a SetFit model.
( inputs: typing.List[str] batch_size: int = 32 show_progress_bar: typing.Optional[bool] = 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: typing.List[str] y_train: typing.Union[typing.List[int], typing.List[typing.List[int]]] num_epochs: int batch_size: typing.Optional[int] = None body_learning_rate: typing.Optional[float] = None head_learning_rate: typing.Optional[float] = None end_to_end: bool = False l2_weight: typing.Optional[float] = None max_length: typing.Optional[int] = 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: typing.Union[typing.Literal['body', 'head'], NoneType] = 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: typing.Union[str, typing.List[str]] batch_size: int = 32 as_numpy: bool = False use_labels: bool = True show_progress_bar: typing.Optional[bool] = 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: typing.Union[str, typing.List[str]] batch_size: int = 32 as_numpy: bool = False show_progress_bar: typing.Optional[bool] = 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: typing.Union[str, torch.device] ) → SetFitModel
Move this SetFitModel to device, and then return self. This method does not copy.
( component: typing.Union[typing.Literal['body', 'head'], NoneType] = None keep_body_frozen: typing.Optional[bool] = None )
Unfreeze the model body and/or the head, allowing further training on that component.
( in_features: typing.Optional[int] = None out_features: int = 2 temperature: float = 1.0 eps: float = 1e-05 bias: bool = True device: typing.Union[torch.device, str, NoneType] = 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: typing.Union[typing.Dict[str, torch.Tensor], torch.Tensor] temperature: typing.Optional[float] = 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: typing.Union[str, typing.List[str], NoneType] = None license: typing.Optional[str] = None tags: typing.Optional[typing.List[str]] = <factory> model_name: typing.Optional[str] = None model_id: typing.Optional[str] = None dataset_name: typing.Optional[str] = None dataset_id: typing.Optional[str] = None dataset_revision: typing.Optional[str] = None task_name: typing.Optional[str] = None st_id: typing.Optional[str] = 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: typing.Optional[str] = None spacy_model: typing.Optional[str] = None span_contexts: typing.Tuple[typing.Optional[int], typing.Optional[int]] = (None, None) force_download: bool = None resume_download: bool = None proxies: typing.Optional[typing.Dict] = None token: typing.Union[str, bool, NoneType] = None cache_dir: typing.Optional[str] = None local_files_only: bool = None use_differentiable_head: bool = None normalize_embeddings: bool = None **model_kwargs )
( save_directory: typing.Union[str, pathlib.Path] polarity_save_directory: typing.Union[str, pathlib.Path, NoneType] = None push_to_hub: bool = False **kwargs )
( model_body: typing.Optional[sentence_transformers.SentenceTransformer.SentenceTransformer] = None model_head: typing.Union[setfit.modeling.SetFitHead, sklearn.linear_model._logistic.LogisticRegression, NoneType] = None multi_target_strategy: typing.Optional[str] = None normalize_embeddings: bool = False labels: typing.Optional[typing.List[str]] = None model_card_data: typing.Optional[setfit.model_card.SetFitModelCardData] = <factory> spacy_model: str = 'en_core_web_lg' span_context: int = 0 )
( docs: typing.List[ForwardRef('Doc')] aspects_list: typing.List[typing.List[slice]] )
Get the Torch device that this model is on.
( pretrained_model_name_or_path: typing.Union[str, pathlib.Path] force_download: bool = False resume_download: bool = False proxies: typing.Optional[typing.Dict] = None token: typing.Union[str, bool, NoneType] = None cache_dir: typing.Union[str, pathlib.Path, NoneType] = None local_files_only: bool = False revision: typing.Optional[str] = None **model_kwargs )
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. bool
, optional, defaults to False
) —
Whether to delete incompletely received files. Will attempt to resume the download if such a file exists. 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: typing.Union[str, typing.List[str]] batch_size: int = 32 as_numpy: bool = False use_labels: bool = True show_progress_bar: typing.Optional[bool] = 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: typing.Optional[dict] = None commit_message: str = 'Push model using huggingface_hub.' private: bool = False api_endpoint: typing.Optional[str] = None token: typing.Optional[str] = None branch: typing.Optional[str] = None create_pr: typing.Optional[bool] = None allow_patterns: typing.Union[str, typing.List[str], NoneType] = None ignore_patterns: typing.Union[str, typing.List[str], NoneType] = None delete_patterns: typing.Union[str, typing.List[str], NoneType] = None )
Parameters
str
) —
ID of the repository to push to (example: "username/my-model"
). dict
, optional) —
Configuration object to be saved alongside the model weights. str
, optional) —
Message to commit while pushing. bool
, optional, defaults to False
) —
Whether the repository created should be private. str
, optional) —
The API endpoint to use when pushing the model to the hub. 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. 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: typing.Union[str, pathlib.Path] config: typing.Optional[dict] = None repo_id: typing.Optional[str] = None push_to_hub: bool = False **kwargs )
Parameters
str
or Path
) —
Path to directory in which the model weights and configuration will be saved. dict
, optional) —
Model configuration specified as a key/value dictionary. 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.
kwargs —
Additional key word arguments passed along to the SetFitModel.push_to_hub()
method. Save weights in local directory.
( device: typing.Union[str, torch.device] ) → SetFitModel
Move this SetFitModel to device, and then return self. This method does not copy.
( model_body: typing.Optional[sentence_transformers.SentenceTransformer.SentenceTransformer] = None model_head: typing.Union[setfit.modeling.SetFitHead, sklearn.linear_model._logistic.LogisticRegression, NoneType] = None multi_target_strategy: typing.Optional[str] = None normalize_embeddings: bool = False labels: typing.Optional[typing.List[str]] = None model_card_data: typing.Optional[setfit.model_card.SetFitModelCardData] = <factory> spacy_model: str = 'en_core_web_lg' span_context: int = 3 )
( docs: typing.List[ForwardRef('Doc')] aspects_list: typing.List[typing.List[slice]] )
Get the Torch device that this model is on.
( pretrained_model_name_or_path: typing.Union[str, pathlib.Path] force_download: bool = False resume_download: bool = False proxies: typing.Optional[typing.Dict] = None token: typing.Union[str, bool, NoneType] = None cache_dir: typing.Union[str, pathlib.Path, NoneType] = None local_files_only: bool = False revision: typing.Optional[str] = None **model_kwargs )
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. bool
, optional, defaults to False
) —
Whether to delete incompletely received files. Will attempt to resume the download if such a file exists. 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: typing.Union[str, typing.List[str]] batch_size: int = 32 as_numpy: bool = False use_labels: bool = True show_progress_bar: typing.Optional[bool] = 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: typing.Optional[dict] = None commit_message: str = 'Push model using huggingface_hub.' private: bool = False api_endpoint: typing.Optional[str] = None token: typing.Optional[str] = None branch: typing.Optional[str] = None create_pr: typing.Optional[bool] = None allow_patterns: typing.Union[str, typing.List[str], NoneType] = None ignore_patterns: typing.Union[str, typing.List[str], NoneType] = None delete_patterns: typing.Union[str, typing.List[str], NoneType] = None )
Parameters
str
) —
ID of the repository to push to (example: "username/my-model"
). dict
, optional) —
Configuration object to be saved alongside the model weights. str
, optional) —
Message to commit while pushing. bool
, optional, defaults to False
) —
Whether the repository created should be private. str
, optional) —
The API endpoint to use when pushing the model to the hub. 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. 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: typing.Union[str, pathlib.Path] config: typing.Optional[dict] = None repo_id: typing.Optional[str] = None push_to_hub: bool = False **kwargs )
Parameters
str
or Path
) —
Path to directory in which the model weights and configuration will be saved. dict
, optional) —
Model configuration specified as a key/value dictionary. 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.
kwargs —
Additional key word arguments passed along to the SetFitModel.push_to_hub()
method. Save weights in local directory.
( device: typing.Union[str, torch.device] ) → SetFitModel
Move this SetFitModel to device, and then return self. This method does not copy.