154. 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.
Inputs can be Python lists or NumPy arrays, so convert them with np.asarray first.
def confusion(y_true, y_pred, k)A live confusion matrix
Every prediction falls in one of four cells. Move the threshold to see counts shift between them.
| predicted 1 | predicted 0 | |
|---|---|---|
| actual 1 | TP 114 | FN 36 |
| actual 0 | FP 33 | TN 117 |
- precision
- 0.776
- recall
- 0.76
- F1
- 0.768
- MCC
- 0.54
- ROC AUC
- 0.849
Synthetic scores made in your browser: 150 per class, sigmoid of a normal value centred at ±separation / 2. AUC counts every positive and negative pair.
Example 1
Input: confusion([0, 1, 1], [0, 0, 1], 2)
Output: [[1, 0], [1, 1]]
Example 2
Input: y_true = [0, 1, 2, 2, 1], y_pred = [0, 2, 2, 1, 1], k = 3
Output: [[1, 0, 0], [0, 1, 1], [0, 1, 1]]
Example 3
Input: y_true = [0, 0], y_pred = [0, 0], k = 3
Output: [[2, 0, 0], [0, 0, 0], [0, 0, 0]]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
Hint 1
np.add.at(M, (y_true, y_pred), 1) handles repeated pairs correctly.
Hint 2
Rows are truth, columns are predictions.
Hint 3
Use np.add.at, not M[a, b] += 1.
Common mistakes
- Swapping the axes.
- Using
M[y_true, y_pred]+= 1, which drops repeated pairs.
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.
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]].
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.
Topics
Companies1
- Meta a candidate reported this question Timed ML screen: concept questions then classic models from scratch (Land the Lab)
From public interview reports and guides. Not affiliated with or endorsed by these companies.