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, 可選) — Hub 上模型的修訂版本。可以是分支名稱、git 標籤或任何提交 ID。預設為 main 分支上的最新提交。
  • force_download (bool, 可選, 預設為 False) — 是否強制(重新)從 Hub 下載模型權重和配置檔案,覆蓋現有快取。
  • proxies (Dict[str, str], 可選) — 要按協議或端點使用的代理伺服器字典,例如 {‘http’: ‘foo.bar:3128’, ‘http://hostname’: ‘foo.bar:4012’}。每個請求都會使用代理。
  • token (strbool, 可選) — 用於遠端檔案的 HTTP Bearer 授權令牌。預設情況下,它將使用執行 hf auth login 時快取的令牌。
  • cache_dir (str, Path, 可選) — 快取檔案儲存的資料夾路徑。
  • local_files_only (bool, 可選, 預設為 False) — 如果為 True,則避免下載檔案,如果本地快取檔案存在則返回其路徑。
  • labels (List[str], 可選) — 如果標籤是 0num_classes-1 範圍內的整數,則這些標籤表示相應的標籤。
  • model_card_data (SetFitModelCardData, 可選) — 一個 SetFitModelCardData 例項,儲存模型語言、許可證、資料集名稱等資料,用於自動生成的模型卡。
  • multi_target_strategy (str, 可選) — 與多標籤分類一起使用的策略。可以是 “one-vs-rest”、“multi-output” 或 “classifier-chain” 之一。
  • use_differentiable_head (bool, 可選) — 是否使用可微分(即 Torch)頭部而不是邏輯迴歸來載入 SetFit。
  • normalize_embeddings (bool, 可選) — 是否對 Sentence Transformer 主體生成的嵌入應用歸一化。
  • device (Union[torch.device, str], 可選) — 載入 SetFit 模型的裝置,例如 “cuda:0”“mps”torch.device(“cuda”)
  • trust_remote_code (bool, 預設為 False) — 是否允許在 Hub 上自己的建模檔案中定義的自定義 Sentence Transformers 模型。此選項僅應設定為您信任且已閱讀其程式碼的倉庫,因為它將在您的本地機器上執行 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 ) strNone

引數

  • 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

將權重儲存到本地目錄。

push_to_hub

< >

( repo_id: str config: typing.Union[dict, huggingface_hub.hub_mixin.DataclassInstance, NoneType] = None commit_message: str = '使用 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 授權令牌。預設情況下,它將使用執行 hf auth login 時快取的令牌。
  • branch (str, 可選) — 推送模型的 git 分支。預設為 "main"
  • create_pr (boolean, 可選) — 是否從 branch 建立帶有該提交的 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 參考。

__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_labelsTrueSetFitModel.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 到字串標籤的對映。

建立模型卡片

< >

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

引數

  • path (str) — 儲存模型卡的路徑。
  • model_name (str, 可選) — 模型的名稱。預設為 SetFit Model

為 SetFit 模型建立並儲存模型卡。

編碼

< >

( 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) — 訓練的 epoch 數量。
  • 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, 可選) — 分詞器可以生成的最大 token 長度。如果未提供,則使用 SentenceTransformer 主體的最大長度。
  • show_progress_bar (bool, 預設為 True) — 是否顯示訓練 epoch 和迭代的進度條。

訓練分類器頭部,僅在使用可微分 PyTorch 頭部時使用。

freeze

< >

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

引數

  • component (Literal["body", "head"], 可選) — “body” 或 “head” 以凍結該元件。如果未提供元件,則凍結兩者。預設為 None。

凍結模型主體和/或頭部,防止在該元件上進行進一步訓練,直到解凍。

generate_model_card

< >

( ) 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_labelsTrueSetFitModel.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], 預設為 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"], 可選) — “body” 或 “head” 以解凍該元件。如果未提供元件,則解凍兩者。預設為 None。
  • keep_body_frozen (bool, 可選) — 已棄用的引數,請改用 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, 可選) — SetFit 主體輸出的嵌入維度。如果為 None,則預設為 LazyLinear
  • out_features (int, 預設為 2) — 目標數量。如果將 out_features 設定為 1 用於二分類,它將被更改為 2,因為是二分類。
  • temperature (float, 預設為 1.0) — Logits 的縮放因子。值越高,模型信心越低;值越低,模型信心越高。
  • eps (float, 預設為 1e-5) — 用於縮放 logits 的數值穩定性值。
  • bias (bool, 可選, 預設為 True) — 是否在頭部新增偏差。
  • device (torch.device, str, 可選) — 模型將被髮送到的裝置。如果為 None,將檢查 GPU 是否可用。
  • multitarget (bool, 預設為 False) — 透過將 out_features 設定為二元預測而不是單一多項式預測來啟用多目標分類。

一個支援多類別分類的 SetFit 頭部,用於端到端訓練。二元分類被視為二類別分類。

為了與 Sentence Transformers 相容,我們繼承了 Dense 自:https://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]torch.Tensor) -- 編碼器輸出的嵌入。如果使用 dict` 格式,請確保在鍵 'sentence_embedding' 下儲存嵌入,輸出將在鍵 'prediction' 下。
  • temperature (float, 可選) — 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]) — 資料集的 ID,例如“dair-ai/emotion”。
  • dataset_revision (Optional[str]) — 用於訓練/評估的資料集修訂/提交。
  • st_id (Optional[str]) — Sentence Transformers 模型 ID。

儲存模型卡中使用的資料的 dataclass。

安裝 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_yaml

< >

( 換行 = 無 )

AbsaModel

setfit.AbsaModel

< >

( 方面提取器: AspectExtractor 方面模型: AspectModel 極性模型: PolarityModel )

__call__

< >

( 輸入: typing.Union[str, typing.List[str]] )

裝置

< >

( )

from_pretrained

< >

( 模型ID: str 極性模型ID: typing.Optional[str] = None spaCy模型: typing.Optional[str] = None span上下文: typing.Tuple[typing.Optional[int], typing.Optional[int]] = (None, None) 強制下載: bool = None 恢復下載: bool = None 代理: typing.Optional[typing.Dict] = None 令牌: typing.Union[bool, str, NoneType] = None 快取目錄: typing.Optional[str] = None 僅限本地檔案: bool = None 使用可微分頭: bool = None 歸一化嵌入: bool = None **模型引數 )

predict

< >

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

引數

  • inputs (Union[str, List[str], Dataset]) — 句子、句子列表或包含文字跨度列(可選序數)的資料集。此資料集包含金方面,我們只預測它們的極性。

返回

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

如果輸入是句子或句子列表,則返回一個字典列表,鍵為跨度極性;如果輸入是資料集,則返回一個包含文字跨度序數預測極性列的資料集。

預測給定輸入的方面及其極性。

示例

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

< >

( 倉庫ID: str 極性倉庫ID: typing.Optional[str] = None **kwargs )

< >

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

save_pretrained

< >

( 儲存目錄: typing.Union[str, pathlib.Path] 極性儲存目錄: typing.Union[str, pathlib.Path, NoneType] = None 推送到集線器: bool = False **kwargs )

AspectModel

setfit.AspectModel

< >

( *引數 **kwargs )

__call__

< >

( 文件: typing.List[ForwardRef('Doc')] 方面列表: typing.List[typing.List[slice]] )

裝置

< >

( ) torch.device

返回

torch.device

模型所在的裝置。

獲取此模型所在的Torch裝置。

from_pretrained

< >

( )

引數

  • pretrained_model_name_or_path (str, Path) —
    • 可以是託管在Hub上的模型的model_id(字串),例如bigscience/bloom
    • 或者是包含使用save_pretrained儲存的模型權重的directory路徑,例如../path/to/my_model_directory/
  • revision (str, 可選) — Hub上模型的修訂版本。可以是分支名稱、git標籤或任何提交ID。預設為main分支的最新提交。
  • force_download (bool, 可選, 預設為False) — 是否強制(重新)從Hub下載模型權重和配置檔案,覆蓋現有快取。
  • proxies (Dict[str, str], 可選) — 一個字典,其中包含按協議或端點使用的代理伺服器,例如{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}。代理用於每個請求。
  • token (strbool, 可選) — 用作遠端檔案HTTP bearer授權的令牌。預設情況下,它將使用執行hf auth login時快取的令牌。
  • cache_dir (str, Path, 可選) — 快取檔案儲存的資料夾路徑。
  • local_files_only (bool, 可選, 預設為False) — 如果為True,則避免下載檔案,如果本地快取檔案存在,則返回其路徑。
  • labels (List[str], 可選) — 如果標籤是0到num_classes-1之間的整數,則這些標籤表示相應的標籤。
  • model_card_data (SetFitModelCardData, 可選) — 一個SetFitModelCardData例項,儲存模型語言、許可證、資料集名稱等資料,用於自動生成的模型卡。
  • model_card_data (SetFitModelCardData, 可選) — 一個SetFitModelCardData例項,儲存模型語言、許可證、資料集名稱等資料,用於自動生成的模型卡。
  • use_differentiable_head (bool, 可選) — 是否使用可微分(即 Torch)頭部而不是邏輯迴歸載入SetFit。
  • normalize_embeddings (bool, 可選) — 是否對Sentence Transformer主體生成的嵌入進行歸一化。
  • span_context (int, 預設為0) — 跨度候選前後應新增的單詞數。對於方面模型,預設為0;對於極性模型,預設為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) — 用於將句子編碼為嵌入的批處理大小。通常,值越大處理速度越快,但記憶體使用量也越高。
  • 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_labelsTrueSetFitModel.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 = '使用 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授權的令牌。預設情況下,它將使用執行hf auth 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 ) strNone

引數

  • 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"])

極性模型

class setfit.PolarityModel

< >

( span_context: int = 3 **kwargs )

__call__

< >

( 文件: typing.List[ForwardRef('Doc')] 方面列表: typing.List[typing.List[slice]] )

裝置

< >

( ) torch.device

返回

torch.device

模型所在的裝置。

獲取此模型所在的Torch裝置。

from_pretrained

< >

( )

引數

  • pretrained_model_name_or_path (str, Path) —
    • 模型在Hub上的model_id(字串),例如bigscience/bloom
    • 或者包含使用save_pretrained儲存的模型權重的directory路徑,例如../path/to/my_model_directory/
  • revision (str, 可選) — Hub上模型的修訂版本。可以是分支名稱、git標籤或任何提交ID。預設為main分支上的最新提交。
  • force_download (bool, 可選, 預設為 False) — 是否強制(重新)從Hub下載模型權重和配置檔案,覆蓋現有快取。
  • proxies (Dict[str, str], 可選) — 要按協議或端點使用的代理伺服器字典,例如{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}。代理用於每個請求。
  • token (strbool, 可選) — 用作遠端檔案HTTP bearer授權的token。預設情況下,它將使用執行hf auth login時快取的token。
  • 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)頭部而不是邏輯迴歸來載入SetFit。
  • normalize_embeddings (bool, 可選) — 是否對Sentence Transformer主體生成的嵌入應用歸一化。
  • span_context (int, 預設為 0) — 在完整句子中,應預置在 span 候選之前的單詞數量。對於方面模型預設為 0,對於極性模型預設為 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) — 用於將句子編碼為嵌入的批次大小。越高通常意味著處理速度越快,但記憶體使用量也越高。
  • 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_labelsTrueSetFitModel.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 = '使用 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授權的token。預設情況下,它將使用執行hf auth login時快取的token。
  • 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 ) strNone

引數

  • 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"])
< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.