Neural Mastery
← Practice
NumPy Vectorized Confusion Matrixeasy

NumPy Vectorized Confusion Matrix

easy NumPy & Data Wrangling 10–15 min

NumPy allowed · plain Python earns 10 bonus points

Linear algebra step 1/4

A vector transforms

Matrix multiplication is the first computation behind every model.
Open lesson →
01vector
02matrix
03transform
04result
[2, −1] × [[1, 2], [−.5, 1]] = [0, −2]

Computed matrix × vector transformation

Construct a multi-class confusion matrix from ground-truth and predicted labels using vectorized NumPy operations.

Task

Implement vectorized_confusion_matrix(y_true, y_pred, num_classes). For labels in $0 \dots C-1$, generate the $C \times C$ contingency table where row $i$ is the actual class and column $j$ is the predicted class. Return a 2D list of integers.

Function Signature

vectorized_confusion_matrix(y_true: list[int], y_pred: list[int], num_classes: int) -> list[list[int]]

Examples

Example 1: Binary Classification Balanced
Input: y_true = [0, 1, 0, 1, 0, 1] y_pred = [0, 1, 1, 1, 0, 0] num_classes = 2
Output: [[2, 1], [1, 2]]
Example 2: 3-Class Perfect Diagonal
Input: y_true = [0, 1, 2, 0, 1, 2] y_pred = [0, 1, 2, 0, 1, 2] num_classes = 3
Output: [[2, 0, 0], [0, 2, 0], [0, 0, 2]]
Example 3: All Predictions Class 0
Input: y_true = [0, 1, 2] y_pred = [0, 0, 0] num_classes = 3
Output: [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

Constraints

  • y_true and y_pred are lists of integers in range [0, num_classes - 1].
  • num_classes is an integer > 0.
  • Returns a (num_classes x num_classes) 2D list of integers.
Python3Saved ✓
import numpy as np

def vectorized_confusion_matrix(y_true: list[int], y_pred: list[int], num_classes: int) -> list[list[int]]:
"""Construct a (num_classes, num_classes) confusion matrix using vectorized NumPy.
matrix[i][j] is the count of samples with true class i and predicted class j.
If inputs are empty or mismatch, return zero matrix of shape (num_classes, num_classes)."""
# Your implementation here
pass

Case 1: Binary Classification Balanced
Input: y_true = [0, 1, 0, 1, 0, 1] y_pred = [0, 1, 1, 1, 0, 0] num_classes = 2
Expected: [[2, 1], [1, 2]]
Case 2: 3-Class Perfect Diagonal
Input: y_true = [0, 1, 2, 0, 1, 2] y_pred = [0, 1, 2, 0, 1, 2] num_classes = 3
Expected: [[2, 0, 0], [0, 2, 0], [0, 0, 2]]
Case 3: All Predictions Class 0
Input: y_true = [0, 1, 2] y_pred = [0, 0, 0] num_classes = 3
Expected: [[1, 0, 0], [1, 0, 0], [1, 0, 0]]