欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 八卦 > LLM之RAG实战(五十二)| 如何使用混合搜索优化RAG 检索

LLM之RAG实战(五十二)| 如何使用混合搜索优化RAG 检索

2025/3/26 6:03:30 来源:https://blog.csdn.net/wshzd/article/details/146451107  浏览:    关键词:LLM之RAG实战(五十二)| 如何使用混合搜索优化RAG 检索

       在RAG项目中,大模型生成的参考内容(专业术语称为块)来自前一步的检索,检索的内容在很大程度上直接决定了生成的效果,因此检索对于RAG项目至关重要,最常用的检索方法是关键字搜索和语义搜索。本文将分别介绍这两种搜索策略,然后将它们结合起来进行混合检索。

一、使用 BM25 进行关键字搜索

       BM25 是关键字搜索的首选算法。使用 BM25,我们可以为语料库中每个文档的查询获得分数。

       BM25 基于 TF-IDF 算法,这意味着公式的核心是术语频率 (TF) 和逆向文档频率 (IDF) 的乘积。

      TF-IDF 算法基于以下理念:“对频率较低、更具体的术语的匹配比对频繁术语的匹配更有价值”

      换句话说,TF-IDF 算法会查找包含查询中罕见关键字的文档。

图片

       如果我们看一下 LangChain 源码(https://api.python.langchain.com/en/latest/_modules/langchain_community/retrievers/bm25.html#BM25Retriever),可以看到它使用了 rank_bm25 包中的 BM25Okapi 类,该类是 ATIRE BM25 算法的略微修改版本。

     在 ATIRE BM25 版本中,获得文档 d 和由多个词 t 组成的给定查询 q的分数的公式如下

图片

  • N 是语料库中的文档数

  • df_t 是包含术语 t 的文档数 (也称为文档频率)

  • tf_td 是术语 t 在文档 d 中出现的次数(也称为术语频率)

  • L_d是我们文档的长度,L_avg是平均文档长度

  • 有两个经验调优参数: b 和 k_1

我们看到公式对所有项 t 求和,我们可以将其视为单词。

      BM25 方程中的左手因子 log(N/df_t) 称为逆文档频率。对于像 “the” 这样的常用词,我们所有的文档都可能包含,所以逆向文档频率将为零(因为 log(1) 为零)。

     另一方面,非常罕见的单词只会出现在少数文档中,从而增加左因子。因此,逆向文档频率是衡量术语 t 中包含多少信息的量度。

      右因子受术语 t 在文档 d 中出现的次数的影响。

    该文档 d=["I like red cats, black cats, white cats, and brown cats"] 对词 t=“cats” 具有非常高的词频tf_td,这将导致包含单词 “cats” 的查询获得较高的 BM25 分数。

      让我们使用 BM25 来使用 Python 库rank_bm25来获得一些直觉。

pip install rank_bm25

      首先,我们加载库并使用我们的标记化语料库初始化 BM25。

from rank_bm25 import BM25Okapicorpus = [    "The cat, commonly referred to as the domestic cat or house cat, is a small domesticated carnivorous mammal.",        "The dog is a domesticated descendant of the wolf.",        "Humans are the most common and widespread species of primate, and the last surviving species of the genus Homo.",        "The scientific name Felis catus was proposed by Carl Linnaeus in 1758"]tokenized_corpus = [doc.split(" ") for doc in corpus]
bm25 = BM25Okapi(tokenized_corpus)

      接下来,我们对查询进行标记化。​​​​​​​

query = "The cat"tokenized_query = query.split(" ")

     最后,我们使用 BM25 算法计算分数。高分表示文档和查询之间的匹配良好。​​​​​​​

doc_scores = bm25.get_scores(tokenized_query)
print(doc_scores)
>> [0.92932018 0.21121974 0. 0.1901173]# scores for documents 1, 2, 3, and 4

       由于 BM25 查找完全匹配的术语,因此查询术语“cats”、“Cat”或“feline”都将导致三个示例文档的分数为 doc_scores = [0,0,0]。

二、使用密集嵌入的语义搜索

       当我们通过密集嵌入执行语义搜索时,我们会将单词转换为数字表示。其理念是,在这种新的数学表示形式中,相似的单词紧密相连。

图片

       文本嵌入是单个单词或整个句子的高维向量。它们称为 dense,因为向量中的每个条目都是一个有意义的数字。相反,当许多 vector 条目只是为零时,称为 sparse。

       在将单词转换为嵌入之前,首先通过称为编码器的神经网络嵌入模型将token转换为嵌入向量。

图片

       在将文档语料库中的所有文本转换为嵌入后,可以执行语义搜索以查看哪个嵌入文档最接近我们的嵌入查询。

       我们可以通过绘制嵌入维度并找到与我们的查询最匹配的文档来可视化此任务。

图片

       在数学上,我们使用余弦距离函数找到最接近的匹配项。对于两个嵌入向量 a 和 b,我们可以使用点积计算余弦相似度,如下所示:

图片

       其中分子是两个嵌入向量的点积,分母是它们量级的乘积。

       在几何学上,余弦相似度是向量之间的角度。余弦相似性分数范围为 -1 到 +1。

       余弦相似度分数 -1 表示嵌入 a 和 b 正好朝向相反的方向,0 表示它们的角度为 90 度(它们无关),+1 表示它们相同。 因此,在将搜索查询与文档匹配时,我们会寻找接近 +1 的值。

        如果我们事先对嵌入进行归一化,则余弦相似度测度将等效于点积相似度测度(分母变为 1)。

        下面让我们使用 Python 包 sentence-transformers 来计算一下基本的语义搜索。

pip install sentence-transformers

     首先,从 HuggingFace 下载全 MiniLM-L6-v2 编码器模型,可生成 384 维密集嵌入。​​​​​​​

from sentence_transformers import SentenceTransformer
# 1. Load a pretrained Sentence Transformer modelmodel = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')

      然后,我们使用与以前相同的文档语料库。​​​​​​​

# The documents to encodecorpus = [    "The cat, commonly referred to as the domestic cat or house cat, is a small domesticated carnivorous mammal.",        "The dog is a domesticated descendant of the wolf.",        "Humans are the most common and widespread species of primate, and the last surviving species of the genus Homo.",        "The scientific name Felis catus was proposed by Carl Linnaeus in 1758"]    # Calculate embeddings by calling model.encode()document_embeddings = model.encode(corpus)    # Sanity checkprint(document_embeddings.shape)>> (4, 384)

       对查询进行嵌入:​​​​​​​

query = "The cat"query_embedding = model.encode(query)

      最后,计算余弦相似度分数。可以使用 sentence_transformers 中的 utility 函数 cos_sim,而不是自己编写公式。​​​​​​​

from sentence_transformers.util import cos_sim# Compute cosine_similarity between documents and queryscores = cos_sim(document_embeddings, query_embedding)

print(scores)>> tensor([[0.5716],  # score for document 1>>         [0.2904],  # score for document 2>>         [0.0942],  # score for document 3>>         [0.3157]]) # score for document 4

       为了了解使用密集嵌入的语义搜索的强大功能,我可以使用查询 “feline” 重新运行代码:​​​​​​​

query_embedding = model.encode("feline")
scores = cos_sim(document_embeddings, query_embedding)
print(scores)>> tensor([[0.4007],>>         [0.3837],>>         [0.0966],>>         [0.3804]])

       即使 “feline” 一词没有出现在文档语料库中,语义搜索仍然将有关猫的文本列为最高匹配度。

三、语义搜索还是关键字搜索?

       哪种搜索方法更好?这要看情况。两者都有优点和缺点。现在我们知道了两者的工作原理,我们可以看到它们在哪些方面有用,哪些方面可能失败。

       使用 BM25 进行关键字搜索会查找查询词的完全匹配项。当我们在寻找短语的精确匹配时,这可能非常有用。

       如果我在找《帽子里的猫》(The Cat in the Hat),我可能在找这本书/电影。而且我不希望出现语义上相似的结果,这些结果接近 hats 或 cats。

       关键字搜索的另一个用例是编程。如果我正在寻找特定的函数或代码段,我想要一个完全匹配。

       另一方面,语义搜索会查找语义相似的内容。这意味着语义搜索还会查找具有同义词或不同拼写(如复数、大写等)的文档。

       由于这两种算法都有其用例,因此混合搜索同时使用这两种算法,然后将它们的结果合并为一个最终排名。

       混合搜索的缺点是它比只运行一种算法需要更多的计算资源。

四、混合搜索

       我们可以使用倒数秩融合 (RRF) 将 BM25 和余弦相似性的结果结合起来。RRF 是一种简单的算法,用于组合不同评分函数的排名 [4]。

       首先,我们需要获取每种评分算法的文档排名。在我们的示例中,这将是:​​​​​​​

corpus = [    "The cat, commonly referred to as the domestic cat or house cat, is a small domesticated carnivorous mammal.",        "The dog is a domesticated descendant of the wolf.",        "Humans are the most common and widespread species of primate, and the last surviving species of the genus Homo.",        "The scientific name Felis catus was proposed by Carl Linnaeus in 1758",]    query = "The cat"bm25_ranking = [1, 2, 4, 3] # scores = [0.92932018 0.21121974 0. 0.1901173]cosine_ranking = [1, 3, 4, 2] # scores = [0.5716, 0.2904, 0.0942, 0.3157]

       每个文档 d 的综合 RRF 分数公式如下:

图片

       其中 k 是一个参数(原始论文使用 k=60),r(d) 是 BM25 和余弦相似度的排名。

       现在,我们可以通过分别进行 BM25 和余弦相似性,然后将结果与 RRF 相结合来实现我们的混合搜索。

       首先,让我们定义 RRF 的函数和将浮点分数转换为 int 排名的辅助函数。​​​​​​​

import numpy as np
def scores_to_ranking(scores: list[float]) -> list[int]:    """Convert float scores into int rankings (rank 1 is the best)"""        return np.argsort(scores)[::-1] + 1    def rrf(keyword_rank: int, semantic_rank: int) -> float:    """Combine keyword rank and semantic rank into a hybrid score."""        k = 60        rrf_score = 1 / (k + keyword_rank) + 1 / (k + semantic_rank)        return rrf_score

        这是我使用上述概念的简单混合搜索实现。​​​​​​​

from rank_bm25 import BM25Okapifrom sentence_transformers import SentenceTransformerfrom sentence_transformers.util import cos_sim
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")def hybrid_search(    query: str, corpus: list[str], encoder_model: SentenceTransformer    ) -> list[int]:    # bm25        tokenized_corpus = [doc.split(" ") for doc in corpus]        tokenized_query = query.split(" ")        bm25 = BM25Okapi(tokenized_corpus)        bm25_scores = bm25.get_scores(tokenized_query)        bm25_ranking = scores_to_ranking(bm25_scores)            # embeddings        document_embeddings = model.encode(corpus)        query_embedding = model.encode(query)        cos_sim_scores = cos_sim(document_embeddings, query_embedding).flatten().tolist()        cos_sim_ranking = scores_to_ranking(cos_sim_scores)            # combine rankings into RRF scores        hybrid_scores = []        for i, doc in enumerate(corpus):                document_ranking = rrf(bm25_ranking[i], cos_sim_ranking[i])                print(f"Document {i} has the rrf score {document_ranking}")                hybrid_scores.append(document_ranking)                # convert RRF scores into final rankings        hybrid_ranking = scores_to_ranking(hybrid_scores)        return hybrid_ranking

现在我们可以将 hybrid_search 用于不同的查询。​​​​​​​

hybrid_ranking = hybrid_search(    query="What is the scientifc name for cats?", corpus=corpus, encoder_model=model    )print(hybrid_ranking)>> Document 0 has the rrf score 0.03125>> Document 1 has the rrf score 0.032266458495966696>> Document 2 has the rrf score 0.03225806451612903>> Document 3 has the rrf score 0.032266458495966696>> [4 2 3 1]

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词