typestar

The confusion matrix in Python

Four counts that explain every classification score you might quote.

from sklearn.metrics import confusion_matrix

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

matrix = confusion_matrix(y_true, y_pred, labels=[0, 1])
print(matrix)

tn, fp, fn, tp = matrix.ravel()
print(f"tn {tn} fp {fp} fn {fn} tp {tp}")
print(f"specificity {tn / (tn + fp):.3f}")

How it works

  1. Rows are the truth, columns the prediction.
  2. ravel unpacks a binary matrix into tn, fp, fn, tp.
  3. labels fixes the order so the matrix is readable.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
303
Tokens
117
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 64 seconds.

Type this snippet

Step 2 of 4 in Scoring, step 17 of 25 in Machine learning with scikit-learn.

← Previous Next →