Implement a Multi-Class Confusion Matrix and F1 Scores in NumPy

Quick Overview

Implement a multi-class confusion matrix in NumPy and compute per-class precision, recall and F1 along with macro and micro F1. Tests label handling, matrix orientation, safe division for classes with no predictions or no samples, and how the two averages differ.

Implement a Multi-Class Confusion Matrix and F1 Scores in NumPy

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement two NumPy functions for single-label multi-class classification. - `confusion_matrix(y_true, y_pred, labels=None)` returns an N x N `np.int64` matrix. Rows are true labels and columns are predicted labels. - `multiclass_metrics(y_true, y_pred, labels=None)` returns a dict with keys `labels`, `confusion_matrix`, `precision`, `recall`, `f1` (per-class `float64` arrays in label order), and `macro_f1`, `micro_f1` (Python floats). For example: ```python y_true = [0, 0, 1, 1, 2, 2] y_pred = [0, 1, 1, 1, 0, 0] confusion_matrix -> [[1, 1, 0], [0, 2, 0], [2, 0, 0]] precision -> [1/3, 2/3, 0.0] recall -> [0.5, 1.0, 0.0] f1 -> [0.4, 0.8, 0.0] macro_f1 -> 0.4 micro_f1 -> 0.5 ``` ```hint Where the counts live Once the matrix exists, every per-class count you need is on its diagonal or in its row and column sums. ``` ```hint Empty classes Class 2 in the example is never predicted. Check what each of your divisions does for that class before you average anything. ``` ### Constraints & Assumptions - When `labels` is `None`, use the sorted unique union of `y_true` and `y_pred` (ints or strings). When `labels` is given, keep that order and skip any sample whose true or predicted label is not listed. - Inputs with mismatched shapes raise `ValueError`. - F1 is `2TP / (2TP + FP + FN)`. Any zero denominator yields 0.0, never `NaN`. - `macro_f1` averages over all labels, including labels with no samples. `micro_f1` uses the summed TP, FP and FN. - Empty input returns a `(0, 0)` matrix and 0.0 for both averages. - Only `numpy` is allowed. `sklearn` is used only by the tests. ### What a Strong Answer Covers - Label resolution in both modes: sorted union when `labels` is `None`, the given order otherwise, and dropping samples with unlisted labels - The matrix orientation and how TP, FP and FN per class come from the diagonal and the margins - Division that returns 0.0 on a zero denominator for precision, recall, per-class F1 and micro F1 - How macro and micro averaging differ, and how labels with no samples affect macro F1 - Edge cases and types: empty input, mismatched shapes, `int64` matrix, `float64` arrays and Python float averages ### Follow-up Questions - Why does `micro_f1` equal accuracy in the example, and when would it not? - How would you build the matrix for millions of samples without a Python loop? - How would you add a support-weighted F1? - What changes for multilabel data, where a sample can have several true labels or none?

Overview: Implement a multi-class confusion matrix in NumPy and compute per-class precision, recall and F1 along with macro and micro F1. Tests label handling, matrix orientation, safe division for classes with no predictions or no samples, and how the two averages differ.

General logo
General
Nov 24, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement two NumPy functions for single-label multi-class classification.

  • confusion_matrix(y_true, y_pred, labels=None) returns an N x N np.int64 matrix. Rows are true labels and columns are predicted labels.
  • multiclass_metrics(y_true, y_pred, labels=None) returns a dict with keys labels , confusion_matrix , precision , recall , f1 (per-class float64 arrays in label order), and macro_f1 , micro_f1 (Python floats).

For example:

y_true = [0, 0, 1, 1, 2, 2]
y_pred = [0, 1, 1, 1, 0, 0]

confusion_matrix -> [[1, 1, 0], [0, 2, 0], [2, 0, 0]]
precision -> [1/3, 2/3, 0.0]
recall    -> [0.5, 1.0, 0.0]
f1        -> [0.4, 0.8, 0.0]
macro_f1  -> 0.4
micro_f1  -> 0.5

Constraints & Assumptions

  • When labels is None , use the sorted unique union of y_true and y_pred (ints or strings). When labels is given, keep that order and skip any sample whose true or predicted label is not listed.
  • Inputs with mismatched shapes raise ValueError .
  • F1 is 2TP / (2TP + FP + FN) . Any zero denominator yields 0.0, never NaN .
  • macro_f1 averages over all labels, including labels with no samples. micro_f1 uses the summed TP, FP and FN.
  • Empty input returns a (0, 0) matrix and 0.0 for both averages.
  • Only numpy is allowed. sklearn is used only by the tests.

What a Strong Answer Covers Guidance

  • Label resolution in both modes: sorted union when labels is None , the given order otherwise, and dropping samples with unlisted labels
  • The matrix orientation and how TP, FP and FN per class come from the diagonal and the margins
  • Division that returns 0.0 on a zero denominator for precision, recall, per-class F1 and micro F1
  • How macro and micro averaging differ, and how labels with no samples affect macro F1
  • Edge cases and types: empty input, mismatched shapes, int64 matrix, float64 arrays and Python float averages

Follow-up Questions Guidance

  • Why does micro_f1 equal accuracy in the example, and when would it not?
  • How would you build the matrix for millions of samples without a Python loop?
  • How would you add a support-weighted F1?
  • What changes for multilabel data, where a sample can have several true labels or none?