Sub topic 13
Filtering synthetic labels by confidence and agreement
This chapter assumes you can write basic Python and train and evaluate a text classifier. It also assumes you know precision, recall and F1, and have read the earlier chapter on using an LLM as a labeling source. Here we decide which LLM-produced labels are good enough to train on.
Why filter at all
An LLM labels every example you give it, including the ones it should not. A review that says "Thank you, but it is terrible" gets a label with the same fluent confidence as "I love this phone". If you train on all of those labels, the classifier learns from the model's guesses as well as its knowledge.
Filtering keeps the examples where the LLM's label is more likely to be right and drops the rest. It trades coverage (how many examples you keep) for accuracy (how many kept labels are correct). A smaller, cleaner set often trains a better classifier than a larger, noisier one. That is not guaranteed, so you measure it, as described below.
Agreement as a confidence signal
Chat-style LLM APIs usually do not return a trustworthy probability for a label. A practical substitute is self-consistency: ask the same question k times with a nonzero sampling temperature, then measure how often the answers agree.
- If all 5 answers say "positive", agreement is 1.0.
- If 3 say "positive" and 2 say "negative", agreement is 0.6.
- Easy examples tend to get stable answers. Ambiguous ones tend to flip.
The function below implements this. It takes ask, any function from a prompt string to a reply string, so you can plug in any model client or a test stub.
from collections import Counter
LABELS = ('positive', 'negative')
def llm_label(text, ask, k=5):
"""Label text by asking an LLM k times.
`ask` is any function that takes a prompt string and returns a string.
Returns (label, agreement), or (None, 0.0) if no valid answer was given.
"""
prompt = (
'Classify the sentiment of the review as positive or negative. '
'Answer with one word.\n\nReview: ' + text
)
answers = []
for _ in range(k):
a = ask(prompt).strip().lower().rstrip('.')
if a in LABELS:
answers.append(a)
if not answers:
return None, 0.0
label, count = Counter(answers).most_common(1)[0]
return label, count / k
def keep_confident(examples, ask, min_agreement=0.8):
kept = []
for text in examples:
label, agreement = llm_label(text, ask)
if label is not None and agreement >= min_agreement:
kept.append((text, label))
return keptThree details in this code matter.
- Invalid answers are dropped, not counted as votes. If the model replies "It depends" or "Positive, because...", the parse fails and that sample is ignored.
- The denominator is k, not the number of valid answers. Suppose 3 of 5 replies are valid and all say "positive". Agreement is 0.6, not 1.0. Format failures lower confidence, which is usually what you want, because a model that cannot follow the output format on this input is unreliable on it.
- Ties. With two labels and an odd k there are no ties. With an even k, or with more than two classes,
most_commonbreaks ties by first occurrence, which is arbitrary. Use an odd k, or set a threshold above 0.5 so that ties are discarded.
Choosing the threshold with a gold set
The right min_agreement depends on your model, task and data. Measure it on a small hand-labeled gold set. For each threshold, compute coverage (the share of examples kept) and accuracy of the kept labels, then pick the point your downstream classifier can live with.
The script below is self-contained. It replaces the real LLM with a stub whose answers are noisy, so you can run it without an API key. Each review has a probability that the stub answers "positive". Clear reviews are near 0 or 1, and ambiguous ones are near 0.5.
import random
from collections import Counter
LABELS = ('positive', 'negative')
def llm_label(text, ask, k=5):
prompt = (
'Classify the sentiment of the review as positive or negative. '
'Answer with one word.\n\nReview: ' + text
)
answers = []
for _ in range(k):
a = ask(prompt).strip().lower().rstrip('.')
if a in LABELS:
answers.append(a)
if not answers:
return None, 0.0
label, count = Counter(answers).most_common(1)[0]
return label, count / k
def keep_confident(examples, ask, min_agreement=0.8):
kept = []
for text in examples:
label, agreement = llm_label(text, ask)
if label is not None and agreement >= min_agreement:
kept.append((text, label))
return kept
# (text, gold label, probability the stub answers "positive")
GOLD = [
('I love this phone', 'positive', 0.97),
('Great battery life', 'positive', 0.95),
('Works fine, nothing special', 'positive', 0.60),
('Thank you, but it is terrible', 'negative', 0.45),
('Arrived broken', 'negative', 0.03),
('I want a refund', 'negative', 0.05),
('Not bad, not good', 'negative', 0.50),
('Excellent screen', 'positive', 0.96),
]
P_POSITIVE = {text: p for text, _, p in GOLD}
GOLD_LABEL = {text: label for text, label, _ in GOLD}
rng = random.Random(0)
def stub_ask(prompt):
text = prompt.split('Review: ', 1)[1]
return 'Positive.' if rng.random() < P_POSITIVE[text] else 'negative'
texts = [text for text, _, _ in GOLD]
for threshold in (0.6, 0.8, 1.0):
kept = keep_confident(texts, stub_ask, min_agreement=threshold)
coverage = len(kept) / len(texts)
correct = sum(GOLD_LABEL[t] == label for t, label in kept)
accuracy = correct / len(kept) if kept else float('nan')
print(f'threshold={threshold} coverage={coverage:.2f} accuracy={accuracy:.2f}')The exact numbers depend on the random seed, but the pattern should hold. With k=5 and two labels, the top label always has at least 3 of 5 votes, so a threshold of 0.6 keeps every example that has any valid answer. Raising it to 0.8 or 1.0 removes the ambiguous reviews first, so coverage falls and accuracy of the kept set should rise. Check this on your own data rather than assuming it.
A gold set of a few hundred examples is enough to see the curve. Keep it separate from anything the LLM or your prompts were tuned on, as covered in the evaluation chapter.
Beyond a single agreement score
Self-consistency is the simplest signal. Others can be combined with it.
| Signal | How to get it | Main weakness |
|---|---|---|
| Sample agreement | Ask k times at temperature above 0 | Costs k calls per example |
| Token log-probabilities | Read the probability of the label token, if the API exposes it | Often poorly calibrated, and unavailable on many APIs |
| Verbalized confidence | Ask the model to state a 0 to 100 score | Models cluster at "90" and "95" |
| Cross-prompt or cross-model agreement | Use two phrasings or two models and keep matches | Models can share the same blind spots |
| Agreement with other sources | Compare to labeling functions or a label model | Needs those sources to exist and to be independent |
A useful pattern is to treat the LLM as one more column in the label matrix. Its agreement score then decides whether it votes or abstains, which matches how labeling functions already work. Low-agreement answers become abstentions instead of wrong votes.
Edge cases and failure modes
Consistent is not correct. An LLM can give the same wrong answer five times. Sarcasm and domain jargon are typical causes. Agreement filters out noise that varies between samples, but it does nothing about systematic error. Only the gold set tells you about that.
Filtering skews the data. Easy examples survive and hard ones vanish. The kept set can become unrepresentative, and the classifier then does poorly on exactly the ambiguous inputs you most care about. Compare the kept set against the full pool by length, topic and difficulty.
Class balance shifts. If the model is more consistent about "negative" than "positive", a single threshold keeps more negatives. Count labels before and after filtering. If they diverge, use per-class thresholds or resample.
Prompt wording changes everything. Agreement measures stability under one prompt. Small rewordings can change both labels and confidence. Fix the prompt before choosing a threshold, and redo the sweep if you change it.
Sampling cost scales with k. Five samples per example is five times the price. Many pipelines sample 3 times first and sample more only for examples that disagree.
Do not discard silently. Keep the dropped examples. They are your best candidates for hand labeling, since they are the ones the model finds hard, and a handful of human labels there is worth more than thousands of easy ones.
Exercise
Exercise
You label 1,000 reviews with k=4 samples per review and keep only reviews with agreement of 1.0. Afterward, 90% of the kept reviews are negative, but the full pool is about 50% negative. Name two plausible causes and one fix.
Show answer
Two plausible causes: (1) the model answers "negative" more consistently than "positive", so positive reviews fail the 1.0 cutoff more often, and (2) the prompt or the model has a bias that makes borderline reviews flip toward "positive" between samples. A fix is to set a per-class threshold, for example a lower one for positive, or to resample the kept set to restore balance. Check the result against the gold set per class.
Exercise
In llm_label, three of five replies are "positive" and the other two are "I'm not sure". What agreement does the function return, and why is dividing by k rather than by the number of valid answers the safer choice?
Show answer
It returns ("positive", 0.6), because 3 / 5 = 0.6. Dividing by the 3 valid answers would give 1.0 and hide the fact that the model failed to give a usable answer on 40% of samples. Dividing by k makes format failures reduce confidence.