# How Do You Evaluate an LLM Classifier With a Confusion Matrix?

> How to score an LLM that sorts text into labels: the confusion matrix, recall per label, and why accuracy alone misleads, for your AI interview.

**In short:** Run the classifier on a set of texts that people have already labelled, and put the results in a confusion matrix. Then score each label on its own, because one costly mix-up can hide behind a good overall accuracy.

AI and LLM interview question Q278, Evaluation and observability. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/how-do-you-evaluate-an-llm-classifier-confusion-matrix

## Say it in 30 seconds

I start with a set of tickets that people have already labelled, run the classifier on every one, and count the results in a confusion matrix. Then I read each label on its own: how many real cases it caught, and how many of its flags were right. Overall accuracy can look fine while one costly label fails, so I never report accuracy alone. Invalid answers count as wrong.

## Say it in 2 minutes

A classifier is only as good as its test. I start with a set of texts where a person already chose the right label, called the gold set. I run the model on every text and put the results in a confusion matrix. In my example the rows are the true labels and the columns are the model's answers, and the diagonal holds the right calls.

Then I score each label on its own. Recall asks how many real cases of a label the model caught. Precision asks how many of its flags were right. Overall accuracy is one number, and it can look fine while one costly label fails. In my example a support router gets 86.8 percent of tickets right, yet only 70 of 100 real fraud tickets reach the fraud queue, and 18 land in billing. So I report the fraud row on its own.

With an LLM there are three extra jobs. First, normalise the reply: trim spaces, match the case, and map it to the label list. Second, keep anything that is not a label in an invalid column, and count it as wrong. Third, run the set more than once or pin the settings, because the same text can sometimes come back with a different label. The test set should also come from real traffic, so its label mix matches production.

Last, I agree the target for each label before the test, not after it.

## What is evaluating a classifier, in plain words?

An LLM classifier reads a piece of text and picks one label from a fixed list, such as fraud, billing, technical or other. To know whether it works, you need texts where a person already chose the right label. Then you compare the model's pick with the person's.

Think about a claims clerk at an insurer who sorts incoming claims into pay, review or reject. Her manager checks 200 of her decisions and writes down each wrong call, not only a count. A confusion matrix is that notebook, drawn as a table. Our real case is a bank's support assistant, which routes each customer message to one of four queues.

- **Label:** One of the fixed choices, such as fraud or billing.
- **Gold set:** Texts with a label a person chose. It is the answer key.
- **Confusion matrix:** A table that counts each pair of true label and model answer. Tools differ on which axis holds the true label.
- **Invalid answer:** A reply that is not one of the labels, such as a sentence or a blank.
- **Recall:** Of the real cases of one label, the share the model caught.

## How do you read a confusion matrix?

Each row is the label a person chose. Each column is what the model answered. So a count in the fraud row and the billing column means one real fraud ticket that the model sent to billing. The diagonal, from top left, holds the right calls.

Tools do not all print it the same way. scikit-learn, the Python machine learning library, puts the true labels in the rows. Google's course lays the table out the other way round. So check which way a tool prints before you read any table.

> "if you lay out the ground truth as columns and the model's prediction as rows" (Google, Machine Learning Crash Course)

## Which numbers do you read from the matrix?

Score each label from its own row and column. Here are the three numbers, worked from the made-up matrix below.

1. **Recall: the row:** Divide the diagonal cell by the row total. Of 100 real fraud tickets, 70 went to fraud, so fraud recall is 70.0 percent.
2. **Precision: the column:** Divide the diagonal cell by the column total. The model flagged 82 tickets as fraud, and 70 were real, so fraud precision is 85.4 percent.
3. **Accuracy: the whole table:** Add the diagonal and divide by all tickets. 868 of 1,000 were right, so accuracy is 86.8 percent. Invalid answers count as wrong.

The matrix below is printed by a short Python script. It uses only the standard library, so you can run it anywhere.

