Logo

开始使用

  • 安装
    • 使用 pip 安装
    • 使用 Conda 安装
    • 从源码安装
    • 可编辑安装
    • 安装支持 CUDA 的 PyTorch
  • 快速入门
    • 句子转换器 (Sentence Transformer)
    • 交叉编码器 (Cross Encoder)
    • 稀疏编码器 (Sparse Encoder)
    • 后续步骤
  • 迁移指南
    • 从 v4.x 迁移到 v5.x
      • model.encode 的迁移
      • 从 Asym 迁移到 Router
      • 高级用法的迁移
    • 从 v3.x 迁移到 v4.x
      • 关于 CrossEncoder 初始化和方法中参数的迁移
      • 关于 CrossEncoder.fit 中特定参数的迁移
      • CrossEncoder 评估器的迁移
    • 从 v2.x 迁移到 v3.x
      • 关于 SentenceTransformer.fit 中特定参数的迁移
      • 在 SentenceTransformer.fit 中使用的自定义数据集和数据加载器的迁移

句子转换器 (Sentence Transformer)

  • 用法
    • 计算嵌入 (Embeddings)
      • 初始化一个句子转换器模型 (Sentence Transformer Model)
      • 计算嵌入 (Embeddings)
      • 提示模板 (Prompt Templates)
      • 输入序列长度
      • 多进程 / 多 GPU 编码
    • 语义文本相似度
      • 相似度计算
    • 语义搜索
      • 背景
      • 对称与非对称语义搜索
      • 手动实现
      • 优化实现
      • 速度优化
      • Elasticsearch
      • OpenSearch
      • 近似最近邻
      • 检索与重排 (Retrieve & Re-Rank)
      • 示例
    • 检索与重排 (Retrieve & Re-Rank)
      • 检索与重排流程 (Retrieve & Re-Rank Pipeline)
      • 检索:双编码器 (Bi-Encoder)
      • 重排器:交叉编码器 (Cross-Encoder)
      • 示例脚本
      • 预训练的双编码器 (检索)
      • 预训练的交叉编码器 (重排器)
    • 聚类
      • k-均值 (k-Means)
      • 层次聚类 (Agglomerative Clustering)
      • 快速聚类
      • 主题建模
    • 释义挖掘 (Paraphrase Mining)
      • paraphrase_mining()
    • 翻译句对挖掘 (Translated Sentence Mining)
      • 基于边界的挖掘 (Margin Based Mining)
      • 示例
    • 图像搜索
      • 安装
      • 用法
      • 示例
    • 嵌入量化 (Embedding Quantization)
      • 二值量化 (Binary Quantization)
      • 标量 (int8) 量化
      • 其他扩展
      • 演示
      • 亲自尝试
    • 创建自定义模型
      • 句子转换器模型的结构
      • 从 Transformers 模型创建句子转换器模型
      • 高级:自定义模块
    • 使用 MTEB 进行评估
      • 安装
      • 评估
      • 附加参数
      • 结果处理
      • 排行榜提交
    • 加速推理
      • PyTorch
      • ONNX
      • OpenVINO
      • 基准测试
  • 预训练模型
    • 原始模型
    • 语义搜索模型
      • 多问答模型
      • MSMARCO 段落模型
    • 多语言模型
      • 语义相似度模型
      • 双语文本挖掘
    • 图像与文本模型
    • INSTRUCTOR 模型
    • 科学相似度模型
  • 训练概述
    • 为何要微调?
    • 训练组件
    • 模型
    • 数据集
      • 数据集格式
    • 损失函数
    • 训练参数
    • 评估器
    • 训练器 (Trainer)
      • 回调 (Callbacks)
    • 多数据集训练
    • 已弃用的训练
    • 最佳基础嵌入模型
    • 与交叉编码器训练的比较
  • 数据集概览
    • Hugging Face Hub 上的数据集
    • 已存在的数据集
  • 损失函数概览
    • 损失函数表
    • 损失修改器
    • 蒸馏
    • 常用损失函数
    • 自定义损失函数
  • 训练示例
    • 语义文本相似度
      • 训练数据
      • 损失函数
    • 自然语言推断
      • 数据
      • SoftmaxLoss
      • MultipleNegativesRankingLoss
    • 释义数据 (Paraphrase Data)
      • 预训练模型
    • Quora 重复问题
      • 训练
      • MultipleNegativesRankingLoss
      • 预训练模型
    • MS MARCO
      • 双编码器 (Bi-Encoder)
    • 套娃嵌入 (Matryoshka Embeddings)
      • 用例
      • 结果
      • 训练
      • 推理
      • 代码示例
    • 自适应层 (Adaptive Layers)
      • 用例
      • 结果
      • 训练
      • 推理
      • 代码示例
    • 多语言模型
      • 扩展您自己的模型
      • 训练
      • 数据集
      • 训练数据来源
      • 评估
      • 可用的预训练模型
      • 用法
      • 性能
      • 引用
    • 模型蒸馏
      • 知识蒸馏
      • 速度-性能权衡
      • 降维
      • 量化
    • 增强型 SBERT (Augmented SBERT)
      • 动机
      • 扩展到您自己的数据集
      • 方法论
      • 场景 1:有限或小型的已标注数据集(少量带标签的句对)
      • 场景 2:无已标注数据集(只有未标注的句对)
      • 训练
      • 引用
    • 使用提示进行训练
      • 什么是提示?
      • 为什么我们要使用提示进行训练?
      • 我们如何使用提示进行训练?
    • 使用 PEFT 适配器进行训练
      • 兼容性方法
      • 添加新适配器
      • 加载预训练的适配器
      • 训练脚本
    • 无监督学习
      • TSDAE
      • SimCSE
      • CT
      • CT (批内负采样)
      • 掩码语言模型 (MLM)
      • GenQ
      • GPL
      • 性能比较
    • 领域自适应
      • 领域自适应与无监督学习
      • 自适应预训练
      • GPL:生成式伪标签
    • 超参数优化
      • HPO 组件
      • 整合所有内容
      • 示例脚本
    • 分布式训练
      • 比较
      • FSDP

