Sub topic 10
Thresholds and abstaining on low-confidence predictions
A zero-shot classifier always returns an answer. The pipeline sorts the candidate labels and gives you a top one, even when the text fits none of them. This chapter shows how to add a score threshold so the classifier can decline to answer, and how to choose that threshold from data.
This chapter assumes you can run the zero-shot-classification pipeline and know the difference between single-label and multi-label scoring. It also assumes you know accuracy and macro F1 from the evaluation chapter.
Why a top label is not an answer
Take the message "What is the capital of Australia?" and the labels billing, technical support and sales. The pipeline still returns a ranked list, and one label is first. Nothing in the output says "none of these".
In production, a wrong confident answer is often worse than no answer. A misrouted support ticket wastes a customer's time. A mislabeled document pollutes a report. Abstaining means the system returns "no label" and sends the item to a person, a fallback model, or a default queue.
Abstaining trades coverage for precision:
- Coverage is the share of inputs that receive a label.
- Selective accuracy is the accuracy measured only on the inputs that received a label.
A higher threshold lowers coverage and usually raises selective accuracy. The task is to find the point on that curve your application can live with.
What the scores mean
The threshold only makes sense if you know what the number is. The two scoring modes produce different numbers.
In single-label mode, the pipeline takes the entailment logit for each label's hypothesis and applies a softmax across the labels. The scores sum to 1. With three labels, the top score can never fall below 0.333. If the text matches none of the labels, the softmax still spreads probability across them, and one label can end up with a high share. The score measures how the labels compare with each other. It does not measure whether any label fits.
In multi-label mode (multi_label=True), each label is scored on its own. For each hypothesis, the pipeline applies a softmax over the contradiction and entailment logits, as in the manual scoring example from the pipeline chapter. The score for one label is closer to "how strongly does this text entail this one hypothesis". An out-of-scope text can get low scores on every label at once, which makes the scores a better signal for abstaining.
A basic abstaining wrapper
The first step is a function that returns a label or None.
from transformers import pipeline
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
labels = ["billing", "technical support", "sales"]
def predict(text, threshold=0.7):
result = classifier(text, candidate_labels=labels)
top_label = result["labels"][0]
top_score = result["scores"][0]
if top_score < threshold:
return None, top_score
return top_label, top_score
for text in [
"I was charged twice for my subscription this month.",
"What is the capital of Australia?",
]:
label, score = predict(text)
print(f"{text!r} -> {label} ({score:.3f})")The exact scores depend on the model version and library version. The pattern to watch for is that the first text scores high on billing, while the second spreads its scores across the labels and may fall under the threshold. It may not, though. Single-label softmax can give an off-topic text a deceptively high top score, which is why the threshold should be tested and not assumed.
Margin as a second signal
The top score alone misses one case: two labels that score almost the same. In single-label mode, a top score of 0.52 against a runner-up of 0.48 is a coin flip, while 0.52 against 0.20 is not. The margin is the top score minus the runner-up's score.
def predict_with_margin(text, min_score=0.6, min_margin=0.2):
result = classifier(text, candidate_labels=labels)
scores = result["scores"]
top_score, runner_up = scores[0], scores[1]
if top_score < min_score or (top_score - runner_up) < min_margin:
return None
return result["labels"][0]Using both rules makes the classifier more cautious, and you now have two numbers to tune instead of one. Start with the score alone. Add the margin only if the validation data shows confident-looking errors between two close labels.
Thresholds in multi-label mode
In multi-label mode, the threshold decides which labels are applied, and abstaining falls out naturally: an empty list means no label passed.
def predict_multi(text, threshold=0.5):
result = classifier(
text,
candidate_labels=labels,
hypothesis_template="This customer message is about {}.",
multi_label=True,
)
return [
(label, score)
for label, score in zip(result["labels"], result["scores"])
if score >= threshold
]
print(predict_multi("The app crashes when I try to update my payment method."))
print(predict_multi("Thanks, have a great weekend!"))The first call can return both technical support and billing. The second should return an empty list, which is your abstain signal. You can also set a different threshold for each label:
label_thresholds = {"billing": 0.6, "technical support": 0.5, "sales": 0.8}Per-label thresholds help when a label is easy to over-trigger. For example, sales may fire on any message that mentions prices. Each extra threshold is another value to tune, so with a small validation set it can overfit. Use per-label values only when you see a clear per-label pattern in the errors.
Choosing a threshold from labeled data
Choose the threshold on a validation set, not by intuition. The method is to score every example once, then sweep candidate thresholds and measure coverage and selective accuracy at each. Scoring once matters because the model call is the expensive part, and the sweep itself is cheap.
Include out-of-scope examples in the validation set. If every example belongs to one of your labels, the sweep will tell you abstaining only hurts. In the code below, None as the true label means "the correct response is to abstain".
from transformers import pipeline
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
labels = ["billing", "technical support", "sales"]
samples = [
("I was charged twice for my subscription this month.", "billing"),
("The app freezes every time I open the settings page.", "technical support"),
("Do you offer a discount for annual plans?", "sales"),
("My invoice shows a plan I never signed up for.", "billing"),
("I cannot log in even after resetting my password.", "technical support"),
("Can I get a quote for fifty seats?", "sales"),
("What is the capital of Australia?", None),
("Thanks for the quick reply yesterday!", None),
("Your office plants look lovely.", None),
]
texts = [text for text, _ in samples]
truth = [label for _, label in samples]
results = classifier(texts, candidate_labels=labels)
top = [(r["labels"][0], r["scores"][0]) for r in results]
print("threshold coverage selective_acc overall_acc")
for t in [0.0, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95]:
preds = [label if score >= t else None for label, score in top]
answered = [(p, y) for p, y in zip(preds, truth) if p is not None]
coverage = len(answered) / len(truth)
if answered:
selective = sum(p == y for p, y in answered) / len(answered)
else:
selective = float("nan")
overall = sum(p == y for p, y in zip(preds, truth)) / len(truth)
print(f"{t:9.2f} {coverage:8.2f} {selective:13.2f} {overall:11.2f}")The three columns answer different questions:
| Column | Question it answers |
|---|---|
| `coverage` | How many items does the system label by itself? |
| `selective_acc` | When it answers, how often is it right? |
| `overall_acc` | Counting a correct abstention as a correct result, how often is the system right? |
Pick the threshold from your cost model. If a person reviewing an abstained item costs one minute and a wrong label costs ten, accept lower coverage. If review capacity is limited, fix the maximum review rate first, then take the lowest threshold that keeps selective accuracy acceptable. Nine examples is only enough to run the code. A real sweep needs at least a few hundred labeled items, and enough out-of-scope items to represent what production traffic contains.
When the threshold stops working
A tuned threshold is tied to the setup it was tuned in. Change any of these and you must tune again:
- The model or its version.
- The hypothesis template. The template changes the entailment score for every label, so the whole score distribution shifts.
- The number of candidate labels in single-label mode. With more labels, the softmax spreads out and top scores fall.
- The scoring mode.
- The input distribution. Text from a new domain, language or length can move scores in either direction.
Monitor the abstention rate in production. A sudden rise or fall means the traffic or the model changed, even when you have no labels to check accuracy against. Periodically label a random sample of both accepted and abstained items to confirm the threshold still holds.
Do not rely on an other label instead of a threshold. NLI models handle a vague catch-all label like "other" or "none of the above" badly, because "This text is about other" is a weak hypothesis to entail. A threshold on the real labels is more reliable. You can also use the two together if you validate both.
Summary of options
| Approach | Works best with | Main risk |
|---|---|---|
| Top score threshold | Multi-label mode, clear off-topic traffic | Single-label scores stay high for off-topic text |
| Score plus margin | Single-label mode with similar labels | Two values to tune |
| Per-label thresholds | Labels with clearly different behavior | Overfitting on a small validation set |
| Catch-all `other` label | Rarely | Weak hypothesis, unstable scores |
Exercise
A single-label zero-shot classifier with four candidate labels returns a top score of 0.31 for a message. A teammate says this is impossible because the top score can never be below 0.33. Who is right, and what does this tell you about using a single-label top score to detect off-topic text?
Show answer
The teammate's reasoning is right for three labels, where the lowest possible top score is 1/3. With four labels the lowest possible top score is 1/4 = 0.25, so 0.31 is possible. It means the softmax spread probability nearly evenly, which is a weak-signal case. The general point is that single-label scores sum to 1 across the labels, so the top score reflects relative preference, not absolute fit. A low top score does indicate uncertainty, but a high one does not prove the text fits any label, so for off-topic detection multi-label scores or a tuned threshold on labeled out-of-scope examples are more reliable.
Exercise
You raise the threshold from 0.7 to 0.9. Coverage falls from 0.85 to 0.55 and selective accuracy rises from 0.88 to 0.93. Your team can review at most 30% of items by hand. Which threshold do you keep, and why?
Show answer
Keep 0.7. At 0.9, 45% of items are abstained and need review, which is above the 30% capacity. At 0.7, 15% are abstained, which fits. The 5-point gain in selective accuracy at 0.9 does not help if the review queue overflows. A threshold between the two values might meet the capacity limit with a smaller loss in coverage, so sweep intermediate values on the validation set and choose the highest threshold whose abstention rate stays at or below 30%.