TransformersZeroShotDocumentClassifier
TransformersZeroShotDocumentClassifier
제공된 라벨을 기준으로 문서를 분류하고 분류 결과를 메타데이터에 추가해 주는 컴포넌트예요. 라벨을 하나도 안 보고도, 주어진 라벨 집합 중 문서가 어느 쪽에 가까운지 판별해 줘요.
파이프라인에서 가장 흔한 위치: MetadataRouter 앞
필수 init 변수: model — zero-shot 문서 분류용 Hugging Face 모델의 이름 또는 경로 [positive, negative] 같은 분류 라벨 집합 labels — 각 문서를 분류할 가능한 클래스 라벨 집합. 라벨은 선택한 모델에 따라 달라져요.
필수 run 변수: documents — 분류할 문서 리스트
출력 변수: documents — classification 메타데이터 필드가 추가된 처리된 문서 리스트
API 레퍼런스: Transformers
GitHub 링크: https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/transformers
패키지 이름: transformers-haystack
출처: 문서
본문
개요 (Overview)
TransformersZeroShotDocumentClassifier 컴포넌트는 사용자가 설정한 라벨을 기준으로 문서를 zero-shot 분류하고, 예측된 라벨을 문서의 메타데이터에 추가해요. "zero-shot"이라는 말처럼, 미리 분류를 학습하지 않은 라벨 집합도 바로 적용할 수 있다는 뜻이에요.
이 컴포넌트는 zero-shot 분류용 Hugging Face 파이프라인을 사용해요.
컴포넌트를 초기화하려면 모델과 분류에 쓸 라벨 집합을 제공하면 돼요.
multi_label 불리언 값을 True로 설정하면 여러 라벨이 동시에 맞는 것으로 처리하도록 추가로 구성할 수 있어요.
분류는 기본적으로 문서의 content 필드에서 실행돼요. 다른 필드에서 실행하고 싶다면 classification_field를 문서의 메타데이터 필드 중 하나로 설정하면 돼요.
분류 결과는 각 문서의 메타데이터 안 classification 딕셔너리에 저장돼요. multi_label을 True로 설정했다면, classification 딕셔너리 안 details 키 아래에서 각 라벨의 점수를 확인할 수 있어요.
zero-shot 분류 작업에 사용할 수 있는 모델들은 다음과 같아요:
valhalla/distilbart-mnli-12-3
cross-encoder/nli-distilroberta-base
cross-encoder/nli-deberta-v3-xsmall
사용법 (Usage)
TransformersZeroShotDocumentClassifier를 사용하려면 transformers-haystack 패키지를 설치해요:
pip install transformers-haystack
단독으로 사용하기 (On its own)
from haystack import Document
from haystack_integrations.components.classifiers.transformers import (
TransformersZeroShotDocumentClassifier,
)
documents = [
Document(id="0", content="Cats don't get teeth cavities."),
Document(id="1", content="Cucumbers can be grown in water."),
]
document_classifier = TransformersZeroShotDocumentClassifier(
model="cross-encoder/nli-deberta-v3-xsmall",
labels=["animals", "food"],
)
document_classifier.run(documents=documents)
파이프라인 안에서 사용하기 (In a pipeline)
아래는 검색 파이프라인에서 가져온 문서들을 사전 정의된 분류 라벨을 기준으로 분류하는 파이프라인이에요:
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_integrations.components.classifiers.transformers 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(name="retriever", instance=retriever)
pipeline.add_component(name="document_classifier", instance=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}})
classified_docs = result["document_classifier"]["documents"]
assert classified_docs[0].id == str(idx)
assert (
classified_docs[0].meta["classification"]["label"] == expected_predictions[idx]
)