Sub topic 9
Measuring accuracy and macro F1 on a labeled sample
A zero-shot classifier needs no training data, but you still need labeled data to know whether it works. This chapter shows how to build a small labeled sample, score the classifier on it, and read accuracy and macro F1 correctly. It assumes you can run the zero-shot-classification pipeline and know what a label, a prediction and a confusion matrix are.
Why you must still evaluate
Zero-shot scores look confident even when they are wrong. A score of 0.92 for "billing" is a softmax output from an NLI model. It is not a calibrated probability that the label is correct. The only way to learn how often the classifier is right on your texts is to compare its predictions with human labels.
The labeled sample can be small. A few hundred examples is usually enough to compare two label sets or two templates. It is not enough to claim precise performance numbers. Evaluation here answers two questions:
- Is the classifier good enough for this task?
- Which configuration (labels, template, model) is better?
Building the labeled sample
Build the sample from real traffic, not from sentences you invent. Invented sentences tend to be cleaner and more obvious than real messages, so they inflate your scores.
Follow these rules:
- Draw texts at random from the data the classifier will see in production.
- Label them by hand, ideally with two people on a subset to check agreement.
- Keep the label names identical to the candidate labels you pass to the pipeline.
- Include enough examples of each class. A class with 3 examples gives a very noisy score.
- Do not tune labels or templates on the same texts you report final results on. Split the sample into a development set for tuning and a test set you look at once.
Rule 5 matters more for zero-shot than for supervised models. There are no weights to overfit, but you can still overfit by trying twenty templates and keeping the one that scores best on a small sample.
Accuracy
Accuracy is the fraction of examples where the predicted label equals the true label.
accuracy = correct predictions / total predictionsIt is easy to read, but it hides problems when classes are imbalanced. Suppose 90 of 100 messages are "billing". A classifier that always answers "billing" gets 0.90 accuracy and never finds a single sales or support message.
Precision, recall and F1
For one class, count three things:
- True positives (TP): examples of the class that the model labeled with that class.
- False positives (FP): examples of other classes that the model labeled with this class.
- False negatives (FN): examples of the class that the model labeled as something else.
From these:
- Precision is TP / (TP + FP). Of the messages the model called "billing", how many were billing?
- Recall is TP / (TP + FN). Of the real billing messages, how many did the model find?
- F1 is the harmonic mean of precision and recall: 2 · P · R / (P + R). It is high only when both are high.
Macro F1
Macro F1 computes F1 separately for each class and then takes the plain average. Every class counts equally, whatever its size. The "always billing" classifier above gets an F1 near 0.95 for billing and 0 for the other two classes, so its macro F1 is about 0.32 even though its accuracy is 0.90.
Use macro F1 when rare classes matter as much as common ones, which is common in routing and triage tasks. Report it next to accuracy, not instead of it.
| Metric | Weights classes by | Good for | Weak spot |
|---|---|---|---|
| Accuracy | Number of examples | Balanced classes | Hides failures on rare classes |
| Macro F1 | Equally | Imbalanced classes, rare classes that matter | A tiny class makes the average noisy |
| Weighted F1 | Number of examples | Overall quality with per-class balance | Behaves like accuracy when one class dominates |
Running the evaluation
The pipeline returns labels sorted by score, so the first label is the top prediction. This code compares it with hand-labeled examples.
from sklearn.metrics import accuracy_score, f1_score
from transformers import pipeline
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
labels = ["billing", "technical support", "sales"]
texts = [
"I was charged twice for my subscription this month.",
"The app freezes every time I open the settings page.",
"Do you offer a discount for annual plans?",
]
y_true = ["billing", "technical support", "sales"]
y_pred = [classifier(t, candidate_labels=labels)["labels"][0] for t in texts]
print("accuracy:", accuracy_score(y_true, y_pred))
print("macro F1:", f1_score(y_true, y_pred, average="macro"))Three examples only demonstrate the mechanics. If all three are correct you will see 1.0 for both metrics, which tells you almost nothing. A real run uses a much larger sample.
Where errors hide
The aggregate numbers say how much the model gets wrong. To see what it gets wrong, print a per-class report and a confusion matrix. A confusion matrix is a table where each row is a true class and each column is a predicted class.
from sklearn.metrics import classification_report, confusion_matrix
print(classification_report(y_true, y_pred, labels=labels, zero_division=0))
print(confusion_matrix(y_true, y_pred, labels=labels))Pass labels=labels so the rows and columns follow your label order and classes that never appear still show up. Set zero_division=0 so a class with no predictions gives 0 instead of a warning.
Read the matrix for patterns. If "sales" messages often land in "billing", the two label names may overlap in meaning, which the label-design chapter covers.
An evaluation workflow
The loop below separates tuning from reporting.
Edge cases and pitfalls
Single-label metrics on multi-label output
The code above takes the top label, which assumes exactly one correct label per text. If you use multi_label=True, a text can have several true labels. Taking the top label then undercounts correct answers. For multi-label tasks, compare sets of labels with a threshold and use per-label precision and recall, or sklearn's multi-label support with a binary indicator matrix.
Ties and label order
When scores are nearly equal, the ordering is sensitive to small changes in wording or template. A difference of one example between two configurations is noise, not evidence.
Texts that fit no label
Real traffic contains messages that belong to none of your classes. The pipeline always returns a ranked list, so it will assign one of them anyway. If you plan to abstain on low scores, add an "other" class to the sample, or handle it as described in the thresholds chapter. Otherwise your metrics describe a cleaner problem than you will meet.
Small samples
With 30 examples, one mistake moves accuracy by about 3 points. Treat differences smaller than that as meaningless. A simple check is to resample your test set with replacement a few hundred times, recompute the metric each time, and look at the spread.
import random
from sklearn.metrics import f1_score
def bootstrap_macro_f1(y_true, y_pred, rounds=500, seed=0):
rng = random.Random(seed)
n = len(y_true)
scores = []
for _ in range(rounds):
idx = [rng.randrange(n) for _ in range(n)]
t = [y_true[i] for i in idx]
p = [y_pred[i] for i in idx]
scores.append(f1_score(t, p, average="macro", zero_division=0))
scores.sort()
return scores[int(0.025 * rounds)], scores[int(0.975 * rounds)]
low, high = bootstrap_macro_f1(y_true, y_pred)
print(f"macro F1 95% interval: {low:.2f} to {high:.2f}")If two configurations have overlapping intervals, you cannot say which is better from this sample.
Compare against a baseline
A number only means something next to a reference. Compute the majority-class accuracy and a supervised baseline if you have any labeled training data. If zero-shot macro F1 is not clearly above the majority baseline, the setup is not working.
Summary of what to report
When you present results, give the sample size, how it was drawn, the class counts, accuracy, macro F1, and the per-class breakdown. State the model, the labels and the hypothesis template so someone else can reproduce the run.
Exercise
A test set has 95 "billing" messages and 5 "sales" messages. A classifier predicts "billing" for every message. What are its accuracy and approximate macro F1 over the two classes, and why do the two numbers differ?
Show answer
Accuracy is 95/100 = 0.95. For billing, precision is 95/100 = 0.95 and recall is 1.0, so F1 is about 0.974. For sales, there are no true positives, so F1 is 0. Macro F1 is (0.974 + 0) / 2, about 0.49. Accuracy counts every example equally, so the large class dominates. Macro F1 gives each class equal weight, so the complete failure on "sales" pulls the score down.
Exercise
You tried 15 hypothesis templates on a 40-example sample and the best one reached macro F1 0.81. Why is 0.81 a poor estimate of how it will perform in production, and what two steps would give a better estimate?
Show answer
You chose the best of 15 results on a small sample, so the winner partly reflects luck and quirks of those 40 texts. The score is optimistically biased. Better steps: split the labeled data into a development set for choosing the template and a separate test set scored once, and enlarge the sample or bootstrap it to see the uncertainty around the score.