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.
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
- 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.
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"]))
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.
- 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.
Leçon terminée ?
Marquez-la comme apprise pour suivre votre progression.
Votre progression est enregistrée dans ce navigateur Connectez-vous pour la garder sur tous vos appareils.
Outils pour cette leçon
- Bases de la classification : softmax et k plus proches voisins en PythonTransformez des scores en probabilités de classes avec softmax, évaluez-les avec l'entropie croisée et classez des points avec les k plus proches voisins.
- Jupyter Notebook en ligne : exécuter des cellules Python dans le navigateurJupyter Notebook en ligne gratuit : exécutez des cellules Python avec pandas, NumPy et Matplotlib, ajoutez du texte en Markdown, ouvrez et téléchargez des fichiers .ipynb. Sans installation, sans compte.
- Basthon, Capytale ou CodeUtility : quel outil pour Python en ligne ?Basthon, Capytale et CodeUtility comparés pour écrire du Python en ligne au lycée : à quoi sert chaque outil, compte, débogueur, exercices et classes.