easy primitives

Confusion Matrix

Implement a Cร—C confusion matrix for multiclass classification.

What is a confusion matrix?

A confusion matrix is a square matrix M of shape (C, C) where C is the number of classes. Entry M[i, j] counts the number of examples whose true label is i and whose predicted class is j.

  • The diagonal (M[i, i]) holds correct predictions for each class.
  • Off-diagonal entries reveal specific misclassification patterns โ€” e.g. M[1, 2] > 0 means the model sometimes predicts class 2 when the true class is 1.

Why it matters

Accuracy collapses all errors into a single number. The confusion matrix lets you diagnose which classes are confused with which, so you can prioritise data collection, adjust class weights, or spot labelling errors.

Step by step

  1. Allocate a (C, C) zero tensor.
  2. Cast predictions and labels to integer indices.
  3. For each example k, increment M[labels[k], predictions[k]] by 1.
  4. Return the matrix.

Reference: sklearn.metrics.confusion_matrix computes the same quantity (with the same row = true, column = predicted convention).

Inputs

  • predictions: shape (N,) โ€” predicted class indices, delivered as floats by the test harness.
  • labels: shape (N,) โ€” true class indices, delivered as floats.
  • num_classes: integer C.

Output

Tensor of shape (C, C) โ€” the confusion matrix.

Hints

metrics classification

Sign in to attempt this problem and view the solution.