Evaluation Metrics - Confusion Matrix và F1-Score
Mục tiêu bài học
Sau bài học này, học viên sẽ:
- Hiểu và đọc được Confusion Matrix
- Nam vung Accuracy, Precision, Recall, F1-Score
- Biết khi nào dùng metric nào
- Tính toán thủ công cac metrics
1. Confusion Matrix
1.1 Cấu trúc
| Predicted Negative | Predicted Positive | |
|---|---|---|
| Actual Negative | TN (True Negative) | FP (False Positive) |
| Actual Positive | FN (False Negative) | TP (True Positive) |
1.2 Giải thích
| Ky hieu | Ý nghĩa | Kết quả |
|---|---|---|
| TP | Du doan Positive, thuc te Positive | Đúng |
| TN | Du doan Negative, thuc te Negative | Đúng |
| FP | Du doan Positive, thuc te Negative | Sai (Type I Error) |
| FN | Du doan Negative, thuc te Positive | Sai (Type II Error) |
Hinh: Moi quan he giữa Precision va Recall
2. Các Metrics cơ bản
2.1 Công thức
2.2 Ý nghĩa trực quan
| Metric | Câu hỏi | Focus |
|---|---|---|
| Accuracy | Tổng the dung bao nhieu? | Overall performance |
| Precision | Dự đoán Positive chính xác không? | Giảm False Positive |
| Recall | Có bỏ sót Positive không? | Giảm False Negative |
| F1-Score | Cân bằng Precision va Recall | Trade-off |
Precision: "Trong những cái PREDICT POSITIVE, bao nhiêu % ĐÚNG POSITIVE?"
Recall: "Trong những cái THỰC TẾ POSITIVE, bao nhieu % được PHÁT HIỆN?"
3. Ví dụ tính toán thủ công chi tiết
3.1 Bài toán: Chẩn đoán bệnh
Dữ liệu: 100 bệnh nhân
- 30 người thực sự có bệnh (Positive)
- 70 người không có bệnh (Negative)
Kết quả model:
| Predict Không bệnh | Predict Có bệnh | |
|---|---|---|
| Thực tế Không bệnh | TN = 60 | FP = 10 |
| Thực tế Có bệnh | FN = 5 | TP = 25 |
3.2 Tính tung Metric
Accuracy:
Precision:
"Trong 35 người dự đoán co benh, 25 người thực sự có bệnh"
Recall (Sensitivity):
"Trong 30 người thực sự có bệnh, phát hiện được 25 người"
F1-Score:
3.3 Diễn giải ket qua
| Metric | Gia tri | Diễn giải |
|---|---|---|
| Accuracy | 85% | 85% dự đoán dung |
| Precision | 71.4% | 71.4% dự đoán "co benh" la dung |
| Recall | 83.3% | Phat hien duoc 83.3% người benh |
| F1 | 76.9% | Cân bằng giữa Precision va Recall |
4. Khi nào dùng Metric nao?
4.1 Hướng dẫn chọn Metric
| Trường hợp | Metric | Lý do |
|---|---|---|
| Data balanced | Accuracy | Phản ánh đúng performance |
| Data imbalanced | F1-Score | Accuracy gây hiểu lầm |
| FP cost cao | Precision | Tranh dự đoán sai Positive |
| FN cost cao | Recall | Tránh bỏ sót Positive |
4.2 Vi du cu the
Spam filter (FP cost cao - mất email quan trọng):
- Ưu tiên: Precision
- Lý do: FP = email quan trọng vào spam!
Y tế chẩn đoán (FN cost cao - bo sot bệnh nhân):
- Ưu tiên: Recall
- Lý do: FN = bo sot bệnh nhân nguy hiem!
Fraud detection (FN cost cao - bỏ sót gian lận):
- Ưu tiên: Recall
- Lý do: FN = bỏ sót gian lận mat tien!
4.3 Accuracy Paradox
Tại sao Accuracy khong tot cho imbalanced data:
Vi du: 990 Negative, 10 Positive
- Model dự đoán TAT CA la Negative
- Accuracy = 990/1000 = 99%
- Nhưng model vô nghĩa (recall = 0%)!
5. Thực hành với Scikit-learn
5.1 Code hoàn chỉnh
1import numpy as np2from sklearn.metrics import (3 confusion_matrix, 4 accuracy_score, 5 precision_score, 6 recall_score, 7 f1_score,8 classification_report9)10import seaborn as sns11import matplotlib.pyplot as plt1213# Dữ liệu mau14y_true = [1]*25 + [0]*60 + [1]*5 + [0]*10 # Actual15y_pred = [1]*25 + [0]*60 + [0]*5 + [1]*10 # Predicted1617# Confusion Matrix18cm = confusion_matrix(y_true, y_pred)19print("Confusion Matrix:")20print(cm)2122# Visualize23plt.figure(figsize=(8, 6))24sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',25 xticklabels=['Predict Neg', 'Predict Pos'],26 yticklabels=['Actual Neg', 'Actual Pos'])27plt.title('Confusion Matrix')28plt.ylabel('Actual')29plt.xlabel('Predicted')30plt.show()3132# Metrics33print(f"\nAccuracy: {accuracy_score(y_true, y_pred):.4f}")34print(f"Precision: {precision_score(y_true, y_pred):.4f}")35print(f"Recall: {recall_score(y_true, y_pred):.4f}")36print(f"F1-Score: {f1_score(y_true, y_pred):.4f}")3738# Classification Report39print("\nClassification Report:")40print(classification_report(y_true, y_pred, 41 target_names=['Negative', 'Positive']))5.2 Output mẫu
1Confusion Matrix:2[[60 10]3 [ 5 25]]4 5Accuracy: 0.85006Precision: 0.71437Recall: 0.83338F1-Score: 0.76929 10Classification Report:11 precision recall f1-score support12 Negative 0.92 0.86 0.89 7013 Positive 0.71 0.83 0.77 3014 accuracy 0.85 1006. Specificity va cac Metrics khac
6.1 Specificity (True Negative Rate)
"Trong nhung người khong benh, bao nhieu % duoc nhan dung la khong benh"
6.2 Bảng tổng hợp
| Metric | Công thức | Ý nghĩa |
|---|---|---|
| Sensitivity/Recall/TPR | TP/(TP+FN) | Ty le positive dung |
| Specificity/TNR | TN/(TN+FP) | Ty le negative dung |
| Precision/PPV | TP/(TP+FP) | Do chinh xac positive |
| NPV | TN/(TN+FN) | Do chinh xac negative |
| FPR | FP/(FP+TN) | Ty le false positive |
Bài tập tự luyện
- Bai tap 1: Tính cac metrics cho CM: TP=80, TN=120, FP=20, FN=30
- Bai tap 2: Giải thích tai sao Accuracy cao nhung Recall thấp la nguy hiem trong y te
- Bai tap 3: Train model tren imbalanced data va so sanh cac metrics
