Confusion Matrix in Python with scikit-learn
See exactly which mistakes a classifier makes: read TP, FP, FN and TN, then precision, recall and the classification report.
- confusion_matrix and its layout
- Unpacking tn, fp, fn, tp
- Precision, recall and classification_report
Counting right and wrong answers
The problem
A spam filter that is 75% accurate can be useless or fine, depending on its mistakes. Letting spam through and deleting real mail are very different errors, and accuracy hides which one happens.
Think of it like this
A confusion matrix is like a referee's scorecard with four boxes: goals correctly allowed, goals correctly refused, goals wrongly refused and fouls wrongly allowed. You can see not only how often the referee was right, but how they were wrong.
TP = 4✅ Spam caughtTN = 5📬 Real mail deliveredFP = 2🚫 Real mail sent to spamFN = 1📨 Spam that got throughA confusion matrix is a table that counts the samples of each actual class (rows) by the class the model predicted (columns).
Key points
- For two classes,
confusion_matrix(...).ravel()givestn, fp, fn, tpin that order. - Precision = TP / (TP + FP) = 0.67: a third of the spam alerts were wrong.
- Recall = TP / (TP + FN) = 0.80: 80% of the spam was caught.
classification_reportshows precision, recall and F1 for every class.
When should you use it?
- Evaluating any classifier beyond accuracy.
- Imbalanced problems such as fraud or disease detection.
- Choosing between models that make different kinds of mistakes.
When not to use it
- Regression models that predict numbers: use MAE or R^2.
- Many classes: the table gets big; start with the classification report.
Example code
from sklearn.metrics import classification_report, confusion_matrix
# 1 = spam, 0 = not spam
y_true = [1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0]
y_pred = [1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1]
cm = confusion_matrix(y_true, y_pred)
print("Confusion matrix (rows = actual, columns = predicted):")
print(cm)
tn, fp, fn, tp = cm.ravel().tolist()
print(f"TN={tn} FP={fp} FN={fn} TP={tp}")
print(f"Precision = TP / (TP + FP) = {tp / (tp + fp):.2f}")
print(f"Recall = TP / (TP + FN) = {tp / (tp + fn):.2f}")
print(classification_report(y_true, y_pred, target_names=["not spam", "spam"]))
Result of running the code
Confusion matrix (rows = actual, columns = predicted):
[[5 2]
[1 4]]
TN=5 FP=2 FN=1 TP=4
Precision = TP / (TP + FP) = 0.67
Recall = TP / (TP + FN) = 0.80
precision recall f1-score support
not spam 0.83 0.71 0.77 7
spam 0.67 0.80 0.73 5
accuracy 0.75 12
macro avg 0.75 0.76 0.75 12
weighted avg 0.76 0.75 0.75 12
Code explanation
confusion_matrix puts actual classes in rows and predicted classes in columns, with class 0 first. So the top row says 5 real non-spam messages were kept (TN) and 2 were flagged as spam (FP), and the bottom row says 1 spam got through (FN) and 4 were caught (TP). cm.ravel() unpacks the four numbers in the order tn, fp, fn, tp. Precision 0.67 means a third of the spam alerts were wrong; recall 0.80 means 80% of the spam was caught. classification_report prints the same figures for both classes plus the overall accuracy of 0.75.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change random_state and see how much the score moves.
- Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
- Try a different model or hyperparameter and compare the scores.
Common mistakes
Trusting accuracy on imbalanced data
A model that always predicts the majority class can score 95% and catch nothing.
print(accuracy_score(y_true, y_pred)) # only
print(classification_report(y_true, y_pred))
Swapping the arguments
The true labels come first; swapping them transposes the matrix.
confusion_matrix(y_pred, y_true)
confusion_matrix(y_true, y_pred)
Finished this lesson?
Mark it as learned to track your progress.
Tools for this lesson
- Classification Basics: Softmax and k-Nearest Neighbors in PythonTurn scores into class probabilities with softmax, score them with cross-entropy and classify points with k-nearest neighbors.
- Jupyter Notebook Online: Run Python Cells in Your BrowserFree online Jupyter notebook: run Python cells with pandas, NumPy and Matplotlib, add Markdown text, open and download .ipynb files. No install, no account.
- pandas Online Compiler: Run pandas and NumPy in Your BrowserRun pandas and NumPy code online with nothing to install. NumPy, pandas, SciPy, Matplotlib and scikit-learn are ready in the free Python editor.