交叉编码器 (Cross Encoder)

  • 用法
    • 交叉编码器 vs 双编码器
      • 交叉编码器 vs. 双编码器
      • 何时使用交叉/双编码器?
      • 交叉编码器用法
      • 结合双编码器和交叉编码器
      • 训练交叉编码器
    • 检索与重排 (Retrieve & Re-Rank)
      • 检索与重排流程 (Retrieve & Re-Rank Pipeline)
      • 检索:双编码器 (Bi-Encoder)
      • 重排器:交叉编码器 (Cross-Encoder)
      • 示例脚本
      • 预训练的双编码器 (检索)
      • 预训练的交叉编码器 (重排器)
    • 加速推理
      • PyTorch
      • ONNX
      • OpenVINO
      • 基准测试
  • 预训练模型
    • MS MARCO
    • SQuAD (QNLI)
    • STSbenchmark
    • Quora 重复问题
    • NLI
    • 社区模型
  • 训练概述
    • 为何要微调?
    • 训练组件
    • 模型
    • 数据集
      • 数据集格式
      • 难负例挖掘 (Hard Negatives Mining)
    • 损失函数
    • 训练参数
    • 评估器
    • 训练器 (Trainer)
      • 回调 (Callbacks)
    • 多数据集训练
    • 训练技巧
    • 已弃用的训练
    • 与 SentenceTransformer 训练的比较
  • 损失函数概览
    • 损失函数表
    • 蒸馏
    • 常用损失函数
    • 自定义损失函数
  • 训练示例
    • 语义文本相似度
      • 训练数据
      • 损失函数
      • 推理
    • 自然语言推断
      • 数据
      • CrossEntropyLoss
      • 推理
    • Quora 重复问题
      • 训练
      • 推理
    • MS MARCO
      • 交叉编码器 (Cross Encoder)
      • 训练脚本
      • 推理
    • 重排器 (Rerankers)
      • BinaryCrossEntropyLoss
      • CachedMultipleNegativesRankingLoss
      • 推理
    • 模型蒸馏
      • 交叉编码器知识蒸馏
      • 推理
    • 分布式训练
      • 比较
      • FSDP

