One Confusion Matrix, Four Ways to Read It

Metrics & EvaluationMedium+15 XP+15

One Confusion Matrix, Four Ways to Read It

A confusion matrix lays out exactly which classes a model mixes up. Rows are what the answer really was, columns are what the model said, so the cell at row i, column j counts the examples that truly belonged to class i and were predicted as class j. The diagonal is everything it got right.

Raw counts are hard to read when classes are lopsided, so you often want them as fractions instead.

Task: write confusion_matrix(y_true, y_pred, normalize) returning the matrix, where normalize is one of:

normalizeEach cell becomesReads as
Nonethe raw count, as an integerhow many
"true"count ÷ its row totalof this real class, what fraction went where — i.e. recall on the diagonal
"pred"count ÷ its column totalof everything called this, what fraction was right — i.e. precision on the diagonal
"all"count ÷ the grand totalshare of the whole dataset
  • Class order is the sorted list of every label that appears in y_true or y_pred. A class that only ever gets predicted, and never actually occurs, still earns a row and a column.
  • Round every normalized value to 4 decimal places. With normalize=None, leave the counts as plain integers — no rounding, no floats.
  • If a row or column total is 0, put 0.0 in those cells instead of dividing by zero.

The two middle options are worth dwelling on: the same matrix normalized by row and by column tells you two different stories, and arguments about model quality are usually arguments about which one you're looking at.

Build the Matrix

Sort each prediction into the cell it belongs in.

Actual: Positive · Predicted: Positive
Pred +
Pred −
Actual +
0
0
Actual −
0
0

Examples

y_true = [0, 1, 0, 1]
y_pred = [0, 1, 1, 1]
normalize = None
returns [[1, 1], [0, 2]]
y_true = [0, 1, 0, 1]
y_pred = [0, 1, 1, 1]
normalize = 'true'
returns [[0.5, 0.5], [0.0, 1.0]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run