```python
# A bank's support assistant sorts 1,000 tickets (made-up numbers) into four queues.
# Rows: the human label. Columns: what the model answered. "invalid" = not one of the four labels.
ROWS = {
    "fraud": [70, 18, 4, 6, 2],
    "billing": [9, 350, 20, 18, 3],
    "technical": [1, 12, 270, 15, 2],
    "other": [2, 10, 8, 178, 2],
}
names = ["fraud", "billing", "technical", "other", "invalid"]
print(f"{'actual':<10}" + "".join(f"{name:>10}" for name in names))
for label, row in ROWS.items():
    print(f"{label:<10}" + "".join(f"{n:>10}" for n in row))
total = sum(sum(row) for row in ROWS.values())
correct = sum(row[i] for i, row in enumerate(ROWS.values()))
print(f"tickets {total}, correct {correct}, accuracy {correct / total:.1%}")
print(f"invalid answers {sum(row[4] for row in ROWS.values())}, all counted as wrong")
recalls = []
for i, (label, row) in enumerate(ROWS.items()):
    predicted = sum(r[i] for r in ROWS.values())
    recalls.append(row[i] / sum(row))
    print(f"{label:<10} recall {row[i] / sum(row):.1%}  precision {row[i] / predicted:.1%}")
print(f"fraud sent to billing: {ROWS['fraud'][1]} of {sum(ROWS['fraud'][:5])}")
print(f"macro recall {sum(recalls) / len(recalls):.1%}")
```

Output:

```text
actual         fraud   billing technical     other   invalid
fraud             70        18         4         6         2
billing            9       350        20        18         3
technical          1        12       270        15         2
other              2        10         8       178         2
tickets 1000, correct 868, accuracy 86.8%
invalid answers 9, all counted as wrong
fraud      recall 70.0%  precision 85.4%
billing    recall 87.5%  precision 89.7%
technical  recall 90.0%  precision 89.4%
other      recall 89.0%  precision 82.0%
fraud sent to billing: 18 of 100
macro recall 84.1%
```

## Why is overall accuracy not enough?

Overall accuracy is 86.8 percent, which sounds fine. The fraud row is the problem. 18 fraud tickets went to billing. In this made-up bank, a fraud ticket left in billing means a possible stolen card waits longer to be blocked. The per-label numbers show it, and the total hides it.

*Diagram, Where the tickets land, fraud first: The 100 real fraud tickets and the 102 non-fraud tickets that went wrong, from the made-up 1,000-ticket matrix. The 798 right non-fraud calls are left out to keep the picture small. The 18 fraud tickets sent to billing sit inside a good overall score, so that box is read first.*
1. Each test ticket goes in once, with its human label kept aside.
2. 70 real fraud tickets are routed to fraud, the right call.
3. 18 real fraud tickets land in billing, the costly miss.
4. 12 real fraud tickets go to technical, other or invalid.
5. 12 not-fraud tickets are flagged as fraud, a wrong flag.
6. 90 not-fraud tickets go to a wrong queue or get no label.
7. The billing miss is the first fix, since it costs most.

Google's course gives the extreme case. A model can look right on most of the data and still be useless for the rare class.

> "For heavily imbalanced datasets, where one class appears very rarely, say 1% of the time, a model that predicts negative 100% of the time would score 99% on accuracy, despite being useless." (Google, Machine Learning Crash Course)
>
> "The balanced_accuracy_score function computes the balanced accuracy, which avoids inflated performance estimates on imbalanced datasets." (scikit-learn, model evaluation)

Balanced accuracy averages the recall of each label, so a rare label counts as much as a common one. Google also says the usual metric changes when one kind of mistake costs more, which is most real applications.

## What changes when the classifier is an LLM?

- **Normalise the reply first:** The model may answer Fraud. with a full stop, or in a different case. Trim it and match it to the label list before scoring. Anthropic's testing guide describes exact match checks, which typically normalise whitespace and case.
- **Never drop the odd answers:** A reply that is not a label goes in its own invalid column, and counts as wrong. In the example, 9 of 1,000 were invalid. Dropping them would have lifted accuracy and hidden the problem.
- **Run it more than once:** The same text can sometimes come back with a different label on another run. Run the set two or three times, or pin the settings to cut the variation, write them down, and report the spread that is left.
- **There is no threshold to move:** A plain label has no score cut-off you can slide. Your levers are the label definitions and the prompt. A cut-off exists only if your setup gives a confidence score, and then you tune it on the gold set. This depends on the setup.
- **Match the real label mix:** In the example, fraud is 100 of 1,000 tickets, so the gold set keeps that share. A set with half fraud would change the precision and accuracy numbers, so they would no longer match what users see.

