# Your ticket classifier's errors hide in one cell of the matrix

> Misclassifications tend to pile up between two labels with overlapping meanings, so fix that pair first instead of rewriting the whole prompt.

Original: https://fdetimes.net/en/guides/confusion-matrix-ticket-classification-prompt/

Anthropic's guide to ticket routing sets a target of at least 80% accuracy on a separate set of edge cases. If your prompt scores 72%, though, that number says nothing about which sentence to fix.

Resist the urge to add general instructions or more examples. Open the confusion matrix, find the pair of labels the model mixes up most, read the real tickets in that cell, fix that pair and measure again.

The arXiv paper 2609.01564, published in September 2026, names the problem directly. When two closely related labels are both candidates, the model lacks the signal to choose correctly between them. The authors' method therefore starts by identifying the label pairs the model struggles to tell apart.

## What you will build and what you need

The result is a small Python script. It reads true and predicted labels, prints the confusion matrix as counts and as rates, ranks the confused label pairs, and prints the tickets in any cell you choose. You need Python, scikit-learn, a set of tickets with correct labels, and whatever function you already use to call your LLM.

To keep the numbers consistent throughout, the article uses a made-up example of 200 tickets and four labels: `billing`, `refund`, `technical`, `account`. Every figure below comes from this example, not from any real customer's data.

## Step 1: run the prompt and save the results

First, run the prompt over the whole labeled set and keep the ticket IDs so you can come back and read them later. `classify` is your model-calling function; it is left out of the code below for brevity.

```python
import csv

text_by_id = {t["id"]: t["text"] for t in tickets}

rows = []
for t in tickets:  # each t has id, text, label
    rows.append({"id": t["id"], "true": t["label"],
                 "pred": classify(t["text"])})

with open("run_v1.csv", "w", newline="") as f:
    w = csv.DictWriter(f, fieldnames=["id", "true", "pred"])
    w.writeheader(); w.writerows(rows)
```

Check: the number of rows in the file must equal the number of tickets. The `pred` column may contain only the four labels. If the model returns "Billing." or an unknown label, normalize the string before computing anything, or the matrix will count wrongly.

## Step 2: build the matrix and read it the right way round

According to the scikit-learn documentation, cell C[i, j] is the number of samples known to be in group i but predicted to be in group j. Rows are the truth; columns are the model's judgment. Pass the label list in a fixed order so that runs can be compared with one another.

```python
from sklearn.metrics import confusion_matrix

LABELS = ["billing", "refund", "technical", "account"]
y_true = [r["true"] for r in rows]
y_pred = [r["pred"] for r in rows]

cm = confusion_matrix(y_true, y_pred, labels=LABELS)
print(cm)
```

In the example, the matrix comes out like this:

| True \ Predicted | billing | refund | technical | account |
|---|---|---|---|---|
| billing (60) | 44 | 14 | 1 | 1 |
| refund (30) | 6 | 22 | 0 | 2 |
| technical (80) | 1 | 0 | 76 | 3 |
| account (30) | 0 | 1 | 5 | 24 |

The diagonal sums to 44 + 22 + 76 + 24 = 166, or 83%. That looks fine. But look at the 14: fourteen billing tickets were pushed into refund, and in the other direction six refund tickets were labeled billing. This one pair accounts for 20 of the 34 errors, more than half.

## Step 3: normalize by row when classes are imbalanced

On raw counts, technical looks healthy because it is the largest class. scikit-learn can normalize the matrix over the true labels (rows), the predicted labels (columns) or the whole population. Normalizing by row answers the question you care about most: of the tickets that truly belong to this label, what share was misassigned, and to where?

```python
cm_row = confusion_matrix(y_true, y_pred, labels=LABELS,
                          normalize="true")
print(cm_row.round(3))
```

The result: billing to refund is 14/60 ≈ 23.3%, refund to billing is 6/30 = 20%, account to technical is 5/30 ≈ 16.7%, while technical to account is only 3/80 = 3.75%. The ticket counts are similar, but for a small class such as account, five wrong tickets are far more worrying.

## Step 4: rank the label pairs

The two directions of a pair usually share a cause, because the definitions of the two labels overlap. Combine them and sort.

```python
pairs = []
for i in range(len(LABELS)):
    for j in range(i + 1, len(LABELS)):
        n = cm[i, j] + cm[j, i]
        if n:
            pairs.append((n, LABELS[i], LABELS[j], cm[i, j], cm[j, i]))

for p in sorted(pairs, reverse=True):
    print(p)
```

