Sub topic 1
Zero-Shot Text Classification with Transformers
Prerequisites
This chapter assumes that you:
- Write basic Python and can install packages with
pip. - Know the idea of supervised text classification, where a model learns from labeled examples.
- Understand that a pretrained language model is a model trained on large amounts of text before you use it.
You need the transformers package and PyTorch installed (pip install transformers torch).
Why zero-shot: the cost of labeled data
A supervised classifier needs labeled examples for every category. Labeling takes time and money, and the labels go stale when your categories change. Zero-shot classification avoids this cost. You name the categories when you run the model, and you supply no training examples.
Pretrained transformers as reusable language understanding
A pretrained transformer encoder has already learned how words relate to each other in context. You can reuse that understanding for a new task without training from scratch.
Natural language inference: premise, hypothesis, entailment
Natural language inference (NLI) is a task where a model reads a premise and a hypothesis. It decides whether the premise entails (supports), contradicts, or is neutral toward the hypothesis.
Turning classification into an entailment question
To classify text, each candidate label becomes a hypothesis. The text is the premise. For the label "billing", the hypothesis is "This example is billing." A high entailment score means the label fits the text.
Running the zero-shot pipeline
The Hugging Face pipeline function wraps this scoring for you:
from transformers import pipeline
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
text = "I was charged twice for my subscription this month."
labels = ["billing", "technical support", "sales"]
result = classifier(text, candidate_labels=labels)
print(result["labels"][0], result["scores"][0])The pipeline returns the labels sorted from highest to lowest score.
Exercise
Why does the pipeline create a separate hypothesis for each label?
Show answer
Each label gets its own entailment score, so the model judges the text against every candidate separately.