### How would you set this up for the support router?

OpenAI's eval guide uses a ticket classifier as its example, and checks each output against the human label with a string grader. The same set-up works for any labelled set.

1. **Build the gold set:** Draw 1,000 tickets from last month's real traffic. Two people label each one, and a third settles the disagreements.
2. **Write the label list down:** Put each label and what counts as it in one place. Vague labels make the matrix hard to read.
3. **Run and normalise:** Run the router on every ticket, trim and match each reply, and send anything else to the invalid column.
4. **Check the matrix adds up:** Each row total should match the human counts in the gold set. Only then trust the numbers.
5. **Agree a target per label:** Before the test, set one for each label. For example, fraud recall of at least 95 percent, with a named owner for the misses.
6. **Gate the release:** The release goes ahead only if every label clears its target. A good overall accuracy alone does not pass.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A confusion matrix: true labels against the model's answers.
- [ ] Recall and precision for each label, not only accuracy.
- [ ] Invalid answers kept in their own column and counted as wrong.
- [ ] Normalising the reply before it is scored.
- [ ] Repeated runs, and a gold set with the real label mix.
- [ ] A target per label, agreed before the test.

**Common traps**

- Trap: "The accuracy is 87 percent, so it works." Better: Check each label. One costly row can hide behind a good total.
- Trap: "Invalid replies can just be dropped." Better: Dropping them flatters the score. Count them as wrong and report how many there were.
- Trap: "A matrix only works for classic models." Better: It works for any labelled answers. An LLM just needs normalising and an invalid column.

## Can you spot the costly line?

**Spot the costly line:** Which line in a support router's report should worry you most?

A. Overall accuracy: 91 percent, 910 of 1,000 right.
B. Fraud row: 25 of 100 real fraud tickets went to billing.
C. Technical recall: 94 percent, a strong result.
D. Invalid answers: 4 of 1,000, all counted as wrong.

**Answer:** B. A fraud ticket left in billing is the costly miss, and the 91 percent total hides it. Read the fraud row first. The other three lines are fine on their own.

**Quick check:** A model replies 'Sure, this looks like a fraud case to me.' How should the score count it?

A. As a correct fraud call
B. As an invalid answer, which counts as wrong
C. Drop it from the test set
D. As a billing call

**Answer:** B. The reply is not one of the labels, even after normalising. It stays in the invalid column and counts as wrong, so the score is honest.

## Can you answer these from memory?

**Flash cards**

- **What is a confusion matrix?** A table of true labels against the model's answers, one count per pair.
- **Recall or precision for fraud?** Recall: of real fraud, how much was caught. Precision: of the fraud flags, how many were right.
- **Why is accuracy not enough?** One costly label can fail while the overall total stays high.
- **Where does an invalid answer go?** Its own column, counted as wrong. Never dropped.
- **Which way round are the rows?** scikit-learn puts the true label in rows. Google's course puts it in columns. Check each tool.
- **What makes the gold set fair?** Real traffic, human labels, and the same label mix as production.

## Likely follow-up questions

- Q420 Precision, recall and F1? https://designervenkat.online/interview/ai/precision-recall-and-f1
- Q425 How do you handle class imbalance? (full answer coming)
- Q253 Exact match, accuracy and F1 for LLM tasks? https://designervenkat.online/interview/ai/exact-match-accuracy-and-f1-for-llm-tasks
- Q268 How many eval examples are enough? https://designervenkat.online/interview/ai/how-many-eval-examples-are-enough
- Q270 Code vs model vs human graders? https://designervenkat.online/interview/ai/code-vs-model-vs-human-graders
- Q279 Statistical significance in evals? (full answer coming)

## Learn it in depth

- [Confusion matrix: the table behind scores](https://designervenkat.online/learn/machine-learning/confusion-matrix)
- [Deterministic Evals](https://designervenkat.online/learn/ai-engineering/deterministic-evals)
- [LLM Evaluations](https://designervenkat.online/learn/ai-engineering/llm-evaluations)
