Skip to main content
Open In ColabOpen on GitHub

TF-IDF

TF-IDF means term-frequency times inverse document-frequency.

本笔记本介绍了如何使用一个底层采用TF-IDF的检索器,使用scikit-learn包实现。

有关TF-IDF的详细信息,请参阅这篇博客文章

%pip install --upgrade --quiet  scikit-learn
from langchain_community.retrievers import TFIDFRetriever
API 参考:TFIDFRetriever

使用文本创建新的检索器

retriever = TFIDFRetriever.from_texts(["foo", "bar", "world", "hello", "foo bar"])

使用文档创建一个新的检索器

你现在可以使用你创建的文档创建一个新的检索器。

from langchain_core.documents import Document

retriever = TFIDFRetriever.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(page_content='foo', metadata={}),
Document(page_content='foo bar', metadata={}),
Document(page_content='hello', metadata={}),
Document(page_content='world', metadata={})]

保存并加载

你可以轻松保存和加载这个检索器,这使得它在本地开发中非常方便!

retriever.save_local("testing.pkl")
retriever_copy = TFIDFRetriever.load_local("testing.pkl")
retriever_copy.invoke("foo")
[Document(page_content='foo', metadata={}),
Document(page_content='foo bar', metadata={}),
Document(page_content='hello', metadata={}),
Document(page_content='world', metadata={})]