BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Optimization challenges13 of 14 in topic

884. Confusion matrix in one pass

EasyOptimization challenges Pro

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.

Functiondef 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).
Topics
Optimization challenges
Similar questions
  • Rolling mean with a cumulative sumEasy
  • Count token frequencies fastEasy
  • Batched softmax without the row loopEasy
  • Padding mask from sequence lengthsEasy
All Optimization challenges problems
Report
884 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
8
import numpy as np
​
def confusion_counts(y_true, y_pred, k):
cm = np.zeros((k, k), dtype=int)
for t, p in zip(np.asarray(y_true, dtype=int), np.asarray(y_pred, dtype=int)):
cm[t, p] += 1
return cm
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS