pythonbeginner

Zero-Shot Text Classification

Classify text into custom categories using zero-shot NLI models without training data.

python
from transformers import pipeline

classifier = pipeline('zero-shot-classification', model='facebook/bart-large-mnli')

texts = [
    'The stock market crashed 10% today.',
    'Scientists discover new species in Amazon.',
    'New iPhone model launches next month.',
]

labels = ['finance', 'science', 'technology', 'sports', 'politics']

for text in texts:
    result = classifier(text, candidate_labels=labels)
    top = result['labels'][0]
    score = result['scores'][0]
    print(f'{text[:50]!r}')
    print(f'  -> {top} ({score:.2%})\n')

Use Cases

  • content categorization
  • intent detection
  • topic classification

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.