BM25
BM25 (Wikipedia),又称
Okapi BM25,是一种信息检索系统中用于评估文档与给定搜索查询相关性的排序函数。
BM25Retriever检索器使用rank_bm25包。
%pip install --upgrade --quiet  rank_bm25
from langchain_community.retrievers import BM25Retriever
API 参考:BM25Retriever
使用文本创建新的检索器
retriever = BM25Retriever.from_texts(["foo", "bar", "world", "hello", "foo bar"])
使用文档创建新的检索器
您现在可以使用您创建的文档来创建新的检索器。
from langchain_core.documents import Document
retriever = BM25Retriever.from_documents(
    [
        Document(page_content="foo"),
        Document(page_content="bar"),
        Document(page_content="world"),
        Document(page_content="hello"),
        Document(page_content="foo bar"),
    ]
)
API 参考:Document
使用检索器
我们现在可以使用检索器了!
result = retriever.invoke("foo")
result
[Document(metadata={}, page_content='foo'),
 Document(metadata={}, page_content='foo bar'),
 Document(metadata={}, page_content='hello'),
 Document(metadata={}, page_content='world')]
预处理函数
将自定义预处理函数传递给检索器以改进搜索结果。在单词级别对文本进行分词可以增强检索效果,尤其是在使用 Chroma、Pinecone 或 Faiss 等向量存储处理分块文档时。
import nltk
nltk.download("punkt_tab")
from nltk.tokenize import word_tokenize
retriever = BM25Retriever.from_documents(
    [
        Document(page_content="foo"),
        Document(page_content="bar"),
        Document(page_content="world"),
        Document(page_content="hello"),
        Document(page_content="foo bar"),
    ],
    k=2,
    preprocess_func=word_tokenize,
)
result = retriever.invoke("bar")
result
[Document(metadata={}, page_content='bar'),
 Document(metadata={}, page_content='foo bar')]