Build a confusion matrix
Why it matters Guardrail classifiers are judged by which wrong cells grow, not just accuracy.
Every classification report starts with a confusion matrix.
Write confusion(y_true, y_pred, k). Return a (k, k) int array where entry [i, j] counts samples with true class i predicted as class j.
def confusion(y_true, y_pred, k)Example
confusion([0, 1, 1], [0, 0, 1], 2) is [[1, 0], [1, 1]].
Understand the idea
A confusion matrix is a table that counts how often each true class was predicted as each class. The diagonal holds the correct predictions and everything off the diagonal is a specific kind of mistake. Precision, recall and F1 are all read off this one table. Worked example: y_true = [0, 0, 1, 2], y_pred = [0, 1, 1, 1], k = 3. Pair (0, 0) adds 1 to cell [0, 0]. Pair (0, 1) adds 1 to [0, 1]. Pair (1, 1) adds 1 to [1, 1]. Pair (2, 1) adds 1 to [2, 1]. Result: [[1, 1, 0], [0, 1, 0], [0, 1, 0]]. Rule: start from a k by k integer zero matrix, and for every sample add 1 to cell [true, pred]. Rows are true classes and columns are predictions, never the other way round. If you vectorise, use an accumulating add, because plain fancy-index assignment counts repeated pairs only once. Used in: every classification report, error analysis of LLM classifiers, and moderation dashboards that track false positives.