稀疏编码器 (Sparse Encoder)

  • 用法
    • 计算稀疏嵌入
      • 初始化稀疏编码器模型
      • 计算嵌入 (Embeddings)
      • 输入序列长度
      • 控制稀疏度
      • 使用 SPLADE 模型的可解释性
      • 多进程 / 多 GPU 编码
    • 语义文本相似度
      • 相似度计算
    • 语义搜索
      • 手动搜索
      • 向量数据库搜索
      • Qdrant 集成
      • OpenSearch 集成
      • Elasticsearch 集成
      • Seismic 集成
      • SPLADE-index 集成
    • 检索与重排 (Retrieve & Re-Rank)
      • 概述
      • 交互式演示:简单维基百科搜索
      • 综合评估:混合搜索管道
      • 预训练模型
    • 稀疏编码器评估
      • 带检索评估的示例
    • 加速推理
      • PyTorch
      • ONNX
      • OpenVINO
      • 基准测试
  • 预训练模型
    • 核心 SPLADE 模型
    • 免推理 SPLADE 模型
    • 模型合集
  • 训练概述
    • 为何要微调?
    • 训练组件
    • 模型
    • 数据集
      • 数据集格式
    • 损失函数
    • 训练参数
    • 评估器
    • 训练器 (Trainer)
      • 回调 (Callbacks)
    • 多数据集训练
    • 训练技巧
  • 数据集概览
    • Hugging Face Hub 上的数据集
    • 已存在的数据集
  • 损失函数概览
    • 稀疏专用损失函数
      • SPLADE 损失
      • CSR 损失
    • 损失函数表
    • 蒸馏
    • 常用损失函数
    • 自定义损失函数
  • 训练示例
    • 模型蒸馏
      • MarginMSE
    • MS MARCO
      • SparseMultipleNegativesRankingLoss
    • 语义文本相似度
      • 训练数据
      • 损失函数
    • 自然语言推断
      • 数据
      • SpladeLoss
    • Quora 重复问题
      • 训练
    • 信息检索
      • SparseMultipleNegativesRankingLoss (MNRL)
      • 推理与评估
    • 分布式训练
      • 比较
      • FSDP

