Sub topic 12
Testing a Few-Shot Prompt on Held-Out Data
This chapter assumes you can read short Python, know the system, user, and assistant roles in chat prompts, and have already built a few-shot prompt like the sentiment classifier from earlier chapters. Here you will measure whether that prompt works, instead of judging it by a few outputs that looked fine.
Why you need a held-out set
A prompt that looks good on three hand-picked inputs tells you very little. Language models are sensitive to wording, example order, and which examples you picked. A change that fixes one input can quietly break five others.
A held-out set is a group of labeled inputs that you do not use as in-prompt examples and do not tune the prompt against more than you have to. Each item has an input and the correct answer. You run the prompt on every item and compare the model's answer with the label.
Two groups of data have different jobs:
| Data | Purpose | Appears in the prompt? |
|---|---|---|
| Example pool | Source of the in-prompt examples | Yes, a few of them |
| Development set | Compare prompt variants while you iterate | No |
| Test set | One final check of the chosen prompt | No |
If an item is both in the prompt and in the scoring data, the model can copy the label it was shown. The score then measures memorization of the prompt, not the skill you care about. This is called leakage, and it makes a weak prompt look strong.
Building the split
Split your labeled data before you write any prompt. Shuffle with a fixed seed so the split is repeatable.
import random
def split_data(labeled, pool_size, dev_size, seed=0):
items = list(labeled)
random.Random(seed).shuffle(items)
pool = items[:pool_size]
dev = items[pool_size:pool_size + dev_size]
test = items[pool_size + dev_size:]
return pool, dev, testThe pool supplies candidate examples. The development set is for comparing variants. The test set stays untouched until you have picked a final prompt. If you look at test results after every edit, you are tuning to the test set, and it stops being an honest estimate.
How big should the sets be? With 50 items, one wrong answer moves accuracy by 2 points, so small differences are noise. With 200 items, each item moves it by 0.5 points. As a rough guide, a gap of a few points on a few dozen items is not evidence of a better prompt.
Measuring accuracy
The accuracy function from earlier compares each prediction with its label.
def accuracy(predict, labeled):
correct = 0
for text, label in labeled:
if predict(text).strip().lower() == label:
correct += 1
return correct / len(labeled)predict is any function that takes an input string and returns the model's reply. That keeps the scoring code independent of which model or prompt you use. The call to strip().lower() forgives whitespace and capitalization, which are formatting differences and not real errors.
Note what it does not forgive. A reply such as Positive. with a trailing period, or The sentiment is positive, counts as wrong. That is often what you want, because downstream code may need a clean label. If you instead want to score the meaning, normalize the reply first, as the next section shows.
Wiring a prompt to predict
Here is a predict function for the chat-style prompt. The call_model argument is whatever function sends messages to your model and returns text. It is a parameter because the API differs by provider.
def make_predict(call_model, examples):
def predict(text):
messages = build_messages(examples, text)
return call_model(messages)
return predictWith a stub model you can test the scoring code without any API calls:
def fake_model(messages):
last = messages[-1]["content"].lower()
return "negative" if "stopped" in last else "positive"
dev = [
("It stopped working after a week.", "negative"),
("Great screen and fast charging.", "positive"),
]
predict = make_predict(fake_model, examples=[])
print(accuracy(predict, dev))This prints 1.0. Testing the harness with a fake model first catches bugs in the scoring code before they get mixed up with model behavior.
Looking beyond one accuracy number
Accuracy hides where the prompt fails. Two prompts can both score 80% while one never predicts neutral. Look at the errors by class.
from collections import Counter
def confusion(predict, labeled):
counts = Counter()
for text, label in labeled:
guess = predict(text).strip().lower()
counts[(label, guess)] += 1
return countsEach key is a pair of the true label and the predicted label. Print the counts sorted by frequency and you see patterns such as ("neutral", "positive") appearing 12 times. That pattern points at a specific fix: add a neutral example that resembles the confusing inputs, or sharpen the instruction.
Also read the actual wrong answers. A list of 10 misclassified inputs with the model's reply beside each often shows a cause that no metric would. Common causes are:
- The label itself is debatable, so the data needs fixing and not the prompt.
- The reply is correct but formatted differently, such as
Positive.. - The input type is missing from your examples, such as very short or very long reviews.
Separating format errors from task errors
If the model answers The sentiment is positive, the task was done right and the format was not. Count these separately. A strict score tells you whether the output can be parsed. A lenient score tells you whether the model understood the task.
def extract_label(reply, labels):
reply = reply.lower()
found = [label for label in labels if label in reply]
return found[0] if len(found) == 1 else None
def lenient_accuracy(predict, labeled, labels):
correct = 0
for text, label in labeled:
if extract_label(predict(text), labels) == label:
correct += 1
return correct / len(labeled)If lenient accuracy is much higher than strict accuracy, the examples are not enforcing the format. Check that every example answers with exactly one word, as the format-consistency chapter described.
Comparing prompt variants fairly
The point of a test harness is to compare choices. Typical comparisons are zero-shot against few-shot, three examples against eight, and one ordering against another. Keep everything else fixed so one change explains the difference.
def compare(variants, call_model, dev):
results = {}
for name, examples in variants.items():
predict = make_predict(call_model, examples)
results[name] = accuracy(predict, dev)
return resultsPass variants as a dictionary such as {"zero": [], "three": pool[:3], "eight": pool[:8]}. Every variant is scored on the same development set, so the numbers are comparable.
Three habits make the comparison trustworthy:
- Set the model's temperature to 0, or as low as the API allows, so repeated runs give the same answers. At higher temperatures, run each variant several times and average.
- Change one thing at a time. If you add examples and reorder them together, you cannot tell which helped.
- Test with several random draws of examples. If you pick three examples from the pool and get 82%, try four other draws of three. If the scores range from 70% to 85%, the choice of examples matters more than the count, and a single draw proves little.
The last habit is easy to script:
def spread(call_model, pool, dev, k=3, trials=5, seed=0):
rng = random.Random(seed)
scores = []
for _ in range(trials):
examples = rng.sample(pool, k)
scores.append(accuracy(make_predict(call_model, examples), dev))
return min(scores), sum(scores) / len(scores), max(scores)A wide spread means your prompt is fragile. That is a finding in itself, and it suggests picking examples more carefully or selecting them per query.
Edge cases in evaluation
Several details can quietly distort your numbers.
- Class imbalance. If 80% of the held-out items are
positive, a model that always answerspositivescores 80%. Compute the majority-class baseline and report it next to your accuracy. If you are at 82% against a baseline of 80%, you have learned almost nothing. - Duplicates. Near-identical reviews in both the pool and the test data cause leakage even when no item appears twice. Remove duplicates before splitting.
- Label noise. If humans disagree on 10% of labels, no prompt can score reliably above about 90%. Check a sample of labels by hand.
- Unparseable replies. Decide in advance how to score an empty reply, a refusal, or an answer outside the label set. Counting them as wrong is the safe default. Also report how many there were.
- Distribution shift. Your held-out data should look like real traffic. If production inputs are longer or messier than your test set, the test score overstates real performance.
def majority_baseline(labeled):
counts = Counter(label for _, label in labeled)
return counts.most_common(1)[0][1] / len(labeled)Cost and latency are part of the result
Each added example makes every request longer. A prompt with eight examples of 40 tokens each adds 320 tokens per call. At thousands of calls per day, that is a real cost and a real delay.
Record the prompt token count next to each accuracy score. If five examples score 84% and eight score 85%, the extra three examples rarely justify their cost. Choose the smallest prompt whose accuracy is within the noise of the best one.
| Variant | Accuracy | Prompt tokens | Verdict |
|---|---|---|---|
| Zero-shot | 0.71 | 40 | Baseline |
| 3 examples | 0.82 | 160 | Large gain |
| 5 examples | 0.84 | 240 | Small gain |
| 8 examples | 0.85 | 360 | Within noise |
The numbers above are an illustration of how to read such a table. Your own values will differ.
What to do with the result
If the prompt beats the zero-shot baseline and the majority baseline on the development set, run it once on the test set and record that number. If it does not, the error analysis tells you what to change: add examples for the confused classes, fix the format, or reconsider whether few-shot prompting is the right tool. The last chapters of this tutorial return to that decision.
Exercise
A team builds a sentiment prompt with five in-prompt examples. They score it on 40 labeled reviews and get 85%. Later they find that 4 of the 5 in-prompt examples are also among the 40 scoring reviews, and that 34 of the 40 reviews are labeled positive. List two problems with the 85% figure and say how to fix each.
Show answer
First, leakage: 4 of the scoring items appear in the prompt with their labels, so the model may copy them. Fix this by removing in-prompt examples from the scoring data, and re-split the data before writing the prompt. Second, the majority baseline is 34/40 = 85%, so always answering positive would score the same. Fix this by collecting a more balanced held-out set, or by reporting per-class results and the baseline. A further weakness is that 40 items is small, since each item moves accuracy by 2.5 points.
Exercise
Prompt A scores 0.78 strict accuracy and 0.91 lenient accuracy on the development set. What does the gap suggest, and what should you change first?
Show answer
The model usually understands the task but often answers in a form that does not match the exact label, such as a full sentence or a trailing period. Change the examples and the instruction so every answer is exactly one label word, then re-measure strict accuracy.