Machine Learning with scikit-learn

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.

  • Intermédiaire
  • 2 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • confusion_matrix and its layout
  • Unpacking tn, fp, fn, tp
  • Precision, recall and classification_report
rows = actual, columns = predicted
TN 5
FP 2
FN 1
TP 4

Counting right and wrong answers

Découvrez Confusion Matrix in Python with scikit-learn avec un exemple pratique modifiable et exécutable en ligne.

Points clés

  1. For two classes, confusion_matrix(...).ravel() gives tn, fp, fn, tp in that order.
  2. Precision = TP / (TP + FP) = 0.67: a third of the spam alerts were wrong.
  3. Recall = TP / (TP + FN) = 0.80: 80% of the spam was caught.
  4. classification_report shows precision, recall and F1 for every class.

Quand l’utiliser ?

  • Train and evaluate classic machine learning models on tabular data.
  • Prepare features: split, scale and encode data the way real projects do.
  • Compare models fairly with cross-validation and the right metric.

Code d’exemple

main.py
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"]))
Obtenir un bouton Run pour cet exemple

Résultat de l’exécution

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

Explication du code

Cet exemple montre Confusion Matrix in Python with scikit-learn en pratique. Modifiez les valeurs d’entrée et relancez le code pour voir ce qui change.

Modifiez les valeurs et exécutez le programme avec le compilateur Python en ligne CodeUtility, sans installation locale.

Exercices d’approfondissement

Essayez de modifier le code en suivant les pistes ci-dessous. Changer le code et observer le résultat vous fera bien mieux comprendre la leçon que la simple lecture.

  1. Change random_state and see how much the score moves.
  2. Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
  3. Try a different model or hyperparameter and compare the scores.
Exécuter dans le compilateur Python →

Leçon terminée ?

Marquez-la comme apprise pour suivre votre progression.

Outils pour cette leçon