Sub topic 9
Checking your analysis against human labels
This chapter assumes you can write basic Python and read JSON. It also assumes you know precision, recall and averages, and have already produced labels for reviews with a lexicon, a classifier or an LLM. Here you will test whether those labels can be trusted.
Why you need a human reference
A pipeline that prints a sentiment for every review looks finished, but it can still be wrong in ways that are hard to see. A model that labels most reviews "positive" will look reasonable on a dashboard when most customers really are happy. It will also hide every unhappy customer.
The fix is a gold sample: a set of reviews labelled by people, which you treat as the reference. You run your analysis on the same reviews and compare. The comparison tells you how much to trust the output, and where.
Human labels are not perfect truth. Two careful people will disagree on sarcasm, mixed reviews and short comments such as "fine, I guess". So the gold sample measures agreement with human judgement. It does not measure truth.
Building the gold sample
The sample decides whether your numbers mean anything. Follow these rules.
- Sample at random from the data you will analyse. Do not hand-pick clear examples. Easy cases inflate scores.
- Make it large enough for the rare classes. If 3% of reviews are about "support", a random sample of 100 holds about three of them. Per-class numbers from three examples are noise. Either sample more, or add extra reviews for rare classes and remember to report that you did.
- Write label guidelines first. Use the taxonomy from the first chapter. Give a definition and two or three examples for each label, and say what to do with mixed or off-topic reviews.
- Use at least two annotators on part of the sample. This lets you measure how consistent people are with each other. That figure is the ceiling for the model.
- Keep the gold sample out of prompt tuning. If you adjust a prompt until it scores well on these reviews, you have trained on your test. Split it: a development set for tuning and a held-out test set you look at once.
- Redact personal data before annotators see it. Use the cleaning step from the text-preparation chapter.
Measuring agreement
Agreement can be measured in several ways. Raw accuracy, the share of labels that match, is simple but misleading when classes are unbalanced. If 80% of reviews are positive, a model that always says "positive" is 80% accurate and useless.
Two better tools are per-class precision and recall, and Cohen's kappa.
- Precision for a class: of the reviews the model put in that class, how many the humans also put there.
- Recall for a class: of the reviews the humans put in that class, how many the model found.
- Cohen's kappa is agreement corrected for chance. A value of 1 is perfect agreement and 0 is no better than guessing from the label frequencies. Negative values are worse than chance. Common rules of thumb call 0.6 to 0.8 substantial and above 0.8 near perfect, but these are guides and not standards.
The code below compares model labels to human labels on the same reviews.
from sklearn.metrics import classification_report, cohen_kappa_score
human = ["positive", "negative", "negative", "neutral", "positive", "negative"]
model = ["positive", "negative", "neutral", "neutral", "positive", "positive"]
print(classification_report(human, model, zero_division=0))
print("Cohen's kappa:", cohen_kappa_score(human, model))classification_report prints precision, recall, F1 and support (the number of human labels) for each class. The argument zero_division=0 stops a warning when a class receives no predictions, and scores that class as 0.
In this tiny example the model labelled one negative review as neutral and another as positive. Negative recall is therefore 1 out of 3 (it found one of three negatives), and positive precision is 2 out of 3 (one of its three positives was really negative). With six reviews these numbers show how the tools work, but they are far too few to trust.
Reading the results
Read the per-class lines before the overall score. An average can hide a failure on the class you care about most.
| Pattern | Likely cause | What to try |
|---|---|---|
| Low recall for negative | Model is too generous, or sarcasm is missed | Add sarcastic examples to the prompt, review the missed cases |
| Low precision for negative | Model treats complaints about one aspect as overall negative | Add a "mixed" label or move to aspect-level labels |
| Kappa much lower than accuracy | Unbalanced classes, so accuracy flatters the model | Report kappa and per-class scores |
| Model agrees with humans about as well as humans agree with each other | You are near the ceiling | Stop tuning, since more work will not help |
| Good on development set, poor on held-out set | Over-tuning | Collect new examples and keep a fresh test set |
A confusion matrix shows which labels get mixed up. It lists human labels in rows and model labels in columns. Most errors cluster in a few cells, often "neutral" against "mixed", and fixing those cells helps more than general tuning.
from sklearn.metrics import confusion_matrix
labels = ["positive", "neutral", "negative"]
human = ["positive", "negative", "negative", "neutral", "positive", "negative"]
model = ["positive", "negative", "neutral", "neutral", "positive", "positive"]
matrix = confusion_matrix(human, model, labels=labels)
for name, row in zip(labels, matrix):
print(f"{name:>9}", row)Each printed row is one human label. The numbers in the row show how many of those reviews the model placed under positive, neutral and negative, in that order.
Evaluating structured extraction
Chapter six extracts a sentiment, a list of themes and an evidence quote. Each field needs its own check.
- Sentiment is a single label, so use the precision, recall and kappa tools above.
- Themes are a list, and a review can have several. Treat each theme as a yes or no question and compute precision and recall per theme. Alternatively, compare the full sets with the Jaccard score, the size of the overlap divided by the size of the union.
- Evidence can be checked automatically. The validation code already discards quotes that do not appear in the review. Track how often that happens. A high discard rate means the model is inventing text.
- Schema validity: count how often the reply is valid JSON with allowed labels. This needs no human at all.
Measuring themes with scikit-learn looks like this.
from sklearn.metrics import precision_recall_fscore_support
from sklearn.preprocessing import MultiLabelBinarizer
themes = ["pricing", "delivery", "product_quality", "support", "usability", "other"]
human = [["delivery"], ["pricing", "support"], ["product_quality"], ["delivery", "other"]]
model = [["delivery"], ["pricing"], ["product_quality", "usability"], ["delivery"]]
binarizer = MultiLabelBinarizer(classes=themes)
y_true = binarizer.fit_transform(human)
y_pred = binarizer.transform(model)
precision, recall, f1, support = precision_recall_fscore_support(
y_true, y_pred, zero_division=0
)
for theme, p, r, f, s in zip(themes, precision, recall, f1, support):
print(f"{theme:16} precision={p:.2f} recall={r:.2f} f1={f:.2f} n={s}")MultiLabelBinarizer turns each list into a row of 0s and 1s, one column per theme. The function then scores every column on its own. Pay attention to the n column. A theme with an n of 1 or 2 gives a score you cannot rely on.
Evaluating topics and summaries
Cluster-based topics have no labels to compare against, so evaluation is different. Ask two people to read a sample of reviews from each cluster and name the theme. If they cannot agree on a name, or many reviews do not fit it, the cluster is not useful. You can also assign each sampled review to a theme from your taxonomy by hand, then measure how pure each cluster is.
For summaries, check traceability and coverage. Pick a random set of claims from the summary and follow each back to its source reviews. Count how many claims are supported. Then take a random set of reviews and check that their main points appear in the summary. The first test catches invented claims. The second catches omissions.
Confidence and sample size
A score from a small sample has a wide margin of error. If your model got 42 of 50 correct, the accuracy is 84%, but the true figure could plausibly be anywhere from about 71% to 93%. You can estimate that range with a bootstrap: resample the sample many times and see how much the score moves.
import random
def bootstrap_interval(matches, runs=2000, seed=0):
rng = random.Random(seed)
n = len(matches)
scores = []
for _ in range(runs):
resample = [matches[rng.randrange(n)] for _ in range(n)]
scores.append(sum(resample) / n)
scores.sort()
return scores[int(0.025 * runs)], scores[int(0.975 * runs)]
matches = [1] * 42 + [0] * 8 # 42 correct out of 50
low, high = bootstrap_interval(matches)
print(f"accuracy 0.84, 95% interval about {low:.2f} to {high:.2f}")When you compare two prompts or two models, check that the difference is larger than this range. A gap of two points on 50 reviews is noise.
A repeatable evaluation loop
Evaluation is not a one-off step. The data, the product and the model all change. The diagram shows a loop you can repeat each time you change a prompt or a model.
Errors on the development set drive each round of tuning. The test set is read only when you think you are done.
Common mistakes
- Reporting accuracy alone on unbalanced data.
- Testing on easy examples picked by hand.
- Ignoring annotator disagreement. If humans reach a kappa of 0.5, a model kappa of 0.5 is not a failure. Fix the guidelines first.
- Evaluating once. A new product, a new language or a seasonal campaign can shift the review text. Re-check on a fresh sample on a schedule, for example monthly.
- Mixing languages without checking each. A model that is strong in English can be weak in other languages. Report scores per language when your data has several.
- Skipping the cost of errors. A missed safety complaint matters more than a misfiled pricing remark. Set a higher recall target for the classes where misses are costly.
Exercises
Exercise
A model labels 90 of 100 reviews "positive" and the human labels also have 90 positive reviews, but the model's positives are chosen almost at random. Accuracy is 82%. Why is accuracy a poor summary here, and which metric would show the problem?
Show answer
With 90% of reviews positive, even random positive guesses give high accuracy, so the number reflects class balance more than skill. Cohen's kappa corrects for chance agreement and would be close to 0 here. Per-class precision and recall for the minority class would also show the model finds few of the true negatives.
Exercise
You tuned your prompt on 200 labelled reviews until the sentiment kappa reached 0.78, and you report that figure to your team. What is wrong, and how do you fix it?
Show answer
The figure was measured on the same data used for tuning, so it overstates real performance. Split the labelled data into a development set for tuning and a held-out test set. Report the kappa from the held-out set, measured once after the prompt is final. If no held-out data exists, label a fresh random sample.
Exercise
Two annotators label 100 reviews and reach a kappa of 0.55 with each other. Your model reaches 0.52 against one of them. What should you do first?
Show answer
The model is close to the human ceiling, so more prompt tuning is unlikely to help. Improve the label guidelines instead. Find the cases where the annotators disagree, usually mixed or neutral reviews, clarify those definitions, relabel, and measure again.