文档API 参考📓 教程🧑‍🍳 食谱🤝 集成💜 Discord🎨 Studio
API 参考

Classifiers (分类器)

根据提供的标签对文档进行分类。

模块 document_language_classifier

DocumentLanguageClassifier

对每个文档的语言进行分类并将其添加到其元数据中。

在初始化时提供语言列表。如果文档文本不匹配任何指定的语言,则元数据值将设置为“unmatched”。要根据文档的语言进行路由,请在 DocumentLanguageClassifier 之后使用 MetadataRouter 组件。要路由纯文本,请改用 TextLanguageRouter 组件。

使用示例

from haystack import Document, Pipeline
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack.components.classifiers import DocumentLanguageClassifier
from haystack.components.routers import MetadataRouter
from haystack.components.writers import DocumentWriter

docs = [Document(id="1", content="This is an English document"),
        Document(id="2", content="Este es un documento en español")]

document_store = InMemoryDocumentStore()

p = Pipeline()
p.add_component(instance=DocumentLanguageClassifier(languages=["en"]), name="language_classifier")
p.add_component(instance=MetadataRouter(rules={"en": {"language": {"$eq": "en"}}}), name="router")
p.add_component(instance=DocumentWriter(document_store=document_store), name="writer")
p.connect("language_classifier.documents", "router.documents")
p.connect("router.en", "writer.documents")

p.run({"language_classifier": {"documents": docs}})

written_docs = document_store.filter_documents()
assert len(written_docs) == 1
assert written_docs[0] == Document(id="1", content="This is an English document", meta={"language": "en"})

DocumentLanguageClassifier.__init__

def __init__(languages: Optional[list[str]] = None)

初始化 DocumentLanguageClassifier 组件。

参数:

  • languages: ISO 语言代码列表。请参阅 langdetect 文档中支持的语言。如果未指定,则默认为 ["en"]。

DocumentLanguageClassifier.run

@component.output_types(documents=list[Document])
def run(documents: list[Document])

对每个文档的语言进行分类并将其添加到其元数据中。

如果文档文本不匹配初始化时指定的任何语言,则将元数据值设置为“unmatched”。

参数:

  • documents: 用于语言分类的文档列表。

引发:

  • TypeError: 如果输入不是 Document 列表。

返回值:

一个字典,其中包含以下键

  • documents: 添加了language 元数据字段的文档列表。

模块 zero_shot_document_classifier

TransformersZeroShotDocumentClassifier

根据给定的标签执行文档的零样本分类,并将预测的标签添加到其元数据中。

该组件使用 Hugging Face 管道进行零样本分类。在初始化时提供模型和用于分类的标签集。此外,您可以配置该组件以允许多个标签为真。

默认情况下,分类在文档的内容字段上运行。如果要使其在另一个字段上运行,请将classification_field 设置为文档的元数据字段之一。

零样本分类任务的可用模型包括:-valhalla/distilbart-mnli-12-3 - cross-encoder/nli-distilroberta-base - cross-encoder/nli-deberta-v3-xsmall

使用示例

以下是一个管道,该管道根据从搜索管道检索到的预定义分类标签对文档进行分类

from haystack import Document
from haystack.components.retrievers.in_memory import InMemoryBM25Retriever
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack.core.pipeline import Pipeline
from haystack.components.classifiers import TransformersZeroShotDocumentClassifier

documents = [Document(id="0", content="Today was a nice day!"),
             Document(id="1", content="Yesterday was a bad day!")]

document_store = InMemoryDocumentStore()
retriever = InMemoryBM25Retriever(document_store=document_store)
document_classifier = TransformersZeroShotDocumentClassifier(
    model="cross-encoder/nli-deberta-v3-xsmall",
    labels=["positive", "negative"],
)

document_store.write_documents(documents)

pipeline = Pipeline()
pipeline.add_component(instance=retriever, name="retriever")
pipeline.add_component(instance=document_classifier, name="document_classifier")
pipeline.connect("retriever", "document_classifier")

queries = ["How was your day today?", "How was your day yesterday?"]
expected_predictions = ["positive", "negative"]

for idx, query in enumerate(queries):
    result = pipeline.run({"retriever": {"query": query, "top_k": 1}})
    assert result["document_classifier"]["documents"][0].to_dict()["id"] == str(idx)
    assert (result["document_classifier"]["documents"][0].to_dict()["classification"]["label"]
            == expected_predictions[idx])

TransformersZeroShotDocumentClassifier.__init__

def __init__(model: str,
             labels: list[str],
             multi_label: bool = False,
             classification_field: Optional[str] = None,
             device: Optional[ComponentDevice] = None,
             token: Optional[Secret] = Secret.from_env_var(
                 ["HF_API_TOKEN", "HF_TOKEN"], strict=False),
             huggingface_pipeline_kwargs: Optional[dict[str, Any]] = None)

初始化 TransformersZeroShotDocumentClassifier。

有关零样本分类模型(NLI)的完整列表,请参阅 Hugging Face 网站

参数:

  • model: 用于零样本文档分类的 Hugging Face 模型名称或路径。
  • labels: 可用于将每个文档分类的可能类标签集,例如 ["positive", "negative"]。标签取决于所选模型。
  • multi_label: 是否允许多个候选标签为真。如果False,则分数进行归一化,使得每个序列的标签似然度之和为 1。如果True,则将标签视为独立的,并通过对蕴涵分数与矛盾分数的 softmax 来为每个候选者进行概率归一化。
  • classification_field: 用于分类的文档元字段的名称。如果未设置,Document.content 将默认使用。
  • device: 加载模型的设备。如果None,则自动选择默认设备。如果在huggingface_pipeline_kwargs 中指定了设备/设备映射,它将覆盖此参数。
  • token: 用于作为 HTTP bearer 授权的 Hugging Face 令牌。请在您的 账户设置 中查看您的 HF 令牌。
  • huggingface_pipeline_kwargs: 包含用于初始化 Hugging Face 文本分类管道的关键字参数的字典。

TransformersZeroShotDocumentClassifier.warm_up

def warm_up()

Initializes the component.

TransformersZeroShotDocumentClassifier.to_dict

def to_dict() -> dict[str, Any]

将组件序列化为字典。

返回值:

包含序列化数据的字典。

TransformersZeroShotDocumentClassifier.from_dict

@classmethod
def from_dict(
        cls, data: dict[str, Any]) -> "TransformersZeroShotDocumentClassifier"

从字典反序列化组件。

参数:

  • data: 要反序列化的字典。

返回值:

反序列化后的组件。

TransformersZeroShotDocumentClassifier.run

@component.output_types(documents=list[Document])
def run(documents: list[Document], batch_size: int = 1)

根据提供的标签对文档进行分类,并将它们添加到其元数据中。

分类结果存储在每个文档元数据中的classification 字典中。如果multi_label 设置为True,则每个标签的分数可在classification 字典内的details 键下找到。

参数:

  • documents: 要处理的文档。
  • batch_size: 用于处理每个文档中内容的批处理大小。

返回值:

一个字典,其中包含以下键

  • documents: 添加了名为classification.