InterviewPrepKit

Home / Coding / Machine Learning Coding / Metrics from Scratch / Confusion Matrix

Confusion Matrix

medium 00:00
Solving tips
  • Each (true, pred) pair contributes exactly one +1 to cell [true, pred] — the whole task is counting pairs into a 2-D grid.
  • Reach for np.add.at(M, (y_true, y_pred), 1) or a bincount on flattened indices instead of a Python double loop.
  • Fix the shape at (num_classes, num_classes) up front so classes that never appear still get their zero row and column.

Implement a multiclass confusion matrix from scratch with NumPy, without calling a library metric. The confusion matrix is the foundation for accuracy, precision, recall, and F1, and interviewers use it to check that you can accumulate counts into a fixed-size grid without a slow Python loop.

Definition

Given n samples with integer true labels y_true and predicted labels y_pred, both in [0, num_classes), the confusion matrix M is a (k, k) array where

M[i, j] = number of samples whose true class is i and whose predicted class is j

Rows index the true class, columns index the predicted class. The diagonal M[i, i] counts correct predictions for class i; off-diagonal entries are the specific mistakes.

Task

Complete confusion_matrix(y_true, y_pred, num_classes) so it returns a (k, k) integer NumPy array following the definition above, with k = num_classes. Classes that never appear must still get an all-zero row and column, so the shape depends only on num_classes, not on which labels are present. Do not call sklearn or any built-in confusion-matrix helper.

Example

y_true = np.array([0, 1, 2, 2, 0, 1])
y_pred = np.array([0, 2, 2, 0, 0, 1])
confusion_matrix(y_true, y_pred, num_classes=3)
# -> array([[2, 0, 0],
#           [0, 1, 1],
#           [1, 0, 1]])

Class 0 is predicted correctly both times (M[0, 0] = 2). One class-1 sample is misread as class 2 (M[1, 2] = 1), and one class-2 sample is misread as class 0 (M[2, 0] = 1).

Constraints

  • 1 <= n <= 10^6 and 1 <= num_classes <= 10^3; use vectorized NumPy, not a Python loop over samples.
  • All labels are valid integers in [0, num_classes).

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug