CrossEncoder¶
CrossEncoder¶
关于 Cross-Encoders 的介绍,请参见 Cross-Encoders。
- class sentence_transformers.cross_encoder.CrossEncoder(model_name: str, num_labels: int | None = None, max_length: int | None = None, device: str | None = None, automodel_args: dict | None = None, tokenizer_args: dict | None = None, config_args: dict | None = None, cache_dir: str | None = None, trust_remote_code: bool = False, revision: str | None = None, local_files_only: bool = False, default_activation_function=None, classifier_dropout: float | None = None)[源代码][源代码]¶
CrossEncoder 接受两个句子/文本作为输入,并预测这对句子的分数或标签。例如,它可以预测句子对在 0 ... 1 范围内的相似度。
它不会生成句子嵌入,也不适用于单个句子。
- 参数:
model_name (str) -- 来自 Hugging Face Hub 的模型名称,可以使用 AutoModel 加载,或本地模型的路径。我们提供了几个预训练的 CrossEncoder 模型,可用于常见任务。
num_labels (int, optional) -- 分类器的标签数量。如果为1,CrossEncoder 是一个输出连续分数 0...1 的回归模型。如果大于1,它输出多个分数,这些分数可以通过soft-max得到不同类别的概率分数。默认为None。
max_length (int, optional) -- 输入序列的最大长度。较长的序列将被截断。如果为 None,将使用模型的最大长度。默认为 None。
device (str, optional) -- 用于模型的设备。如果为 None,将在可用时使用 CUDA。默认为 None。
automodel_args (Dict, optional) -- 传递给 AutoModelForSequenceClassification 的参数。默认为 None。
tokenizer_args (Dict, optional) -- 传递给 AutoTokenizer 的参数。默认为 None。
config_args (Dict, optional) -- 传递给 AutoConfig 的参数。默认为 None。
cache_dir (str, Path, optional) -- 存储缓存文件的文件夹路径。
trust_remote_code (bool, optional) -- 是否允许在Hub上定义的自定义模型使用其自己的建模文件。此选项仅应在您信任的存储库中设置为True,并且您已经阅读了代码,因为它将在您的本地机器上执行Hub上存在的代码。默认为False。
revision (Optional[str], optional) -- 要使用的特定模型版本。它可以是分支名称、标签名称或提交ID,用于Hugging Face上存储的模型。默认为None。
local_files_only (bool, optional) -- 如果
True
,避免下载模型。默认为 False。default_activation_function (Callable, optional) -- 可调用对象(如 nn.Sigmoid)关于应该在 model.predict() 之上使用的默认激活函数。如果为 None,则在 num_labels=1 时将使用 nn.Sigmoid(),否则使用 nn.Identity()。默认为 None。
classifier_dropout (float, optional) -- 分类头的丢弃率。默认为 None。
- fit(train_dataloader: ~torch.utils.data.dataloader.DataLoader, evaluator: ~sentence_transformers.evaluation.SentenceEvaluator.SentenceEvaluator | None = None, epochs: int = 1, loss_fct=None, activation_fct=Identity(), scheduler: str = 'WarmupLinear', warmup_steps: int = 10000, optimizer_class: type[~torch.optim.optimizer.Optimizer] = <class 'torch.optim.adamw.AdamW'>, optimizer_params: dict[str, object] = {'lr': 2e-05}, weight_decay: float = 0.01, evaluation_steps: int = 0, output_path: str | None = None, save_best_model: bool = True, max_grad_norm: float = 1, use_amp: bool = False, callback: ~typing.Callable[[float, int, int], None] | None = None, show_progress_bar: bool = True) None [源代码][源代码]¶
使用给定的训练目标训练模型。每个训练目标依次采样一个批次。我们只从每个目标中采样与最小目标中批次数量相同的批次,以确保每个数据集的训练均衡。
- 参数:
train_dataloader (DataLoader) -- 带有训练 InputExamples 的 DataLoader
evaluator (SentenceEvaluator, optional) -- 评估器 (sentence_transformers.evaluation) 在训练期间评估模型在保留的开发数据上的性能。它用于确定保存到磁盘的最佳模型。默认为 None。
epochs (int, optional) -- 训练的轮数。默认为1。
loss_fct -- 用于训练的损失函数。如果为 None,将使用 nn.BCEWithLogitsLoss() 如果 self.config.num_labels == 1 否则使用 nn.CrossEntropyLoss()。默认为 None。
activation_fct -- 应用于模型logits输出的激活函数。
scheduler (str, optional) -- 学习率调度器。可用调度器:constantlr、warmupconstant、warmuplinear、warmupcosine、warmupcosinewithhardrestarts。默认为“WarmupLinear”。
warmup_steps (int, optional) -- 行为取决于调度器。对于 WarmupLinear(默认),学习率从 0 增加到最大学习率。在这些训练步骤之后,学习率线性下降回零。默认为 10000。
optimizer_class (Type[Optimizer], optional) -- 优化器。默认为 torch.optim.AdamW。
optimizer_params (Dict[str, object], optional) -- 优化器参数。默认值为 {"lr": 2e-5}。
weight_decay (float, optional) -- 模型参数的权重衰减。默认为 0.01。
evaluation_steps (int, optional) -- 如果 > 0,在每训练若干步后使用评估器评估模型。默认为 0。
output_path (str, optional) -- 模型和评估文件的存储路径。默认为 None。
save_best_model (bool, optional) -- 如果为真,最佳模型(根据评估器)将存储在 output_path 中。默认为 True。
max_grad_norm (float, optional) -- 用于梯度归一化。默认为 1。
use_amp (bool, optional) -- 使用自动混合精度(AMP)。仅适用于 Pytorch >= 1.6.0。默认为 False。
callback (Callable[[float, int, int], None], optional) -- 回调函数,在每次评估后调用。它必须按顺序接受以下三个参数:
score
、epoch
、steps
。默认为 None。show_progress_bar (bool, optional) -- 如果为 True,则输出 tqdm 进度条。默认为 True。
- predict(sentences: tuple[str, str] | list[str], batch_size: int = 32, show_progress_bar: bool | None = None, num_workers: int = 0, activation_fct: Callable | None = None, apply_softmax: bool | None = False, convert_to_numpy: Literal[False] = True, convert_to_tensor: Literal[False] = False) Tensor [源代码][源代码]¶
- predict(sentences: list[tuple[str, str]] | list[list[str]] | tuple[str, str] | list[str], batch_size: int = 32, show_progress_bar: bool | None = None, num_workers: int = 0, activation_fct: Callable | None = None, apply_softmax: bool | None = False, convert_to_numpy: Literal[True] = True, convert_to_tensor: Literal[False] = False) ndarray
- predict(sentences: list[tuple[str, str]] | list[list[str]] | tuple[str, str] | list[str], batch_size: int = 32, show_progress_bar: bool | None = None, num_workers: int = 0, activation_fct: Callable | None = None, apply_softmax: bool | None = False, convert_to_numpy: bool = True, convert_to_tensor: Literal[True] = False) Tensor
- predict(sentences: list[tuple[str, str]] | list[list[str]], batch_size: int = 32, show_progress_bar: bool | None = None, num_workers: int = 0, activation_fct: Callable | None = None, apply_softmax: bool | None = False, convert_to_numpy: Literal[False] = True, convert_to_tensor: Literal[False] = False) list[Tensor]
在给定的句子对上使用CrossEncoder进行预测。
- 参数:
sentences (Union[List[Tuple[str, str]], Tuple[str, str]]) -- 句子对列表 [(Sent1, Sent2), (Sent3, Sent4)] 或一个句子对 (Sent1, Sent2)。
batch_size (int, optional) -- 编码的批处理大小。默认为 32。
show_progress_bar (bool, optional) -- 输出进度条。默认为 None。
num_workers (int, optional) -- 用于分词的工作者数量。默认为 0。
activation_fct (callable, optional) -- 应用于 CrossEncoder 的 logits 输出的激活函数。如果为 None,当 num_labels=1 时将使用 nn.Sigmoid(),否则使用 nn.Identity。默认为 None。
convert_to_numpy (bool, optional) -- 将输出转换为 numpy 矩阵。默认为 True。
apply_softmax (bool, optional) -- 如果有超过2个维度且 apply_softmax=True,则对 logits 输出应用 softmax。默认为 False。
convert_to_tensor (bool, optional) -- 将输出转换为张量。默认为 False。
- 返回:
对已通过的句子对进行预测。返回类型取决于
convert_to_numpy
和convert_to_tensor
参数。如果convert_to_tensor
为 True,输出将是 torch.Tensor。如果convert_to_numpy
为 True,输出将是 numpy.ndarray。否则,输出将是浮点值列表。- 返回类型:
Union[List[float], np.ndarray, torch.Tensor]
示例
from sentence_transformers import CrossEncoder model = CrossEncoder("cross-encoder/stsb-roberta-base") sentences = [["I love cats", "Cats are amazing"], ["I prefer dogs", "Dogs are loyal"]] model.predict(sentences) # => array([0.6912767, 0.4303499], dtype=float32)
- push_to_hub(repo_id: str, use_temp_dir: bool | None = None, commit_message: str | None = None, private: bool | None = None, token: bool | str | None = None, max_shard_size: int | str | None = '5GB', create_pr: bool = False, safe_serialization: bool = True, revision: str = None, commit_description: str = None, tags: List[str] | None = None, **deprecated_kwargs) str ¶
将 {object_files} 上传到 🤗 Model Hub。
- 参数:
repo_id (str) -- 您想要推送 {object} 的仓库名称。当推送到特定组织时,应包含您的组织名称。
use_temp_dir (bool, optional) -- 是否使用临时目录来存储在推送到Hub之前保存的文件。如果没有名为
repo_id
的目录,将默认设置为True
,否则为False
。commit_message (str, optional) -- 推送时的提交信息。将默认为
"上传 {object}"
。private (bool, optional) -- 创建的仓库是否应为私有。
token (bool or str, optional) -- 用于远程文件的HTTP承载授权的令牌。如果为
True
,将使用运行huggingface-cli login
时生成的令牌(存储在~/.huggingface
中)。如果未指定repo_url
,则默认为True
。max_shard_size (int or str, optional, defaults to "5GB") -- 仅适用于模型。分片前的检查点最大大小。检查点分片的大小将小于此大小。如果以字符串形式表示,需要是数字后跟单位(如
"5MB"
)。我们默认设置为"5GB"
,以便用户可以在免费层的 Google Colab 实例上轻松加载模型,而不会出现任何 CPU 内存不足的问题。create_pr (bool, optional, defaults to False) -- 是否使用上传的文件创建PR或直接提交。
safe_serialization (bool, optional, defaults to True) -- 是否将模型权重转换为safetensors格式以实现更安全的序列化。
revision (str, optional) -- 推送上传文件的分支。
commit_description (str, optional) -- 将要创建的提交的描述
tags (List[str], optional) -- 要推送到Hub的标签列表。
示例:
```python from transformers import {object_class}
{object} = {object_class}.from_pretrained("google-bert/bert-base-cased")
# Push the {object} to your namespace with the name "my-finetuned-bert". {object}.push_to_hub("my-finetuned-bert")
# Push the {object} to an organization with the name "my-finetuned-bert". {object}.push_to_hub("huggingface/my-finetuned-bert") ```
- rank(query: str, documents: list[str], top_k: int | None = None, return_documents: bool = False, batch_size: int = 32, show_progress_bar: bool | None = None, num_workers: int = 0, activation_fct=None, apply_softmax=False, convert_to_numpy: bool = True, convert_to_tensor: bool = False) list[dict[Literal['corpus_id', 'score', 'text'], int | float | str]] [源代码][源代码]¶
使用 CrossEncoder 对给定的查询和文档进行排序。返回一个包含文档索引和分数的排序列表。
- 参数:
query (str) -- 一个单独的查询。
documents (List[str]) -- 文档列表。
top_k (Optional[int], optional) -- 返回前 k 个文档。如果为 None,则返回所有文档。默认为 None。
return_documents (bool, optional) -- 如果为 True,则同时返回文档。如果为 False,则仅返回索引和分数。默认为 False。
batch_size (int, optional) -- 编码的批处理大小。默认为 32。
show_progress_bar (bool, optional) -- 输出进度条。默认为 None。
num_workers (int, optional) -- 用于分词的工作者数量。默认为 0。
activation_fct ([type], optional) -- 应用于 CrossEncoder 的 logits 输出的激活函数。如果为 None,当 num_labels=1 时将使用 nn.Sigmoid(),否则使用 nn.Identity。默认为 None。
convert_to_numpy (bool, optional) -- 将输出转换为 numpy 矩阵。默认为 True。
apply_softmax (bool, optional) -- 如果有超过2个维度且 apply_softmax=True,则对 logits 输出应用 softmax。默认为 False。
convert_to_tensor (bool, optional) -- 将输出转换为张量。默认为 False。
- 返回:
一个包含“corpus_id”、“score”以及可选的“text”的文档的排序列表。
- 返回类型:
List[Dict[Literal["corpus_id", "score", "text"], Union[int, float, str]]]
示例
from sentence_transformers import CrossEncoder model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2") query = "Who wrote 'To Kill a Mockingbird'?" documents = [ "'To Kill a Mockingbird' is a novel by Harper Lee published in 1960. It was immediately successful, winning the Pulitzer Prize, and has become a classic of modern American literature.", "The novel 'Moby-Dick' was written by Herman Melville and first published in 1851. It is considered a masterpiece of American literature and deals with complex themes of obsession, revenge, and the conflict between good and evil.", "Harper Lee, an American novelist widely known for her novel 'To Kill a Mockingbird', was born in 1926 in Monroeville, Alabama. She received the Pulitzer Prize for Fiction in 1961.", "Jane Austen was an English novelist known primarily for her six major novels, which interpret, critique and comment upon the British landed gentry at the end of the 18th century.", "The 'Harry Potter' series, which consists of seven fantasy novels written by British author J.K. Rowling, is among the most popular and critically acclaimed books of the modern era.", "'The Great Gatsby', a novel written by American author F. Scott Fitzgerald, was published in 1925. The story is set in the Jazz Age and follows the life of millionaire Jay Gatsby and his pursuit of Daisy Buchanan." ] model.rank(query, documents, return_documents=True)
[{'corpus_id': 0, 'score': 10.67858, 'text': "'To Kill a Mockingbird' is a novel by Harper Lee published in 1960. It was immediately successful, winning the Pulitzer Prize, and has become a classic of modern American literature."}, {'corpus_id': 2, 'score': 9.761677, 'text': "Harper Lee, an American novelist widely known for her novel 'To Kill a Mockingbird', was born in 1926 in Monroeville, Alabama. She received the Pulitzer Prize for Fiction in 1961."}, {'corpus_id': 1, 'score': -3.3099542, 'text': "The novel 'Moby-Dick' was written by Herman Melville and first published in 1851. It is considered a masterpiece of American literature and deals with complex themes of obsession, revenge, and the conflict between good and evil."}, {'corpus_id': 5, 'score': -4.8989105, 'text': "'The Great Gatsby', a novel written by American author F. Scott Fitzgerald, was published in 1925. The story is set in the Jazz Age and follows the life of millionaire Jay Gatsby and his pursuit of Daisy Buchanan."}, {'corpus_id': 4, 'score': -5.082967, 'text': "The 'Harry Potter' series, which consists of seven fantasy novels written by British author J.K. Rowling, is among the most popular and critically acclaimed books of the modern era."}]