Skip to main content

TF-IDF

TF-IDF 是词频与逆文档频率的乘积。

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

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

%pip install --upgrade --quiet  scikit-learn
from langchain_community.retrievers import 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"),
]
)

使用检索器

我们现在可以使用检索器了!

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={})]

相关


此页面是否有帮助?


您还可以留下详细的反馈 在 GitHub 上