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:
Where is true positives for class i, and is errors where class i was predicted as class j.
Example
predictions = [0, 1, 0, 1] ground_truth = [0, 0, 0, 1] num_classes = 2
[[2, 1], [0, 1]]
- Inputs:
predictionsandground_truthare read side by side as (true, predicted) pairs, one per sample: , , , . Withnum_classesthe matrix is ; row is the true class, column 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 and . The row sums to 3, the number of class-0 samples.
- Row 1 (true class 1): only sample 3, predicted correctly, so and .
- Output:
[[2, 1], [0, 1]]. The diagonal holds correct predictions out of 4 (75% accuracy); the single off-diagonal count 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 . 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