The first line will be `(20, 'billing', 'refund', 14, 6)`, followed by technical and account with 8 errors. This is your to-do list, and you work through it from the top.

**Key point:** Do not fix the prompt against the overall score; fix it against the label pair the model confuses most.

## Step 5: read the real tickets before writing a word

Hamel Husain, who writes about LLM evals, argues that error analysis is the most important activity in evals. At this step, error analysis is concrete: print the 14 billing tickets labeled as refund and read every one. `text_by_id` is the dictionary built in Step 1.

```python
cell = [r for r in rows
        if r["true"] == "billing" and r["pred"] == "refund"]
for r in cell:
    print(r["id"], text_by_id[r["id"]][:200])
```

As you read, note what they have in common, in the customers' own words. Many tickets may mention "money" or "charged twice" while actually asking about an invoice. You may also find a few tickets that were mislabeled in the first place; if so, fix the labels in the data first, because on those tickets the prompt was right.

## Step 6: fix exactly one pair

From what you read, write a distinguishing rule for the billing and refund pair alone, with two contrasting examples whose wording is nearly identical but whose labels differ.

The arXiv paper mentioned above expands the candidate set to include the easily confused labels once the confused pairs have been found. The practical lesson: put the two labels side by side in the prompt and state clearly where the boundary between them lies.

```text
Distinguishing billing from refund:
- refund: the customer asks for money back on a completed transaction.
- billing: the customer asks about an invoice, a billing cycle or a charge
  without asking for a refund.
Example: "Why was I charged twice this month?" -> billing
Example: "I was charged twice, please refund one of them" -> refund
```

This is a shortened version. The real rule should use the exact phrases you found in Step 5. Fix only one pair per iteration, so that when the numbers move you know what moved them.

## Step 7: rerun and check both directions

Rerun on the same set, save the output as `run_v2.csv` and compare cell by cell. The most common mistake is overcorrection: the billing-to-refund cell drops from 14 to 3, but the refund-to-billing cell rises from 6 to 12.

The pair's total errors then fall only slightly, from 20 to 15, because most of the errors have simply moved to the opposite direction. Check the other cells in the billing and refund rows too, since a new rule can pull in tickets from a third label.

Then re-measure against the targets in Anthropic's ticket-routing guide. The edge-case set should reach at least 80%. When only a title and a short description are available, accuracy should be at least 90%.

For languages other than the primary one, accuracy should not drop by more than 5 to 10%. Each evaluation set deserves its own confusion matrix, because the label pairs confused in Vietnamese tickets may be entirely different from those in English tickets.

## Three mistakes that make the whole exercise pointless

The first is reading the matrix the wrong way round. Swap y_true and y_pred and you will fix the wrong label. The second is letting the label order be generated automatically on each run, so the cells no longer line up across runs.

The third is adding examples taken straight from the test set into the prompt, which makes the next measurement look artificially good. Keep a separate set to draw examples from.

## Using this skill in front of a client

In a review with the client's support team, that four-row matrix is more persuasive than any slide. You can say that more than half the errors sit on the boundary between billing and refund, then ask: how do your own agents tell these two apart?

Their answer often becomes the best rule in your prompt, and it also shows whether the label set needs merging.

If you want to move into an FDE role, run exactly this process on a public ticket dataset and put it in your portfolio: the matrices before and after, with notes on each iteration.

When a job posting mentions "evals" or "error analysis", those matrices and notes let a recruiter see for themselves that you can do the work: you found which cell the errors lived in and how you fixed them.

The overall score only tells you where you stand against the target. The individual cells tell you what to write into the next version of the prompt.

**Try this week:**

- Take about 200 labeled tickets, run your current prompt and save y_true and y_pred with the ticket IDs to a CSV file
- Print the row-normalized matrix, pick the label pair with the largest combined errors in both directions and read every ticket in that cell
- Write one distinguishing rule with two contrasting examples for that pair, rerun, and record the before and after numbers in a small table

## Sources

- [sklearn.metrics.confusion_matrix](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html)

- [Ticket routing (Claude Platform Docs)](https://platform.claude.com/docs/en/about-claude/use-case-guides/ticket-routing)

- [From Confusion to Clarity: Confusion-Aware Retrieval and Knowledge Injection for Text Classification (arXiv 2609.01564)](https://arxiv.org/abs/2609.01564)

- [Hamel Husain – Evals FAQ](https://hamel.dev/blog/posts/evals-faq/)
