v9.1.1
Menu

Confusion Matrix Builder

mediumPROImage ClassificationMetricsCV: Recognition

You are given lists of predictions and ground truth labels, and need to build a confusion matrix.

A confusion matrix C is a square matrix where:

  • C[i][j] = count of samples with true class i that were predicted as class j
  • Diagonal entries C[i][i] are correct predictions
  • Off-diagonal entries are misclassifications

The matrix provides detailed insight into which classes are being confused with each other.

For a 3-class problem, the structure is: C=[TP0E0→1E0→2E1→0TP1E1→2E2→0E2→1TP2]C = \begin{bmatrix} TP_0 & E_{0\to1} & E_{0\to2} \\ E_{1\to0} & TP_1 & E_{1\to2} \\ E_{2\to0} & E_{2\to1} & TP_2 \end{bmatrix}

Where TPiTP_i is true positives for class i, and Ei→jE_{i\to j} is errors where class i was predicted as class j.

Example

Input
predictions = [0, 1, 0, 1]
ground_truth = [0, 0, 0, 1]
num_classes = 2
Output
[[2, 1], [0, 1]]
Reasoning
  • Inputs: predictions and ground_truth are read side by side as (true, predicted) pairs, one per sample: (0,0)(0,0), (0,1)(0,1), (0,0)(0,0), (1,1)(1,1). With num_classes =2=2 the matrix is 2×22 \times 2; row ii is the true class, column jj the predicted class.
  • Row 0 (true class 0): samples 0, 1 and 2 are truly class 0. Two were predicted 0 and one was predicted 1, so C00=2C_{00}=2 and C01=1C_{01}=1. The row sums to 3, the number of class-0 samples.
  • Row 1 (true class 1): only sample 3, predicted correctly, so C10=0C_{10}=0 and C11=1C_{11}=1.
  • Output: [[2, 1], [0, 1]]. The diagonal holds 2+1=32+1=3 correct predictions out of 4 (75% accuracy); the single off-diagonal count E0→1=1E_{0\to1}=1 is a class-0 sample mistaken for class 1.
  • Notice: orientation matters. Sample 1 has truth 0 and prediction 1, so it belongs in row 0, column 1; mixing up the roles gives the transpose [2011]\begin{bmatrix}2&0\\1&1\end{bmatrix}. All entries always add up to the number of samples, and a class that never occurs keeps a row of zeros.

Constraints

  • predictions and ground_truth are lists of class indices of the same length
  • num_classes is the total number of classes
  • All class indices are in range [0, num_classes-1]
  • Return the confusion matrix as a 2D list

Learn this in

More from CV: Recognition

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.