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 參考文件:文件
使用檢索器
我們現在可以使用檢索器了!
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')]