包参考

  • 句子转换器 (Sentence Transformer)
    • SentenceTransformer
      • SentenceTransformer
      • SentenceTransformerModelCardData
      • SimilarityFunction
    • 训练器 (Trainer)
      • SentenceTransformerTrainer
    • 训练参数
      • SentenceTransformerTrainingArguments
    • 损失函数
      • BatchAllTripletLoss
      • BatchHardSoftMarginTripletLoss
      • BatchHardTripletLoss
      • BatchSemiHardTripletLoss
      • ContrastiveLoss
      • OnlineContrastiveLoss
      • ContrastiveTensionLoss
      • ContrastiveTensionLossInBatchNegatives
      • CoSENTLoss
      • AnglELoss
      • CosineSimilarityLoss
      • DenoisingAutoEncoderLoss
      • GISTEmbedLoss
      • CachedGISTEmbedLoss
      • MSELoss
      • MarginMSELoss
      • MatryoshkaLoss
      • Matryoshka2dLoss
      • AdaptiveLayerLoss
      • MegaBatchMarginLoss
      • MultipleNegativesRankingLoss
      • CachedMultipleNegativesRankingLoss
      • MultipleNegativesSymmetricRankingLoss
      • CachedMultipleNegativesSymmetricRankingLoss
      • SoftmaxLoss
      • TripletLoss
      • DistillKLDivLoss
    • 采样器
      • 批处理采样器
      • 多数据集批处理采样器
    • 评估
      • BinaryClassificationEvaluator
      • EmbeddingSimilarityEvaluator
      • InformationRetrievalEvaluator
      • NanoBEIREvaluator
      • MSEEvaluator
      • ParaphraseMiningEvaluator
      • RerankingEvaluator
      • SentenceEvaluator
      • SequentialEvaluator
      • TranslationEvaluator
      • TripletEvaluator
    • 数据集
      • ParallelSentencesDataset
      • SentenceLabelDataset
      • DenoisingAutoEncoderDataset
      • NoDuplicatesDataLoader
    • 模块
      • 主模块
      • 更多模块
      • 基础模块
    • quantization
      • quantize_embeddings()
      • semantic_search_faiss()
      • semantic_search_usearch()
  • 交叉编码器 (Cross Encoder)
    • CrossEncoder
      • CrossEncoder
      • CrossEncoderModelCardData
    • 训练器 (Trainer)
      • CrossEncoderTrainer
    • 训练参数
      • CrossEncoderTrainingArguments
    • 损失函数
      • BinaryCrossEntropyLoss
      • CrossEntropyLoss
      • LambdaLoss
      • ListMLELoss
      • PListMLELoss
      • ListNetLoss
      • MultipleNegativesRankingLoss
      • CachedMultipleNegativesRankingLoss
      • MSELoss
      • MarginMSELoss
      • RankNetLoss
    • 评估
      • CrossEncoderRerankingEvaluator
      • CrossEncoderNanoBEIREvaluator
      • CrossEncoderClassificationEvaluator
      • CrossEncoderCorrelationEvaluator
  • 稀疏编码器 (Sparse Encoder)
    • SparseEncoder
      • SparseEncoder
      • SparseEncoderModelCardData
      • SimilarityFunction
    • 训练器 (Trainer)
      • SparseEncoderTrainer
    • 训练参数
      • SparseEncoderTrainingArguments
    • 损失函数
      • SpladeLoss
      • FlopsLoss
      • CSRLoss
      • CSRReconstructionLoss
      • SparseMultipleNegativesRankingLoss
      • SparseMarginMSELoss
      • SparseDistillKLDivLoss
      • SparseTripletLoss
      • SparseCosineSimilarityLoss
      • SparseCoSENTLoss
      • SparseAnglELoss
      • SparseMSELoss
    • 采样器
      • 批处理采样器
      • 多数据集批处理采样器
    • 评估
      • SparseInformationRetrievalEvaluator
      • SparseNanoBEIREvaluator
      • SparseEmbeddingSimilarityEvaluator
      • SparseBinaryClassificationEvaluator
      • SparseTripletEvaluator
      • SparseRerankingEvaluator
      • SparseTranslationEvaluator
      • SparseMSEEvaluator
      • ReciprocalRankFusionEvaluator
    • 模块
      • SPLADE 池化
      • MLM Transformer
      • 稀疏自编码器 (SparseAutoEncoder)
      • 稀疏静态嵌入 (SparseStaticEmbedding)
    • 回调 (Callbacks)
      • SpladeRegularizerWeightSchedulerCallback
    • 搜索引擎
      • semantic_search_elasticsearch()
      • semantic_search_opensearch()
      • semantic_search_qdrant()
      • semantic_search_seismic()
  • util
    • 辅助函数
      • community_detection()
      • http_get()
      • is_training_available()
      • mine_hard_negatives()
      • normalize_embeddings()
      • paraphrase_mining()
      • semantic_search()
      • truncate_embeddings()
    • 模型优化
      • export_dynamic_quantized_onnx_model()
      • export_optimized_onnx_model()
      • export_static_quantized_openvino_model()
    • 相似度度量
      • cos_sim()
      • dot_score()
      • euclidean_sim()
      • manhattan_sim()
      • pairwise_cos_sim()
      • pairwise_dot_score()
      • pairwise_euclidean_sim()
      • pairwise_manhattan_sim()
Sentence Transformers
  • 用法
  • 语义搜索
  • 在 GitHub 上编辑

语义搜索

语义搜索旨在通过理解搜索查询和语料库的语义含义来提高搜索准确性。与只能基于词汇匹配查找文档的关键词搜索引擎不同,语义搜索在给定同义词、缩写和拼写错误时也能表现良好。

背景

语义搜索的理念是将语料库中的所有条目(无论是句子、段落还是文档)嵌入到向量空间中。在搜索时,查询被嵌入到相同的向量空间中,然后找到与语料库中最接近的嵌入。这些条目应与查询具有高度的语义相似性。

SemanticSearch

对称式与非对称式语义搜索

对于您的设置来说,一个关键区别是对称式与非对称式语义搜索

  • 对于对称式语义搜索,您的查询和语料库中的条目长度和内容大致相同。一个例子是搜索相似问题:您的查询可以是“How to learn Python online?”,您想找到一个类似“How to learn Python on the web?”的条目。对于对称任务,您可能会颠倒查询和语料库中的条目。

    • 相关训练示例:Quora 重复问题。

    • 适用模型:预训练句子嵌入模型

  • 对于非对称式语义搜索,您通常有一个短查询(例如问题或一些关键词),并且您想找到一个较长的段落来回答该查询。一个例子是像“What is Python”这样的查询,您想找到段落“Python is an interpreted, high-level and general-purpose programming language. Python’s design philosophy …”。对于非对称任务,颠倒查询和语料库中的条目通常没有意义。

    • 相关训练示例:MS MARCO

    • 适用模型:预训练 MS MARCO 模型

