Sub topic 5
Running the zero-shot pipeline
This chapter assumes basic Python, familiarity with supervised text classification, and a general idea of pretrained language models. You should also have transformers and PyTorch installed:
pip install transformers torchA zero-shot classifier receives text and a list of candidate labels at prediction time. The model does not need a training example for each label in that list. Instead, it compares the text with a natural-language statement about each label.
A first prediction
Hugging Face provides this behavior through the zero-shot-classification pipeline. The pipeline downloads a suitable natural language inference model the first time you run it.
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"])
print(result["scores"])
print("best label:", result["labels"][0])The result is a dictionary with three important fields:
sequenceis the original input text.labelscontains the candidate labels, sorted from highest score to lowest score.scorescontains the corresponding confidence-like scores.
For this example, billing should usually be the first label. The scores are model probabilities for the comparison performed by the pipeline. They are useful for ranking, but they are not a guarantee that the prediction is correct.
The first execution may take time because the tokenizer and model weights are downloaded and cached locally. Later executions can reuse the cached files.
What the pipeline does
The pipeline turns each candidate label into a hypothesis, such as “This text is about billing.” It then asks the NLI model whether the input text supports that hypothesis.
You can change the wording of the hypothesis with hypothesis_template. The placeholder {} is replaced by each candidate label.
from transformers import pipeline
classifier = pipeline(
"zero-shot-classification",
model="facebook/bart-large-mnli",
)
text = "The app crashes when I try to update my payment method."
labels = ["billing", "technical support", "sales"]
result = classifier(
text,
candidate_labels=labels,
hypothesis_template="This customer message is about {}.",
)
for label, score in zip(result["labels"], result["scores"]):
print(f"{label}: {score:.3f}")A template should form a natural, meaningful sentence for every label. Poor grammar or an overly specific template can change the scores even when the input text stays the same.
Single-label and multi-label predictions
By default, the pipeline treats the labels as competing alternatives. Their scores are normalized together, so the labels are intended to describe one primary category.
Use multi_label=True when one text can belong to several categories. The pipeline then scores each label independently. Several labels can receive high scores, and the scores do not need to add up to one.
result = classifier(
text,
candidate_labels=labels,
hypothesis_template="This customer message is about {}.",
multi_label=True,
)
for label, score in zip(result["labels"], result["scores"]):
print(f"{label}: {score:.3f}")Choose the mode based on the data model. Use the default for one routing category. Use multi-label mode for properties such as “billing,” “urgent,” and “account access,” which can all apply to the same message.
Exercise
Which argument should you add when a message may receive more than one independent label?
Show answer
Add multi_label=True to the pipeline call.