PIXELBANKv9.1.0
Menu

Confusion Matrix Builder

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:

For each sample, increment C[true][predicted]:

  1. Sample 0: true=0, pred=0 β†’ C[0][0]++ β†’ [[1,0],[0,0]]
  2. Sample 1: true=0, pred=1 β†’ C[0][1]++ β†’ [[1,1],[0,0]]
  3. Sample 2: true=0, pred=0 β†’ C[0][0]++ β†’ [[2,1],[0,0]]
  4. Sample 3: true=1, pred=1 β†’ C[1][1]++ β†’ [[2,1],[0,1]]

Reading the matrix:

  • C[0][0]=2: 2 samples of class 0 correctly predicted
  • C[0][1]=1: 1 sample of class 0 wrongly predicted as class 1
  • C[1][1]=1: 1 sample of class 1 correctly predicted

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
πŸ”’

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

0/0
Run code to see test results.