Sub topic 1
Why zero-shot: the cost of labeled data
Zero-shot text classification assigns text to categories the model was never trained on. This chapter explains the problem it solves, which is the cost of labeled data. It also sets up the questions the rest of the tutorial answers: how the method works, how well it works, and when to use something else.
Prerequisites
This chapter assumes you can do the following:
- Read and write basic Python, including functions and f-strings.
- Explain supervised text classification in a sentence. You train a model on texts paired with labels, then use it to label new texts.
- Describe a pretrained language model as a network trained on large amounts of text and then reused for other tasks.
- Install and import Python packages. The one runnable model example needs
transformersandtorch, and the first run downloads about 1.6 GB of model weights.
You do not need to know how natural language inference (NLI) works. The next chapters cover it.
The supervised baseline and what it needs
In a standard supervised setup, you pick a fixed set of classes, collect examples of each, and train or fine-tune a model to map text to those classes. A support team might want incoming messages routed to billing, technical support, or sales. The pipeline looks like this:
- Define the label set and write labeling guidelines.
- Collect unlabeled messages.
- Have people assign a label to each message.
- Train a model on the labeled messages.
- Evaluate on held-out labeled messages.
- Deploy, and repeat when the requirements change.
Step 3 dominates the cost. The model code is a few lines with a modern library. The labeled dataset is the expensive and slow part.
Where the labeling cost comes from
Labeling costs more than the per-item time suggests, for several reasons.
- Volume per class. Fine-tuning a transformer classifier typically needs tens to hundreds of examples per class to be reliable. Hard or subtle classes need more.
- Multiple annotators. Labels are noisy. Teams often have two or three people label the same item and resolve disagreements, so each item costs several times its single-label price.
- Guidelines and calibration. Someone has to write the labeling rules, pilot them, find the ambiguous cases, and revise. This is skilled work.
- Class imbalance. Rare classes are the ones you most want to catch and the ones with the fewest examples. Collecting enough of them can mean labeling thousands of common items.
- Domain expertise. Medical, legal, or financial text often needs expert annotators, who cost more per hour and are harder to schedule.
- Privacy. Customer messages may contain personal data. Sending them to an outside annotation vendor can require legal review.
The next script is a rough cost model for the supervised approach. It is pure Python and runs as shown.
def labeling_cost(n_classes, examples_per_class, seconds_per_example,
annotators_per_item, hourly_rate):
"""Return (hours, dollars) to build a labeled training set."""
total_labels = n_classes * examples_per_class * annotators_per_item
hours = total_labels * seconds_per_example / 3600
return hours, hours * hourly_rate
# Initial dataset: 12 classes, 500 examples each, 20 s per label,
# 2 annotators per item, $25/hour.
hours, dollars = labeling_cost(12, 500, 20, 2, 25)
print(f"Initial dataset: {hours:.1f} h, ${dollars:,.2f}")
# The taxonomy gains a 13th class. Collect 500 examples of it.
hours_new, dollars_new = labeling_cost(1, 500, 20, 2, 25)
# Existing items may belong to the new class, so a reviewer re-checks
# all 6,000 existing items at 5 s each, with one reviewer.
hours_review, dollars_review = labeling_cost(12, 500, 5, 1, 25)
print(f"New class examples: {hours_new:.1f} h, ${dollars_new:,.2f}")
print(f"Re-review of old data: {hours_review:.1f} h, ${dollars_review:,.2f}")The initial dataset comes to roughly 67 hours and about $1,670. Adding one class costs roughly another 14 hours, split between new examples and re-review. These numbers rest on assumptions, and your real figures will differ. What carries over is the structure of the cost. It grows with the number of classes, and it grows again every time the label set changes.
Costs beyond money
Dollars are only part of the cost.
- Time to first result. A labeling project can take weeks. A product team that wants to try an idea this afternoon cannot wait for it.
- The cold-start problem. At the start of a project you often have no data. You cannot know which classes matter until you have seen real traffic, and you cannot label traffic that has not arrived.
- Label-set rigidity. A supervised classifier has an output layer sized for its training classes. A new class means new labeled data and retraining. A class you want to merge or split can mean relabeling.
- Drift. Products change, new topics appear, and the vocabulary shifts. A model trained on last year's labels can degrade, and refreshing it means labeling again.
What zero-shot changes
A zero-shot classifier takes the label names at inference time. You give it a text and a list of candidate labels, and it returns a score for each one. No training examples for your task are involved. In this tutorial you will use an NLI model for this. The model was trained on a general task of judging whether one sentence follows from another. That ability transfers to your labels without further training.
Here is the idea in running code. This is the first example from the tutorial's plan, and later chapters explain what happens inside 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"][0], result["scores"][0])The model has never seen your three categories as training targets. The label list is an argument to the function call, so you can change it without retraining. Changing it costs one edit to a Python list.
Compare this with the cost model above. The new-class scenario that cost about 14 hours of annotation becomes adding a string to labels. The cold-start problem shrinks because you can start classifying real traffic immediately and use the output to see which classes matter.
Zero-shot is not label-free
Two common misreadings are worth correcting early.
First, zero-shot removes the need for training data. It does not remove the need for evaluation data. Without a labeled sample you cannot know whether the classifier is right 95% of the time or 55% of the time, and a confident-looking score does not tell you. Even 100 to 200 carefully labeled examples are enough to compare approaches and catch serious problems. That is a much smaller labeling job than building a training set. Chapter 9 of this tutorial covers measuring accuracy and macro F1 on such a sample.
Second, zero-shot does not mean free. You move the cost from annotation to other places:
- Inference cost. An NLI model reads the text once per candidate label. With 12 labels, that is 12 model passes per message. Chapter 11 of this tutorial covers this limit.
- Accuracy. A fine-tuned model that has seen thousands of in-domain examples usually beats a zero-shot model on the same task. The gap is larger for niche domains and subtle distinctions.
- Prompt engineering. Label wording and templates affect the scores. You spend effort on them instead of on annotation.
The trade is worth making when labels are scarce, when the label set changes often, or when you need a working prototype fast. It is a poor trade when you have abundant clean labels, strict latency limits, and a stable label set.
Related settings: few-shot and weak supervision
Zero-shot sits on a spectrum of label efficiency.
| Setting | Task-specific labeled examples | Typical use |
|---|---|---|
| Supervised fine-tuning | Hundreds to thousands per class | Stable task, high accuracy needed |
| Few-shot | A handful per class | Small labeling budget, some adaptation |
| Zero-shot | None for training, a small sample for evaluation | Prototypes, changing label sets, cold start |
A common path is to start zero-shot, use its predictions to speed up labeling by having humans correct predictions instead of labeling from scratch, and later fine-tune a smaller, faster model on the corrected data. The zero-shot classifier then serves as a bootstrap for supervised training.
What the rest of the tutorial covers
This tutorial builds the method in layers. It begins with how a pretrained encoder and the NLI task make zero-shot possible. It then runs the Hugging Face pipeline, tunes hypothesis templates and label wording, and scores single-label and multi-label cases. After that it evaluates with accuracy and macro F1, adds thresholds so the classifier can abstain, and covers limits such as cost per label, ambiguity, domain shift, and bias. It closes with embedding similarity and LLM prompting as alternatives, and with criteria for choosing among all the approaches and for when to fine-tune instead.
Exercise
A team supports 8 product categories, and a new category appears roughly every month. They have no labeled data and want a working router within a week. Give two reasons zero-shot is a good starting point. Then name one thing they still need to label, and say why.
Show answer
Reasons: (1) The label list is a runtime argument, so adding a monthly category means editing a list and not collecting data and retraining. (2) With no labeled data they cannot train a supervised model within a week, and zero-shot gives usable predictions immediately. They still need a small labeled evaluation sample, perhaps 100 to 200 messages, because without it they cannot measure accuracy or macro F1, and they cannot tell whether the classifier is good enough to deploy or which categories it confuses.
Exercise
Using the labeling_cost function, a project has 20 classes, wants 300 examples per class, uses 15 seconds per label, 3 annotators per item, and pays $30/hour. How many hours does labeling take, and what does it cost?
Show answer
Total labels = 20 300 3 = 18,000. Seconds = 18,000 15 = 270,000. Hours = 270,000 / 3600 = 75 hours. Cost = 75 30 = $2,250.