Build a classification error ledger with actual rows, predicted columns, fixed labels and visible support for every class.
Confusion matrices: fix class order, denominators and abstentions
Make axes a written contract
A confusion matrix is a count ledger, not merely a colored square. Fix the class vocabulary and its order before comparing model versions. This lesson puts actual class on each row and predicted class on each column. A cell at row Delivery, column Returns therefore means a real Delivery ticket routed to Returns. Swapping axes changes the question while leaving a superficially similar image. Use the same class keys in tables, hover text, screen-reader descriptions and any export. Heatmap color scales should make count ranges readable, but numerical labels must remain available. On a sparse matrix, zero means no observed cases; it does not prove an error is impossible.
Keep counts and row rates together
Raw counts show workload. Row-normalized values divide each cell by the number of actual cases in its row, making recall-like class comparisons possible. Column normalization divides by the number predicted as that class, answering a precision-like question. Whole-matrix normalization divides by all cases and answers a third question. Never label all three simply 'accuracy.' Print row totals and column totals so readers can audit the denominators. A model that gets 9,400 common cases right and misses 47 rare cases can have impressive overall accuracy but fail the rare-class task. Denominator design and precision–recall analysis provide the neighboring view for rare binary outcomes. If a class has zero actual cases, its row rate is undefined, not zero.
Treat abstention and missing truth separately
Some classifiers can decline to assign a class. Represent abstain as a predicted column and report coverage, the share of eligible records receiving a concrete prediction. Do not drop abstentions before calculating performance unless a separate coverage-conditioned table is clearly labeled. Missing ground truth is different: those records cannot enter a verified confusion matrix at all, and their count should be disclosed alongside the eligible population. In a human-review workflow, only the reviewed cases may have labels, creating selection bias. A matrix built from those cases is not automatically representative of all incoming work. Linked filters should make this labeled-cohort restriction visible at all times.
Compare the errors that matter
The diagonal marks correct classifications; off-diagonal cells identify which mistakes occur. A stable class order and shared color domain let readers compare model versions without relearning the image. Sort classes by a documented domain order, not by each version's frequency. When there are dozens of labels, show a targeted subset or a table rather than shrinking every cell until it is unreadable. Report cost-relevant pairs explicitly: sending a fraud report to routine support may be more expensive than confusing two routine categories. Small multiples help comparisons, while text alternatives carry exact counts where color alone cannot. The matrix describes a fixed decision rule; a threshold sweep needs a separate ROC or precision–recall view.
Worked contract
def classification_ledger(records: list[tuple[str, str, str]],
classes: list[str]):
if (not classes or "Abstain" in classes or
len(classes) != len(set(classes)) or any(not item for item in classes)):
raise ValueError("class labels must be unique and nonempty")
identifiers = [ticket_id for ticket_id, _, _ in records]
if len(identifiers) != len(set(identifiers)) or any(not key for key in identifiers):
raise ValueError("ticket IDs must be unique and nonempty")
actual_positions = {name: index for index, name in enumerate(classes)}
predicted_positions = {name: index for index, name in
enumerate(classes + ["Abstain"])}
counts = [[0 for _ in predicted_positions] for _ in classes]
for _, actual, predicted in records:
if actual not in actual_positions or predicted not in predicted_positions:
raise ValueError("unknown actual or predicted class")
counts[actual_positions[actual]][predicted_positions[predicted]] += 1
row_rates = []
for row in counts:
support = sum(row)
row_rates.append([value / support for value in row] if support else None)
assert sum(map(sum, counts)) == len(records)
return counts, row_rates
ticket_routes = [("ticket-47", "Billing", "Billing"),
("ticket-59", "Billing", "Delivery"),
("ticket-83", "Delivery", "Delivery"),
("ticket-97", "Delivery", "Returns"),
("ticket-101", "Returns", "Returns"),
("ticket-131", "Returns", "Billing")]
labels = ["Billing", "Delivery", "Returns", "Technical"]
counts, row_rates = classification_ledger(ticket_routes, labels)
assert counts[0][:3] == [1, 1, 0]
assert row_rates[0][:3] == [0.5, 0.5, 0.0]
assert row_rates[3] is None
assert sum(counts[index][index] for index in range(4)) == 3Performance and operating cost
For N records and K actual classes, ledger construction takes O(N + K²) time and O(N + K²) space: the unique-ID set stores N keys and each dense matrix has K rows and K+1 predicted columns, including Abstain. A sparse map can avoid empty cells when K is large. The code rejects an unknown actual or predicted label; missing actual labels require a separate exclusion ledger. The six-ticket assertion checks axis direction, row normalization and an undefined zero-support row, not model quality.
Common Mistakes
- Flipping actual and predicted axes between dashboards.
- Displaying row-normalized color without support counts.
- Reporting an empty actual-class row as zero recall.
- Discarding abstentions or unreviewed cases without changing the cohort label.
Validation drill
Audit 470 routed tickets across four service classes. Reconcile row and column totals, add an Abstain predicted column, and explain how coverage and per-class recall change between two model versions.