为您的任务类型选择正确的模型至关重要。

提示

对于非对称式语义搜索,建议您使用SentenceTransformer.encode_query来编码您的查询,并使用SentenceTransformer.encode_document来编码您的语料库。

更通用的SentenceTransformer.encode方法与SentenceTransformer.encode_query和SentenceTransformer.encode_document有两点不同

  1. 如果未提供 prompt_name 或 prompt,它将使用模型 prompts 字典中指定的预定义“query”或“document”提示。

  2. 它将 task 设置为“document”。如果模型具有 Router 模块,它将使用“query”或“document”任务类型来通过适当的子模块路由输入。

请注意,SentenceTransformer.encode 是最通用的方法,可用于任何任务,包括信息检索。如果模型未经预定义提示和/或任务类型训练,则所有这三种方法将返回相同的嵌入。

手动实现

对于小型语料库(最多约 100 万个条目),我们可以通过手动实现语义搜索,即使用 SentenceTransformer.encode_document 计算语料库的嵌入,并使用 SentenceTransformer.encode_query 计算查询的嵌入,然后使用 SentenceTransformer.similarity 计算语义文本相似度。

有关简单示例,请参阅 semantic_search.py

输出

Query: How do artificial neural networks work?
Top 5 most similar sentences in corpus:
(Score: 0.5926) Neural networks are computing systems vaguely inspired by the biological neural networks that constitute animal brains.
(Score: 0.5288) Deep learning is part of a broader family of machine learning methods based on artificial neural networks with representation learning.
(Score: 0.4647) Machine learning is a field of study that gives computers the ability to learn without being explicitly programmed.
(Score: 0.1381) Mars rovers are robotic vehicles designed to travel on the surface of Mars to collect data and perform experiments.
(Score: 0.0912) Carbon capture technologies aim to collect CO2 emissions before they enter the atmosphere and store them underground.

Query: What technology is used for modern space exploration?
Top 5 most similar sentences in corpus:
(Score: 0.3754) Mars rovers are robotic vehicles designed to travel on the surface of Mars to collect data and perform experiments.
(Score: 0.3669) SpaceX's Starship is designed to be a fully reusable transportation system capable of carrying humans to Mars and beyond.
(Score: 0.3452) The James Webb Space Telescope is the largest optical telescope in space, designed to conduct infrared astronomy.
(Score: 0.2625) Renewable energy sources include solar, wind, hydro, and geothermal power that naturally replenish over time.
(Score: 0.2275) Carbon capture technologies aim to collect CO2 emissions before they enter the atmosphere and store them underground.

Query: How can we address climate change challenges?
Top 5 most similar sentences in corpus:
(Score: 0.3760) Global warming is the long-term heating of Earth's climate system observed since the pre-industrial period due to human activities.
(Score: 0.3144) Carbon capture technologies aim to collect CO2 emissions before they enter the atmosphere and store them underground.
(Score: 0.2948) Renewable energy sources include solar, wind, hydro, and geothermal power that naturally replenish over time.
(Score: 0.0420) Machine learning is a field of study that gives computers the ability to learn without being explicitly programmed.
(Score: 0.0411) Deep learning is part of a broader family of machine learning methods based on artificial neural networks with representation learning.
"""
This is a simple application for sentence embeddings: semantic search

We have a corpus with various sentences. Then, for a given query sentence,
we want to find the most similar sentence in this corpus.

This script outputs for various queries the top 5 most similar sentences in the corpus.
"""

import torch

from sentence_transformers import SentenceTransformer

embedder = SentenceTransformer("all-MiniLM-L6-v2")

# Corpus with example documents
corpus = [
    "Machine learning is a field of study that gives computers the ability to learn without being explicitly programmed.",
    "Deep learning is part of a broader family of machine learning methods based on artificial neural networks with representation learning.",
    "Neural networks are computing systems vaguely inspired by the biological neural networks that constitute animal brains.",
    "Mars rovers are robotic vehicles designed to travel on the surface of Mars to collect data and perform experiments.",
    "The James Webb Space Telescope is the largest optical telescope in space, designed to conduct infrared astronomy.",
    "SpaceX's Starship is designed to be a fully reusable transportation system capable of carrying humans to Mars and beyond.",
    "Global warming is the long-term heating of Earth's climate system observed since the pre-industrial period due to human activities.",
    "Renewable energy sources include solar, wind, hydro, and geothermal power that naturally replenish over time.",
    "Carbon capture technologies aim to collect CO2 emissions before they enter the atmosphere and store them underground.",
]
# Use "convert_to_tensor=True" to keep the tensors on GPU (if available)
corpus_embeddings = embedder.encode_document(corpus, convert_to_tensor=True)

# Query sentences:
queries = [
    "How do artificial neural networks work?",
    "What technology is used for modern space exploration?",
    "How can we address climate change challenges?",
]

# Find the closest 5 sentences of the corpus for each query sentence based on cosine similarity
top_k = min(5, len(corpus))
for query in queries:
    query_embedding = embedder.encode_query(query, convert_to_tensor=True)

    # We use cosine-similarity and torch.topk to find the highest 5 scores
    similarity_scores = embedder.similarity(query_embedding, corpus_embeddings)[0]
    scores, indices = torch.topk(similarity_scores, k=top_k)

    print("\nQuery:", query)
    print("Top 5 most similar sentences in corpus:")

    for score, idx in zip(scores, indices):
        print(f"(Score: {score:.4f})", corpus[idx])

    """
    # Alternatively, we can also use util.semantic_search to perform cosine similarty + topk
    hits = util.semantic_search(query_embedding, corpus_embeddings, top_k=5)
    hits = hits[0]      #Get the hits for the first query
    for hit in hits:
        print(corpus[hit['corpus_id']], "(Score: {:.4f})".format(hit['score']))
    """

优化实现

您无需自己实现语义搜索,可以使用 util.semantic_search 函数。

该函数接受以下参数

sentence_transformers.util.semantic_search(query_embeddings: ~torch.Tensor, corpus_embeddings: ~torch.Tensor, query_chunk_size: int = 100, corpus_chunk_size: int = 500000, top_k: int = 10, score_function: ~collections.abc.Callable[[~torch.Tensor, ~torch.Tensor], ~torch.Tensor] = <function cos_sim>) → list[list[dict[str, int | float]]][source]

此函数默认执行查询嵌入列表和语料库嵌入列表之间的余弦相似度搜索。它可用于信息检索/语义搜索,适用于最多约 100 万个条目的语料库。

参数:
  • query_embeddings (Tensor) – 包含查询嵌入的二维张量。可以是稀疏张量。

  • corpus_embeddings (Tensor) – 包含语料库嵌入的二维张量。可以是稀疏张量。

  • query_chunk_size (int, optional) – 同时处理 100 个查询。增加此值可提高速度,但需要更多内存。默认为 100。

  • corpus_chunk_size (int, optional) – 每次扫描语料库 10 万个条目。增加此值可提高速度,但需要更多内存。默认为 500000。

  • top_k (int, optional) – 检索 top k 个匹配条目。默认为 10。

  • score_function (Callable[[Tensor, Tensor], Tensor], optional) – 用于计算分数的函数。默认是余弦相似度。

返回:

一个列表,每个查询包含一个条目。每个条目是一个字典列表,包含“corpus_id”和“score”键,按余弦相似度分数降序排列。

返回类型:

List[List[Dict[str, Union[int, float]]]]

默认情况下,最多同时处理 100 个查询。此外,语料库被分块为最多 50 万个条目的集合。您可以增加 query_chunk_size 和 corpus_chunk_size,这会提高大型语料库的速度,但也会增加内存需求。

速度优化

为了使 util.semantic_search 方法达到最佳速度,建议将 query_embeddings 和 corpus_embeddings 放在同一个 GPU 设备上。这将显著提升性能。此外,我们可以将语料库嵌入归一化,使每个语料库嵌入的长度为 1。在这种情况下,我们可以使用点积来计算分数。

corpus_embeddings = corpus_embeddings.to("cuda")
corpus_embeddings = util.normalize_embeddings(corpus_embeddings)

query_embeddings = query_embeddings.to("cuda")
query_embeddings = util.normalize_embeddings(query_embeddings)
hits = util.semantic_search(query_embeddings, corpus_embeddings, score_function=util.dot_score)

