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
- Rows are the truth, columns the prediction.
ravelunpacks a binary matrix into tn, fp, fn, tp.labelsfixes the order so the matrix is readable.
Keywords and builtins used here
print
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.
Step 2 of 4 in Scoring, step 17 of 25 in Machine learning with scikit-learn.