跳到主要内容
TF-IDF 表示词频乘以逆文档频率。
本笔记本介绍了如何使用底层通过 scikit-learn 包使用 TF-IDF 的检索器。 有关 TF-IDF 详细信息,请参阅这篇博客文章
pip install -qU  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={})]

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.