Elasticsearch

Elasticsearch 能够索引密集向量并将其用于文档评分。我们可以轻松地索引嵌入向量,存储其他数据以及向量,最重要的是,通过对嵌入使用近似最近邻搜索(HNSW,另见下文)来高效检索相关条目。

有关更多详细信息,请参阅 semantic_search_quora_elasticsearch.py。

OpenSearch

OpenSearch 是一个社区驱动的开源搜索引擎,支持向量搜索功能。它允许您索引密集向量并使用近似最近邻算法执行高效的相似度搜索。OpenSearch 可用于实现传统的基于关键词的搜索(BM25)和语义搜索,从而可以比较和结合这两种方法。

有关示例实现,请参阅 semantic_search_nq_opensearch.py,其中展示了如何将 OpenSearch 与自然问题数据集一起使用,演示了语义搜索和 BM25 搜索功能。

近似最近邻

如果使用精确最近邻搜索(如 util.semantic_search 所用),搜索包含数百万嵌入的大型语料库可能非常耗时。

在这种情况下,近似最近邻 (ANN) 会很有帮助。在此,数据被分成较小的相似嵌入片段。即使您拥有数百万个向量,该索引也可以高效搜索,并且可以在几毫秒内检索到相似度最高的嵌入(最近邻)。然而,结果不一定是精确的。可能会错过一些高相似度的向量。

对于所有 ANN 方法,通常有一个或多个参数可调整,这些参数决定了召回率-速度的权衡。如果您想要最高速度,则错过命中的可能性很高。如果您想要高召回率,则搜索速度会降低。

三个流行的近似最近邻库是 Annoy、FAISS 和 hnswlib。

示例

  • semantic_search_quora_hnswlib.py

  • semantic_search_quora_annoy.py

  • semantic_search_quora_faiss.py

检索与重排

对于复杂的语义搜索场景,建议采用两阶段的检索和重排序管道:信息检索

有关更多详细信息,请参阅 检索和重排序。

示例

我们列举了一些常见用例

相似问题检索

semantic_search_quora_pytorch.py [ Colab 版本 ] 展示了一个基于 Quora 重复问题数据集的示例。用户可以输入一个问题,代码使用 util.semantic_search 从数据集中检索最相似的问题。作为模型,我们使用 distilbert-multilingual-nli-stsb-quora-ranking,该模型经过训练以识别相似问题,并支持 50 多种语言。因此,用户可以使用 50 多种语言中的任何一种输入问题。这是一个对称搜索任务,因为搜索查询与语料库中的问题具有相同的长度和内容。

相似出版物检索

semantic_search_publications.py [ Colab 版本 ] 展示了一个如何查找相似科学出版物的示例。作为语料库,我们使用了在 EMNLP 2016 - 2018 会议上发表的所有出版物。作为搜索查询,我们输入了最近出版物的标题和摘要,并从我们的语料库中找到了相关的出版物。我们使用了 SPECTER 模型。这是一个对称搜索任务,因为语料库中的论文由标题和摘要组成,我们搜索的也是标题和摘要。

问答检索

semantic_search_wikipedia_qa.py [ Colab 版本 ]:此示例使用了一个在 Natural Questions 数据集上训练的模型。它包含大约 10 万个真实的 Google 搜索查询,以及维基百科中提供答案的带注释段落。这是一个非对称搜索任务的示例。作为语料库,我们使用了较小的 简易英语维基百科,以便它能轻松加载到内存中。

retrieve_rerank_simple_wikipedia.ipynb [ Colab 版本 ]:此脚本使用 检索与重排序 策略,是非对称搜索任务的一个示例。我们将所有维基百科文章分成段落,并使用双编码器对其进行编码。当输入新的查询/问题时,它会由相同的双编码器进行编码,并检索余弦相似度最高的段落。接下来,检索到的候选者由交叉编码器重排序器评分,并将交叉编码器得分最高的 5 个段落呈现给用户。我们使用了在 MS Marco Passage Reranking 数据集(一个包含约 50 万个来自 Bing 搜索的真实查询的数据集)上训练的模型。

上一个 下一个

© 版权所有 2025。

使用 Sphinx 构建,主题由 Read the Docs 提供,基于 此主题。