From ML Metrics to LLM Evals: Same Ruler, New Targets
Precision and recall don't disappear when you build with LLMs; they move. A spam filter at 0.75/0.75, precision@3 and recall@3 on six help-desk documents, exact match vs a key-fact check on two written answers, and the rubric that replaces a single label.
What you will learn
- Explain precision and recall with one picture: the net and the lake
- Carry precision and recall over to retrieval as precision@k and recall@k
- See why exact match breaks on generated text and a key-fact check still works
- Break a good answer into a rubric of yes-or-no checks with a pass rate
Before you start
- Precision, Recall and F1 Score
- Basic Python
What happens to precision and recall when you start building with LLMs? The short answer: they don't disappear. They move. The same ruler gets pointed at new things: first a spam label, then a list of retrieved documents, then a written answer.
We'll take those three in turn with three small scripts, then see the rubric that replaces a single label. No API key is needed.
A fishing net
Here's a lake. It has fish in it, and also a few old boots. You throw a net and pull it out. In the net there are three fish and one boot.
- Precision asks about the net: of everything in the net, how much is fish? Three out of four.
- Recall asks about the lake: of all the fish in the lake, how many did we catch? Only three of eight.
Keep this net in mind. It comes back twice.
The classic ruler: one label per row
Here's the classic version, with a spam filter and ten emails. truth says which emails are really spam; a person decided that, one label per email. flagged is what the filter said.
"""Precision and recall on a spam filter: 10 emails, labels by hand."""
from sklearn.metrics import precision_score, recall_score
truth = [1, 1, 1, 1, 0, 0, 0, 0, 0, 0] # 1 = really spam
flagged = [1, 1, 1, 0, 1, 0, 0, 0, 0, 0] # 1 = filter said spam
# of the emails we flagged, how many were spam?
print("precision:", precision_score(truth, flagged))
# of the spam that exists, how much did we flag?
print("recall: ", recall_score(truth, flagged))
precision: 0.75
recall: 0.75
The filter got three spam emails right, missed one and raised one false alarm. Of the four it flagged, three were spam: precision 0.75. Of the four spam emails that exist, it flagged three: recall 0.75. One label per row, two clear questions. (The four boxes behind these numbers, and F1, are in Precision, Recall and F1 Score.)
Retrieval is a net too
Now an LLM app. Before a model answers a help-desk question, a retriever looks up a few documents to hand it. The question is "I can't log in to my account". A person has marked which documents are really relevant: the password reset and the two-factor codes. The retriever picks its top three. That's the net.
"""Same ruler, new target: precision@k and recall@k for retrieval."""
import numpy as np
from sentence_transformers import SentenceTransformer
docs = [
"Reset your password from Settings > Security.", # 0
"Refunds reach your card in 5 to 7 working days.", # 1
"Change the delivery address before the order ships.", # 2
"Two-factor codes expire after 30 seconds.", # 3
"Cancelled orders are refunded to the original card.", # 4
"Upload photos as JPG or PNG, up to 10 MB.", # 5
]
tests = { # question -> the docs a person marked as relevant
"I can't log in to my account": {0, 3},
"When do I get my money back?": {1, 4},
}
K = 3
model = SentenceTransformer("all-MiniLM-L6-v2")
doc_vecs = model.encode(docs, normalize_embeddings=True)
for question, relevant in tests.items():
q = model.encode(question, normalize_embeddings=True)
top_k = set(np.argsort(-(doc_vecs @ q))[:K].tolist())
hits = top_k & relevant
print(question, "-> retrieved", sorted(top_k))
print(f" precision@{K}: {len(hits) / K:.2f}"
f" recall@{K}: {len(hits) / len(relevant):.2f}")
I can't log in to my account -> retrieved [0, 1, 3]
precision@3: 0.67 recall@3: 1.00
When do I get my money back? -> retrieved [1, 3, 4]
precision@3: 0.67 recall@3: 1.00
Here's where the labels moved. Instead of one label per email, each test question gets the set of documents a person marked as relevant. Each question is embedded with a small sentence model (all-MiniLM-L6-v2, about 90 MB, downloaded once), and the three documents with the highest similarity form the net. hits is what's in the net and also relevant.
For the login question, documents 0, 1 and 3 came back. Two of the three are relevant: precision@3 is 0.67. Both relevant documents were caught: recall@3 is 1.00. The money question gets the same numbers.
Notice something: with only two relevant documents, three retrieved can never all be relevant, so precision@3 tops out at two thirds here. Choosing k is part of the ruler. For ranking-aware retrieval metrics like MRR and nDCG on a bigger test set, see Retrieval Evals: Recall@K, MRR and nDCG.
Many right answers
Now the generated answer itself, and this is where things really change. We have a reference answer and two answers written for this lesson. Answer A says the same thing in other words. Answer B is simply wrong.
"""Generation: many right answers. Exact match breaks, a check still works."""
reference = "Refunds reach your card in 5 to 7 working days."
answers = { # two answers written for this lesson
"A": "You will see the money on your card in 5-7 working days.",
"B": "Refunds are instant and show up right away.",
}
def exact_match(answer):
return answer == reference
def has_key_fact(answer): # one rubric item, written as code
return "5" in answer and "7" in answer
for name, text in answers.items():
print(name, "exact match:", exact_match(text),
"| key fact:", has_key_fact(text))
A exact match: False | key fact: True
B exact match: False | key fact: False
Exact match is the old one-label idea: is the answer identical to the reference? The key-fact check asks something smaller: does the answer contain the 5 and the 7?
Exact match fails both answers, the good one and the bad one. The check tells them apart. With text there are many right answers, so one label is no longer enough.
Same ruler, new things to measure
| Classic ML | Retrieval | Generation | |
|---|---|---|---|
| What gets judged | one prediction | the top k documents | a whole written answer |
| What counts as right | one label | a set of relevant documents | many good answers |
| Who labels | a person, per row | a person, per question | a rubric, per answer |
| The ruler | precision, recall | precision@k, recall@k | checks plus a judge |
The questions stay the same. What changes is what counts as right.
The label becomes a rubric
So what replaces the single label for generation? A rubric: "a good answer" broken into small yes-or-no checks.
- Does it have the key fact? A few lines of code can check that, like
has_key_factabove. - Does it only use the documents it was given? And does it answer the question that was asked? Those are hard for code, so a judge model reads the answer and decides. (Writing and validating that judge is covered in LLM-as-Judge.)
- Is it polite and the right length? Code or a judge.
Every check is a yes or no, so you report a pass rate over many test questions. And because each check is a yes or no, precision and recall still apply: to the checks, and even to the judge model itself. How those checks, cases and a threshold fit together into a real eval is in Why You Cannot Ship an LLM Feature Without an Eval.
Common mistakes
- Scoring generated text with exact match. It fails correct paraphrases, so it can't tell a good answer from a bad one.
- Reading precision@k without looking at k. With two relevant documents and k = 3, the best possible precision@3 is 0.67.
- Forgetting who labels. Retrieval metrics need a person to mark the relevant documents for every test question.
- Trusting a judge model blindly. Its yes-or-no decisions need their own precision and recall.
Quick recap
| Target | Ruler | Result here |
|---|---|---|
| A spam label | precision_score, recall_score | 0.75 and 0.75 |
| Retrieved documents | precision@3, recall@3 | 0.67 and 1.00 for both questions |
| A written answer | exact match vs key-fact check | A: False / True; B: False / False |
| Many answers | a rubric of yes-or-no checks | a pass rate |
Try it yourself
- In the retrieval script, set
K = 2and compare precision and recall. - Add a third test question and mark the documents you think are relevant.
- In the generation script, add an answer C with the numbers spelled out in words. What does the check say?
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
A friendlier prompt looked better on three questions and broke on others. An eval catches that: a fixed set of cases, a grader, a pass rate and a threshold. A tiny Python eval scores two prompt versions on the same six questions: v1 passes 83% and ships, v2 passes 50% and is blocked.
Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
The answer key for a support bot: 24 cases in one JSONL file, from 12 past tickets, 8 edge cases and 4 attacks. A Pydantic schema catches 4 problems in a broken file, a stats table finds that payments and account have no hard case, and a seeded split gives the same 16 dev and 8 test cases every time.
Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
When a RAG answer is wrong, check the retriever first. Score two retrievers on 24 graded queries with Recall@5, MRR and nDCG@5: overall there's no clear winner (0.757 vs 0.819, 0.854 vs 0.826, 0.769 vs 0.782), but the paraphrase slice drops to about 0.5 for both, and one query scores zero everywhere.
Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
A teammate changes one prompt line to make answers shorter, and four of ten golden questions lose their facts. A pytest eval on saved answers catches it: 12 passed for the old prompt, 2 failed gates and 4 xfailed cases for the new one, exit code 1, and the pull request check turns red.