reader-lm/classification.py
2024-10-24 13:07:11 +08:00

32 lines
739 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from pprint import pprint
from pydantic import BaseModel
from transformers import pipeline
classifier = pipeline("zero-shot-classification",
model="MoritzLaurer/mDeBERTa-v3-base-mnli-xnli")
# 返回一个结构化的内容
class ClassifyResult(BaseModel):
sequence: str
rank: list
scores: list
prediction: str
def classify(text: str, labels: list):
output = classifier(text, labels)
# pprint(output)
# 根据 score寻找最高的 label
prediction_rank = output['scores'].index(max(output['scores']))
return ClassifyResult(
sequence=text,
rank=output['labels'],
scores=output['scores'],
prediction=output['labels'][prediction_rank]
)