884. Confusion matrix in one pass
Why it matters Confusion matrices are the base of precision, recall and per-class error analysis on large eval sets.
confusion_counts(y_true, y_pred, k) returns the k x k confusion matrix: cm[i, j] is the number of examples with true class i and predicted class j.
Inputs: y_true and y_pred are lists or ndarrays of ints in [0, k) with the same length (can be empty). k is an int >= 1.
Return an ndarray of ints with shape (k, k).
The starter is a correct but slow Python loop. Make it fast. The small tests check correctness. The last test runs your function on a large input and reports "fast enough" only if the call takes at most 30 times as long as a fixed 200,000-step pure Python loop on the same device. The test times both with time.perf_counter (input generation included), so the limit scales with your device and browser, and a call that is just over the limit is measured once more. Vectorised NumPy finishes far below the limit; the starter loop takes several times longer.
def confusion_counts(y_true, y_pred, k)Example 1
Input: confusion_counts([0, 1, 1, 2], [0, 2, 1, 2], 3)
Output: [[1, 0, 0], [0, 1, 1], [0, 0, 1]]
Example 2
Input: y_true = [], y_pred = [], k = 2
Output: [[0, 0], [0, 0]]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Turn each pair into a single index t * k + p.
Hint 2
np.bincount with minlength=k * k.
Hint 3
Reshape to (k, k).
Common mistakes
cm[t, p]+= 1 with fancy indexing, which does not accumulate duplicates.- Swapping rows and columns.
- Forgetting minlength, which breaks the reshape.
Understand the idea
Encode each (true, pred) pair as one integer t * k + p, count those integers with np.bincount, and reshape to (k, k). One C-level pass replaces 3 million Python iterations. np.add.at(cm, (t, p), 1) also works and reads more directly, but is slower.
Shapes and data flow
y_true, y_pred: (n,). codes: (n,). Output: (k, k).