Skip to main content

How to Classify Text into Your Own Labels with Zero-Shot Classification

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

Zero-shot classification sorts text into labels you choose when you call it, such as "sports", "politics" and "technology", without training a model on them first. It works by asking a model trained for natural language inference whether each label fits the text. This guide classifies headlines with Hugging Face Transformers 5.24.1 and facebook/bart-large-mnli, and shows how the two main options change the scores.

Syntax​

Syntax
from transformers import pipeline

classifier = pipeline("zero-shot-classification", model="<model>", revision="<commit>")
result = classifier(
"<text>",
candidate_labels=["<label>", "<label>"],
multi_label=<True or False>,
hypothesis_template="<sentence with {}>",
)
PartWhat it means
candidate_labelsThe labels to choose from. Any words you like
multi_labelFalse (default): the scores share 1.0 between the labels. True: each label is scored on its own
hypothesis_templateThe sentence each label is put into before the model judges it. Default: "This example is {}."
result["labels"], result["scores"]The labels sorted from best to worst, and their scores in the same order

The pipeline's own documentation explains the template: "The template used to turn each label into an NLI-style hypothesis", and multi_label: "If False, the scores are normalized such that the sum of the label likelihoods for each sequence is 1. If True, the labels are considered independent".

The Example​

Two headlines and three topics. The model is facebook/bart-large-mnli (MIT licence), the one Transformers uses for this task by default. It's 1.6 GB, so the first run takes a minute or two to download it.

Prerequisites​

  • uv. This guide uses uv 0.13.10. The project uses Python 3.14, which uv downloads if needed.
  • About 1.7 GB of disk space for the model.

Step 1: Create the Project​

Terminal
uv init --python 3.14 zero-shot-demo
cd zero-shot-demo
uv add transformers torch

Step 2: Classify a Headline​

headline.py
from transformers import pipeline

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

result = classifier(
"The new phone has a faster chip and a battery that lasts two days.",
candidate_labels=["sports", "politics", "technology"],
)
for label, score in zip(result["labels"], result["scores"]):
print(f"{label:<11}{score:.4f}")

The headline.py script in a macOS-style code window: a zero-shot-classification pipeline with facebook/bart-large-mnli pinned to a commit, a headline about a phone with a faster chip, the labels sports, politics and technology, and a loop that prints each label with its score.

Terminal
uv run python headline.py
Output
W1201 05:03:36.472000 51673 .venv/lib/python3.14/site-packages/torch/distributed/elastic/multiprocessing/redirects.py:35] NOTE: Redirects are currently not supported in MacOs.
Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.
config.json: 100%|█████████████████████████████████████████████| 1.15k/1.15k [00:00<00:00, 2.06MB/s]
model.safetensors: downloading bytes: ██████████████████████████████████████████| 1.09GB, 6.82MB/s
model.safetensors: reconstructing file: 100%|██████████████████████████| 1.63GB / 1.63GB, 35.2MB/s
Loading weights: 100%|██████████████████████████████████████████| 515/515 [00:00<00:00, 5978.91it/s]
tokenizer_config.json: 100%|█████████████████████████████████████| 26.0/26.0 [00:00<00:00, 6.81kB/s]
vocab.json: 100%|████████████████████████████████████████████████| 899k/899k [00:00<00:00, 4.58MB/s]
merges.txt: 100%|████████████████████████████████████████████████| 456k/456k [00:00<00:00, 12.1MB/s]
tokenizer.json: 100%|██████████████████████████████████████████| 1.36M/1.36M [00:00<00:00, 13.3MB/s]
technology 0.9877
sports 0.0082
politics 0.0040

The terminal after uv run python headline.py: the model files downloading, then technology 0.9877, sports 0.0082 and politics 0.0040.

technology won with 0.9877, and the three scores add up to 1. The model was never trained on these three labels: for each one it judged whether "This example is technology." follows from the headline. The notices at the top are harmless: the macOS note comes from PyTorch, and the warning means the download ran without a Hugging Face account.

Step 3: Let Several Labels Be True​

Some texts fit more than one label. This headline is about both politics and technology. The script scores it both ways:

headline_multi.py
from transformers import pipeline

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

headline = "The government will spend 2 billion dollars on new computer chips."
labels = ["sports", "politics", "technology"]

for multi_label in (False, True):
result = classifier(headline, candidate_labels=labels, multi_label=multi_label)
print(f"multi_label={multi_label}")
for label, score in zip(result["labels"], result["scores"]):
print(f" {label:<11}{score:.4f}")
Terminal
uv run python headline_multi.py
Output
W1201 05:05:44.158000 54098 .venv/lib/python3.14/site-packages/torch/distributed/elastic/multiprocessing/redirects.py:35] NOTE: Redirects are currently not supported in MacOs.
Loading weights: 100%|██████████████████████████████████████████| 515/515 [00:00<00:00, 7661.06it/s]
multi_label=False
technology 0.9853
politics 0.0088
sports 0.0059
multi_label=True
technology 0.9868
politics 0.0017
sports 0.0001

The terminal after uv run python headline_multi.py: with multi_label=False, technology 0.9853, politics 0.0088 and sports 0.0059; with multi_label=True, technology 0.9868, politics 0.0017 and sports 0.0001.

With multi_label=True, each label was judged on its own, so the scores no longer add up to 1. But the result may surprise you: politics stayed very low. The model read this headline as technology and nothing else.

Step 4: Change the Hypothesis Template​

The default sentence, "This example is politics.", is an odd thing to say about a headline. The documentation says the default "works well in many cases, but it may be worthwhile to experiment with different templates depending on the task setting." Here's the same headline with a more natural one:

headline_template.py
from transformers import pipeline

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

result = classifier(
"The government will spend 2 billion dollars on new computer chips.",
candidate_labels=["sports", "politics", "technology"],
multi_label=True,
hypothesis_template="This text is about {}.",
)
for label, score in zip(result["labels"], result["scores"]):
print(f"{label:<11}{score:.4f}")
Terminal
uv run python headline_template.py
Output
W1201 05:05:51.007000 54220 .venv/lib/python3.14/site-packages/torch/distributed/elastic/multiprocessing/redirects.py:35] NOTE: Redirects are currently not supported in MacOs.
Loading weights: 100%|██████████████████████████████████████████| 515/515 [00:00<00:00, 7008.52it/s]
technology 0.9773
politics 0.0273
sports 0.0007

The terminal after uv run python headline_template.py: technology 0.9773, politics 0.0273 and sports 0.0007.

The new template raised politics from 0.0017 to 0.0273, sixteen times higher, but still far below technology. The wording of the template and the labels changes the scores, but it can't make a model see what it doesn't. When zero-shot keeps missing a label that matters to you, that's the sign to fine-tune a model on examples of it. The commands in this guide work unchanged in PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
A template without {}The pipeline has nowhere to put the labelKeep {} where the label goes
Reading a high score as proofScores are the model's confidence, not accuracy: a label can win with 0.98 and still be wrong for your useCheck results on examples you know the answer to
Dozens of labels with a large modelEvery label is a separate pass through the model, so the time grows with the number of labelsUse fewer labels, or a smaller model

FAQ​

Why does every label cost a model run?​

Because each one becomes its own question for the model: "does this text mean that this example is sports?", then the same for politics, and so on. The pipeline runs one check per label and compares the answers.

Which models can do zero-shot classification?​

Models trained for natural language inference (NLI), such as facebook/bart-large-mnli. On the Hub, filter by the Zero-Shot Classification task, and check each model's licence and training data.

Conclusion​

The zero-shot pipeline put the phone headline under technology (0.9877) without any training. multi_label=True scored each label on its own, and a better hypothesis_template raised politics sixteen-fold, but still not enough. Zero-shot is a quick start; it doesn't replace training on your own labels.

Additional Resources​