SetFit 文档

主要类

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

主要类

SetFitModel

class setfit.SetFitModel

< >

( 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] = None sentence_transformers_kwargs: typing.Optional[typing.Dict] = None **kwargs )

一个与 Hugging Face Hub 集成的 SetFit 模型。

示例

>>> 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']

from_pretrained

< >

( force_download: bool = False resume_download: typing.Optional[bool] = None proxies: typing.Optional[typing.Dict] = None token: typing.Union[bool, str, NoneType] = None cache_dir: typing.Union[str, pathlib.Path, NoneType] = None local_files_only: bool = False revision: typing.Optional[str] = None **model_kwargs )

参数

  • pretrained_model_name_or_path (str, Path) —
    • 可以是 Hub 上托管的模型的 model_id(字符串),例如 bigscience/bloom
    • 或者是指向目录的路径,该目录包含使用 [~transformers.PreTrainedModel.save_pretrained] 保存的模型权重,例如 ../path/to/my_model_directory/
  • revision (str, optional) — Hub 上模型的修订版本。可以是分支名称、git 标签或任何提交 ID。默认为 main 分支上的最新提交。
  • force_download (bool, optional, defaults to False) — 是否强制(重新)从 Hub 下载模型权重和配置文件,覆盖现有缓存。
  • proxies (Dict[str, str], optional) — 要按协议或端点使用的代理服务器字典,例如,{‘http’: ‘foo.bar:3128’, ‘http://hostname’: ‘foo.bar:4012’}。代理用于每个请求。
  • token (strbool, optional) — 用作远程文件的 HTTP Bearer 授权的令牌。默认情况下,它将使用运行 huggingface-cli login 时缓存的令牌。
  • cache_dir (str, Path, optional) — 缓存文件存储在其中的文件夹的路径。
  • local_files_only (bool, optional, defaults to False) — 如果为 True,则避免下载文件,并在本地缓存文件存在时返回其路径。
  • labels (List[str], optional) — 如果标签是 0num_classes-1 范围内的整数,则这些标签指示相应的标签。
  • model_card_data (SetFitModelCardData, optional) — 一个 SetFitModelCardData 实例,用于存储模型语言、许可证、数据集名称等数据,以便在自动生成的模型卡片中使用。
  • multi_target_strategy (str, optional) — 用于多标签分类的策略。“one-vs-rest”、“multi-output”或“classifier-chain”之一。
  • use_differentiable_head (bool, optional) — 是否使用可微分(即 Torch)头而不是 Logistic 回归来加载 SetFit。
  • normalize_embeddings (bool, optional) — 是否对 Sentence Transformer 主体生成的嵌入应用归一化。
  • device (Union[torch.device, str], optional) — 要在其上加载 SetFit 模型的设备,例如 “cuda:0”“mps”torch.device(“cuda”)
  • trust_remote_code (bool, defaults to False) — 是否允许在 Hub 上自定义 Sentence Transformers 模型,这些模型在其自己的建模文件中定义。此选项仅应针对您信任并已阅读代码的存储库设置为 True,因为它将在您的本地计算机上执行 Hub 上存在的代码。默认为 False。

从 Huggingface Hub 下载模型并实例化它。

示例

>>> from setfit import SetFitModel
>>> model = SetFitModel.from_pretrained(
...     "sentence-transformers/paraphrase-mpnet-base-v2",
...     labels=["positive", "negative"],
... )

save_pretrained

< >

( save_directory: typing.Union[str, pathlib.Path] config: typing.Union[dict, huggingface_hub.hub_mixin.DataclassInstance, NoneType] = None repo_id: typing.Optional[str] = None push_to_hub: bool = False model_card_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None **push_to_hub_kwargs ) str or None

参数

  • save_directory (strPath) — 将在其中保存模型权重和配置的目录的路径。
  • config (dictDataclassInstance, optional) — 模型配置,指定为键/值字典或数据类实例。
  • push_to_hub (bool, optional, defaults to False) — 是否在保存模型后将其推送到 Huggingface Hub。
  • repo_id (str, 可选) — Hub 上的仓库 ID。仅在 push_to_hub=True 时使用。如果未提供,则默认为文件夹名称。
  • model_card_kwargs (Dict[str, Any], 可选) — 传递给模型卡模板以自定义模型卡的附加参数。
  • push_to_hub_kwargs — 传递给 ~ModelHubMixin.push_to_hub 方法的附加关键字参数。

返回

strNone

如果 push_to_hub=True,则返回 Hub 上提交的 url,否则返回 None

将权重保存在本地目录。

push_to_hub

< >

( repo_id: str config: typing.Union[dict, huggingface_hub.hub_mixin.DataclassInstance, NoneType] = None commit_message: str = 'Push model using huggingface_hub.' private: typing.Optional[bool] = 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 model_card_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None )

参数

  • repo_id (str) — 要推送到的仓库 ID (示例:"username/my-model")。
  • config (dictDataclassInstance, 可选) — 模型配置,指定为键/值字典或数据类实例。
  • commit_message (str, 可选) — 推送时提交的消息。
  • private (bool, 可选) — 创建的仓库是否应为私有。如果为 None (默认),则仓库将是公开的,除非组织的默认设置为私有。
  • token (str, 可选) — 用作远程文件 HTTP Bearer 授权的令牌。默认情况下,它将使用运行 huggingface-cli login 时缓存的令牌。
  • branch (str, 可选) — 要将模型推送到的 git 分支。默认为 "main"
  • create_pr (boolean, 可选) — 是否从带有该提交的 branch 创建拉取请求。默认为 False
  • allow_patterns (List[str]str, 可选) — 如果提供,则仅推送与至少一个模式匹配的文件。
  • ignore_patterns (List[str]str, 可选) — 如果提供,则不推送与任何模式匹配的文件。
  • delete_patterns (List[str]str, 可选) — 如果提供,则将从仓库中删除与任何模式匹配的远程文件。
  • model_card_kwargs (Dict[str, Any], 可选) — 传递给模型卡模板以自定义模型卡的附加参数。

将模型检查点上传到 Hub。

使用 allow_patternsignore_patterns 精确筛选要推送到 Hub 的文件。使用 delete_patterns 删除同一提交中已有的远程文件。有关更多详细信息,请参阅 upload_folder 参考。

__call__

< >

( 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]

参数

  • inputs (Union[str, List[str]]) — 要预测类别的输入句子。
  • batch_size (int, 默认为 32) — 用于将句子编码为嵌入的批大小。值越高通常意味着更快的处理速度,但也意味着更高的内存使用量。
  • as_numpy (bool, 默认为 False) — 是否输出为 numpy 数组。
  • use_labels (bool, 默认为 True) — 是否尝试返回 SetFitModel.labels 的元素。
  • show_progress_bar (Optional[bool], 默认为 None) — 是否在编码时显示进度条。

返回

Union[torch.Tensor, np.ndarray, List[str], int, str]

如果 use_labelsTrue 且已定义 SetFitModel.labels,则返回与输入长度相等的字符串标签列表。否则,返回与输入长度相等的向量,表示每个输入预测属于哪个类。如果输入是单个字符串,则输出也是单个标签。

预测各种类别。

示例

>>> model = SetFitModel.from_pretrained(...)
>>> model(["What a boring display", "Exhilarating through and through", "I'm wowed!"])
["negative", "positive", "positive"]
>>> model("That was cool!")
"positive"

label2id

< >

( )

返回从字符串标签到整数 ID 的映射。

id2label

< >

( )

返回从整数 ID 到字符串标签的映射。

create_model_card

< >

( path: str model_name: typing.Optional[str] = 'SetFit Model' )

参数

  • path (str) — 保存模型卡到的路径。
  • model_name (str, 可选) — 模型的名称。 默认为 SetFit Model

为 SetFit 模型创建并保存模型卡。

encode

< >

( inputs: typing.List[str] batch_size: int = 32 show_progress_bar: typing.Optional[bool] = None ) Union[torch.Tensor, np.ndarray]

参数

  • inputs (List[str]) — 要嵌入的输入句子列表。
  • batch_size (int, 默认为 32) — 用于将句子编码为嵌入向量的批次大小。 值越高通常意味着处理速度更快,但内存使用量也更高。
  • show_progress_bar (Optional[bool], 默认为 None) — 是否在编码时显示进度条。

返回

Union[torch.Tensor, np.ndarray]

形状为 [INPUT_LENGTH, EMBEDDING_SIZE] 的矩阵,如果此模型具有可微分的 Torch 头,则为 torch Tensor,否则为 numpy 数组。

使用 SentenceTransformer 主体将输入句子转换为嵌入向量。

fit

< >

( 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 )

参数

  • x_train (List[str]) — 训练句子列表。
  • y_train (Union[List[int], List[List[int]]]) — 与训练句子对应的标签列表。
  • num_epochs (int) — 训练的轮数。
  • batch_size (int, 可选) — 要使用的批次大小。
  • body_learning_rate (float, 可选) — AdamW 优化器中 SentenceTransformer 主体的学习率。 如果 end_to_end=False,则忽略。
  • head_learning_rate (float, 可选) — AdamW 优化器中可微分 torch 头的学习率。
  • end_to_end (bool, 默认为 False) — 如果为 True,则端到端训练整个模型。 否则,冻结 SentenceTransformer 主体,仅训练头部。
  • l2_weight (float, 可选) — AdamW 优化器中模型主体和头部的 l2 权重。
  • max_length (int, 可选) — tokenizer 可以生成的最长 token 长度。 如果未提供,则使用 SentenceTransformer 主体的最大长度。
  • show_progress_bar (bool, 默认为 True) — 是否为训练轮次和迭代显示进度条。

训练分类器头部,仅当使用可微分的 PyTorch 头部时使用。

freeze

< >

( component: typing.Optional[typing.Literal['body', 'head']] = None )

参数

  • component (Literal["body", "head"], 可选) — 要冻结的组件,可以是 “body” 或 “head”。 如果未提供组件,则冻结两者。 默认为 None。

冻结模型主体和/或头部,阻止对该组件进行进一步训练,直到解冻为止。

generate_model_card

< >

( ) str

返回

str

模型卡字符串。

根据模型卡数据生成并返回模型卡字符串。

predict

< >

( 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]

参数

  • inputs (Union[str, List[str]]) — 用于预测类别的输入句子或句子列表。
  • batch_size (int, 默认为 32) — 用于将句子编码为嵌入向量的批次大小。 值越高通常意味着处理速度更快,但内存使用量也更高。
  • as_numpy (bool, 默认为 False) — 是否输出为 numpy 数组。
  • use_labels (bool, 默认为 True) — 是否尝试返回 SetFitModel.labels 的元素。
  • show_progress_bar (Optional[bool], 默认为 None) — 是否在编码时显示进度条。

返回

Union[torch.Tensor, np.ndarray, List[str], int, str]

如果 use_labelsTrue 且已定义 SetFitModel.labels,则返回与输入长度相等的字符串标签列表。否则,返回与输入长度相等的向量,表示每个输入预测属于哪个类。如果输入是单个字符串,则输出也是单个标签。

预测各种类别。

示例

>>> model = SetFitModel.from_pretrained(...)
>>> model.predict(["What a boring display", "Exhilarating through and through", "I'm wowed!"])
["negative", "positive", "positive"]
>>> model.predict("That was cool!")
"positive"

predict_proba

< >

( 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]

参数

  • inputs (Union[str, List[str]]) — 用于预测类别概率的输入句子。
  • batch_size (int, 默认为 32) — 用于将句子编码为嵌入向量的批次大小。 值越高通常意味着处理速度更快,但内存使用量也更高。
  • as_numpy (bool, 默认为 False) — 是否输出为 numpy 数组。
  • show_progress_bar (Optional[bool], defaults to None) — 是否在编码时显示进度条。

返回

Union[torch.Tensor, np.ndarray]

形状为 [INPUT_LENGTH, NUM_CLASSES] 的矩阵,表示预测输入为某个类别的概率。如果输入是字符串,则输出是形状为 [NUM_CLASSES,] 的向量。

预测各种类别的概率。

示例

>>> 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

参数

  • device (Union[str, torch.device]) — 要将模型移动到的设备的标识符。

返回

SetFitModel

返回原始模型,但现在位于所需的设备上。

将此 SetFitModel 移动到 device,然后返回 self。此方法不进行复制。

示例

>>> model = SetFitModel.from_pretrained(...)
>>> model.to("cpu")
>>> model(["cats are cute", "dogs are loyal"])

unfreeze

< >

( component: typing.Optional[typing.Literal['body', 'head']] = None keep_body_frozen: typing.Optional[bool] = None )

参数

  • component (Literal["body", "head"], optional) — 要解冻的组件,可以是 “body” 或 “head”。如果未提供组件,则解冻两者。默认为 None。
  • keep_body_frozen (bool, optional) — 已弃用的参数,请改用 component

解冻模型主体和/或头部,允许在该组件上进行进一步训练。

SetFitHead

class setfit.SetFitHead

< >

( 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 )

参数

  • in_features (int, optional) — 来自 SetFit 主体的输出的嵌入维度。如果为 None,则默认为 LazyLinear
  • out_features (int, defaults to 2) — 目标的数量。如果为二分类设置 out_features 为 1,它将被更改为 2,因为是 2 类分类。
  • temperature (float, defaults to 1.0) — logits 的缩放因子。值越高,模型置信度越低,值越低,模型置信度越高。
  • eps (float, defaults to 1e-5) — 用于缩放 logits 时数值稳定性的值。
  • bias (bool, optional, defaults to True) — 是否向头部添加偏置。
  • device (torch.device, str, optional) — 模型将要发送到的设备。如果为 None,将检查 GPU 是否可用。
  • multitarget (bool, defaults to False) — 通过使 out_features 进行二元预测而不是单个多项式预测来启用多目标分类。

支持端到端训练的多类分类的 SetFit 头部。二分类被视为 2 类分类。

为了与 Sentence Transformers 兼容,我们从以下位置继承 Densehttps://github.com/UKPLab/sentence-transformers/blob/master/sentence_transformers/models/Dense.py

forward

< >

( features: typing.Union[typing.Dict[str, torch.Tensor], torch.Tensor] temperature: typing.Optional[float] = None )

参数

  • features (Dict[str, torch.Tensor] or torch.Tensor) -- 来自编码器的嵌入。如果使用 dict` 格式,请确保将嵌入存储在键 'sentence_embedding' 下,输出将位于键 'prediction' 下。
  • temperature (float, optional) — logits 的缩放因子。值越高,模型置信度越低,值越低,模型置信度越高。将覆盖初始化期间给定的温度。

SetFitHead 可以接受以下格式的嵌入:

  1. 来自 Sentence-Transformers 的输出格式 (dict)。
  2. torch.Tensor

SetFitModelCardData

class setfit.SetFitModelCardData

< >

( 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 )

参数

  • language (Optional[Union[str, List[str]]]) — 模型语言,可以是字符串或列表,例如 “en” 或 [“en”, “de”, “nl”]
  • license (Optional[str]) — 模型的许可证,例如 “apache-2.0”、“mit” 或 “cc-by-nc-sa-4.0”
  • model_name (Optional[str]) — 模型的漂亮名称,例如 “SetFit with mBERT-base on SST2”。如果未定义,则使用 encoder_name/encoder_id 和 dataset_name/dataset_id 生成模型名称。
  • model_id (Optional[str]) — 将模型推送到 Hub 时的模型 ID,例如 “tomaarsen/span-marker-mbert-base-multinerd”。
  • dataset_name (Optional[str]) — 数据集的漂亮名称,例如 “SST2”。
  • dataset_id (Optional[str]) — 数据集的 dataset ID,例如 “dair-ai/emotion”。
  • dataset_revision (Optional[str]) — 用于训练/评估的数据集修订版本/提交。
  • st_id (Optional[str]) — Sentence Transformers 模型 ID。

一个数据类,用于存储模型卡中使用的数据。

安装 codecarbon 以自动跟踪碳排放使用情况并将其包含在您的模型卡中。

示例

>>> 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",
...     ),
... )

to_dict

< >

( )

to_dict

< >

to_yaml

AbsaModel

class setfit.AbsaModel

< >

( aspect_extractor: AspectExtractor aspect_model: AspectModel polarity_model: PolarityModel )

__call__

< >

( inputs: typing.Union[str, typing.List[str]] )

device

< >

( )

from_pretrained

< >

( 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[bool, str, NoneType] = None cache_dir: typing.Optional[str] = None local_files_only: bool = None use_differentiable_head: bool = None normalize_embeddings: bool = None **model_kwargs )

predict

< >

( inputs: typing.Union[str, typing.List[str], datasets.arrow_dataset.Dataset] ) Union[List[Dict[str, Any]], Dataset]

参数

  • inputs (Union[str, List[str], Dataset]) — 句子、句子列表或包含列 textspan 以及可选列 ordinal 的数据集。此数据集包含黄金标准方面,我们仅预测它们的极性。

返回

Union[List[Dict[str, Any]], Dataset]

如果输入是句子或句子列表,则为包含键 spanpolarity 的字典列表;如果输入是数据集,则为包含列 textspanordinalpred_polarity 的数据集。

预测给定输入的方面及其极性。

示例

>>> 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
})

push_to_hub

< >

( repo_id: str polarity_repo_id: typing.Optional[str] = None **kwargs )

< >

( device: typing.Union[str, torch.device] )

save_pretrained

< >

( save_directory: typing.Union[str, pathlib.Path] polarity_save_directory: typing.Union[str, pathlib.Path, NoneType] = None push_to_hub: bool = False **kwargs )

AspectModel

class setfit.AspectModel

< >

( *args **kwargs )

__call__

< >

( docs: typing.List[ForwardRef('Doc')] aspects_list: typing.List[typing.List[slice]] )

device

< >

( ) torch.device

返回

torch.device

The device that the model is on.

Get the Torch device that this model is on.

from_pretrained

< >

( )

参数

  • pretrained_model_name_or_path (str, Path) —
    • Hub 上托管的模型的 model_id(字符串),例如 bigscience/bloom
    • 或者,包含使用 save_pretrained 保存的模型权重的 directory 的路径,例如 ../path/to/my_model_directory/
  • revision (str, optional) — Hub 上模型的修订版本。可以是分支名称、git 标签或任何提交 ID。默认为 main 分支上的最新提交。
  • force_download (bool, optional, defaults to False) — 是否强制(重新)从 Hub 下载模型权重和配置文件,从而覆盖现有缓存。
  • proxies (Dict[str, str], optional) — 要按协议或端点使用的代理服务器字典,例如,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}。代理用于每个请求。
  • token (strbool, 可选) — 用于远程文件的 HTTP Bearer 授权令牌。默认情况下,它将使用运行 huggingface-cli login 时缓存的令牌。
  • cache_dir (str, Path, 可选) — 缓存文件存储所在文件夹的路径。
  • local_files_only (bool, 可选, 默认为 False) — 如果为 True,则避免下载文件,并在本地缓存文件存在时返回其路径。
  • labels (List[str], 可选) — 如果标签是 0num_classes-1 范围内的整数,则这些标签指示相应的标签。
  • model_card_data (SetFitModelCardData, 可选) — 一个 SetFitModelCardData 实例,存储诸如模型语言、许可证、数据集名称等数据,用于自动生成的模型卡片中。
  • model_card_data (SetFitModelCardData, 可选) — 一个 SetFitModelCardData 实例,存储诸如模型语言、许可证、数据集名称等数据,用于自动生成的模型卡片中。
  • use_differentiable_head (bool, 可选) — 是否使用可微分的(即 Torch) head 而不是 Logistic Regression 来加载 SetFit。
  • normalize_embeddings (bool, 可选) — 是否对 Sentence Transformer 主体生成的 embeddings 应用标准化。
  • span_context (int, 默认为 0) — 应添加到完整句子前面和后面的 span 候选词的数量。默认情况下,Aspect 模型为 0,Polarity 模型为 3。
  • device (Union[torch.device, str], 可选) — 加载 SetFit 模型的设备,例如 "cuda:0", "mps"torch.device("cuda")

从 Huggingface Hub 下载模型并实例化它。

predict

< >

( 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]

参数

  • inputs (Union[str, List[str]]) — 用于预测类别的输入句子。
  • batch_size (int, 默认为 32) — 用于将句子编码为 embeddings 的批处理大小。较高的值通常意味着更快的处理速度,但也意味着更高的内存使用率。
  • as_numpy (bool, 默认为 False) — 是否输出为 numpy 数组。
  • use_labels (bool, 默认为 True) — 是否尝试返回 SetFitModel.labels 的元素。
  • show_progress_bar (Optional[bool], 默认为 None) — 编码时是否显示进度条。

返回

Union[torch.Tensor, np.ndarray, List[str], int, str]

如果 use_labelsTrue 且已定义 SetFitModel.labels,则返回与输入长度相等的字符串标签列表。否则,返回与输入长度相等的向量,表示每个输入预测属于哪个类。如果输入是单个字符串,则输出也是单个标签。

预测各种类别。

示例

>>> model = SetFitModel.from_pretrained(...)
>>> model.predict(["What a boring display", "Exhilarating through and through", "I'm wowed!"])
["negative", "positive", "positive"]
>>> model.predict("That was cool!")
"positive"

push_to_hub

< >

( repo_id: str config: typing.Union[dict, huggingface_hub.hub_mixin.DataclassInstance, NoneType] = None commit_message: str = 'Push model using huggingface_hub.' private: typing.Optional[bool] = 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 model_card_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None )

参数

  • repo_id (str) — 要推送到的仓库 ID (例如: "username/my-model")。
  • config (dictDataclassInstance, 可选) — 模型配置,可以指定为键/值字典或 dataclass 实例。
  • commit_message (str, 可选) — 推送时提交的消息。
  • private (bool, 可选) — 创建的仓库是否应为私有。如果为 None (默认),则仓库将是公开的,除非组织的默认设置为私有。
  • token (str, 可选) — 用于远程文件的 HTTP Bearer 授权令牌。默认情况下,它将使用运行 huggingface-cli login 时缓存的令牌。
  • branch (str, 可选) — 推送模型的 git 分支。默认为 "main"
  • create_pr (boolean, 可选) — 是否从带有该提交的分支创建 Pull Request。默认为 False
  • allow_patterns (List[str]str, 可选) — 如果提供,则仅推送与至少一个模式匹配的文件。
  • ignore_patterns (List[str]str, 可选) — 如果提供,则不推送与任何模式匹配的文件。
  • delete_patterns (List[str]str, 可选) — 如果提供,则将从仓库中删除与任何模式匹配的远程文件。
  • model_card_kwargs (Dict[str, Any], 可选) — 传递给模型卡片模板以自定义模型卡片的附加参数。

将模型检查点上传到 Hub。

使用 allow_patternsignore_patterns 精确筛选要推送到 Hub 的文件。使用 delete_patterns 删除同一提交中已有的远程文件。有关更多详细信息,请参阅 upload_folder 参考。

save_pretrained

< >

( save_directory: typing.Union[str, pathlib.Path] config: typing.Union[dict, huggingface_hub.hub_mixin.DataclassInstance, NoneType] = None repo_id: typing.Optional[str] = None push_to_hub: bool = False model_card_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None **push_to_hub_kwargs ) str or None

参数

  • save_directory (strPath) — 模型权重和配置将保存到的目录路径。
  • config (dictDataclassInstance, 可选) — 模型配置,可以指定为键/值字典或 dataclass 实例。
  • push_to_hub (bool, 可选, 默认为 False) — 是否在保存模型后将其推送到 Huggingface Hub。
  • repo_id (str, 可选) — 您在 Hub 上的仓库 ID。仅当 push_to_hub=True 时使用。如果未提供,则默认为文件夹名称。
  • model_card_kwargs (Dict[str, Any], 可选) — 传递给模型卡片模板以自定义模型卡片的附加参数。
  • push_to_hub_kwargs — 传递给 ~ModelHubMixin.push_to_hub 方法的额外关键字参数。

返回

strNone

如果 push_to_hub=True,则返回 Hub 上提交的 url,否则返回 None

将权重保存在本地目录。

< >

( device: typing.Union[str, torch.device] ) SetFitModel

参数

  • device (Union[str, torch.device]) — 将模型移动到的设备的标识符。

返回

SetFitModel

返回原始模型,但现在位于所需的设备上。

将此 SetFitModel 移动到 device,然后返回 self。此方法不进行复制。

示例

>>> model = SetFitModel.from_pretrained(...)
>>> model.to("cpu")
>>> model(["cats are cute", "dogs are loyal"])

PolarityModel

class setfit.PolarityModel

< >

( span_context: int = 3 **kwargs )

__call__

< >

( docs: typing.List[ForwardRef('Doc')] aspects_list: typing.List[typing.List[slice]] )

device

< >

( ) torch.device

返回

torch.device

The device that the model is on.

Get the Torch device that this model is on.

from_pretrained

< >

( )

参数

  • pretrained_model_name_or_path (str, Path) —
    • Hub 上托管的模型的 model_id (字符串),例如 bigscience/bloom
    • 或者一个 directory 的路径,其中包含使用 save_pretrained 保存的模型权重,例如,../path/to/my_model_directory/
  • revision (str, optional) — Hub 上模型的修订版本。可以是分支名称、git 标签或任何提交 ID。默认为 main 分支上的最新提交。
  • force_download (bool, optional, defaults to False) — 是否强制(重新)从 Hub 下载模型权重和配置文件,覆盖现有缓存。
  • proxies (Dict[str, str], optional) — 按协议或端点使用的代理服务器字典,例如,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}。代理用于每个请求。
  • token (str or bool, optional) — 用作远程文件的 HTTP Bearer 授权的令牌。默认情况下,它将使用运行 huggingface-cli login 时缓存的令牌。
  • cache_dir (str, Path, optional) — 存储缓存文件的文件夹的路径。
  • local_files_only (bool, optional, defaults to False) — 如果为 True,则避免下载文件,如果本地缓存文件存在,则返回本地缓存文件的路径。
  • labels (List[str], optional) — 如果标签是 0num_classes-1 范围内的整数,则这些标签指示相应的标签。
  • model_card_data (SetFitModelCardData, optional) — 一个 SetFitModelCardData 实例,存储诸如模型语言、许可证、数据集名称等数据,用于自动生成的模型卡片中。
  • model_card_data (SetFitModelCardData, optional) — 一个 SetFitModelCardData 实例,存储诸如模型语言、许可证、数据集名称等数据,用于自动生成的模型卡片中。
  • use_differentiable_head (bool, optional) — 是否加载使用可微分(即 Torch)头而不是 Logistic Regression 的 SetFit。
  • normalize_embeddings (bool, optional) — 是否对 Sentence Transformer 主体生成的嵌入应用归一化。
  • span_context (int, defaults to 0) — 应预先添加到完整句子的 span 候选词之前和之后的单词数。默认情况下,Aspect 模型为 0,Polarity 模型为 3。
  • device (Union[torch.device, str], optional) — 加载 SetFit 模型的设备,例如 "cuda:0""mps"torch.device("cuda")

从 Huggingface Hub 下载模型并实例化它。

predict

< >

( 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]

参数

  • inputs (Union[str, List[str]]) — 要预测类别的输入句子。
  • batch_size (int, defaults to 32) — 在将句子编码为嵌入时使用的批大小。值越高通常意味着更快的处理速度,但也意味着更高的内存使用量。
  • as_numpy (bool, defaults to False) — 是否输出为 numpy 数组。
  • use_labels (bool, defaults to True) — 是否尝试返回 SetFitModel.labels 的元素。
  • show_progress_bar (Optional[bool], defaults to None) — 是否在编码时显示进度条。

返回

Union[torch.Tensor, np.ndarray, List[str], int, str]

如果 use_labelsTrue 且已定义 SetFitModel.labels,则返回与输入长度相等的字符串标签列表。否则,返回与输入长度相等的向量,表示每个输入预测属于哪个类。如果输入是单个字符串,则输出也是单个标签。

预测各种类别。

示例

>>> model = SetFitModel.from_pretrained(...)
>>> model.predict(["What a boring display", "Exhilarating through and through", "I'm wowed!"])
["negative", "positive", "positive"]
>>> model.predict("That was cool!")
"positive"

push_to_hub

< >

( repo_id: str config: typing.Union[dict, huggingface_hub.hub_mixin.DataclassInstance, NoneType] = None commit_message: str = 'Push model using huggingface_hub.' private: typing.Optional[bool] = 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 model_card_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None )

参数

  • repo_id (str) — 要推送到的仓库的 ID(示例:"username/my-model")。
  • config (dict or DataclassInstance, optional) — 模型配置,指定为键/值字典或数据类实例。
  • commit_message (str, optional) — 推送时提交的消息。
  • private (bool, optional) — 创建的仓库是否应为私有。如果为 None(默认),则仓库将是公开的,除非组织的默认设置为私有。
  • token (str, optional) — 用作远程文件的 HTTP Bearer 授权的令牌。默认情况下,它将使用运行 huggingface-cli login 时缓存的令牌。
  • branch (str, 可选) — 用于推送模型的 git 分支。默认为 "main"
  • create_pr (boolean, 可选) — 是否从 branch 为该提交创建拉取请求。默认为 False
  • allow_patterns (List[str]str, 可选) — 如果提供,则仅推送与至少一个模式匹配的文件。
  • ignore_patterns (List[str]str, 可选) — 如果提供,则不推送与任何模式匹配的文件。
  • delete_patterns (List[str]str, 可选) — 如果提供,则与任何模式匹配的远程文件将从仓库中删除。
  • model_card_kwargs (Dict[str, Any], 可选) — 传递给模型卡片模板以自定义模型卡片的附加参数。

将模型检查点上传到 Hub。

使用 allow_patternsignore_patterns 精确筛选要推送到 Hub 的文件。使用 delete_patterns 删除同一提交中已有的远程文件。有关更多详细信息,请参阅 upload_folder 参考。

save_pretrained

< >

( save_directory: typing.Union[str, pathlib.Path] config: typing.Union[dict, huggingface_hub.hub_mixin.DataclassInstance, NoneType] = None repo_id: typing.Optional[str] = None push_to_hub: bool = False model_card_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None **push_to_hub_kwargs ) str or None

参数

  • save_directory (strPath) — 模型权重和配置将保存到的目录路径。
  • config (dictDataclassInstance, 可选) — 模型配置,指定为键/值字典或数据类实例。
  • push_to_hub (bool, 可选, 默认为 False) — 是否在保存模型后将其推送到 Huggingface Hub。
  • repo_id (str, 可选) — Hub 上仓库的 ID。 仅在 push_to_hub=True 时使用。如果未提供,则默认为文件夹名称。
  • model_card_kwargs (Dict[str, Any], 可选) — 传递给模型卡片模板以自定义模型卡片的附加参数。
  • push_to_hub_kwargs — 传递给 ~ModelHubMixin.push_to_hub 方法的附加关键字参数。

返回

strNone

如果 push_to_hub=True,则返回 Hub 上提交的 url,否则返回 None

将权重保存在本地目录。

< >

( device: typing.Union[str, torch.device] ) SetFitModel

参数

  • device (Union[str, torch.device]) — 将模型移动到的设备的标识符。

返回

SetFitModel

返回原始模型,但现在位于所需的设备上。

将此 SetFitModel 移动到 device,然后返回 self。此方法不进行复制。

示例

>>> model = SetFitModel.from_pretrained(...)
>>> model.to("cpu")
>>> model(["cats are cute", "dogs are loyal"])
< > Update on GitHub