Lý thuyết
3-4 gio
Bài 9/15

Evaluation Metrics - Confusion Matrix và F1-Score

Accuracy, Precision, Recall, F1-Score va Confusion Matrix chi tiết

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 NegativePredicted Positive
Actual NegativeTN (True Negative)FP (False Positive)
Actual PositiveFN (False Negative)TP (True Positive)

1.2 Giải thích

Ky hieuÝ nghĩaKết quả
TPDu doan Positive, thuc te PositiveĐúng
TNDu doan Negative, thuc te NegativeĐúng
FPDu doan Positive, thuc te NegativeSai (Type I Error)
FNDu doan Negative, thuc te PositiveSai (Type II Error)

Confusion Matrix

Hinh: Moi quan he giữa Precision va Recall


2. Các Metrics cơ bản

2.1 Công thức

Accuracy=TP+TNTP+TN+FP+FNAccuracy = \frac{TP + TN}{TP + TN + FP + FN}

Precision=TPTP+FPPrecision = \frac{TP}{TP + FP}

Recall=TPTP+FNRecall = \frac{TP}{TP + FN}

F1=2\tıˋmesPrecision\tıˋmesRecallPrecision+RecallF1 = 2 \tìmes \frac{Precision \tìmes Recall}{Precision + Recall}

2.2 Ý nghĩa trực quan

MetricCâu hỏiFocus
AccuracyTổng the dung bao nhieu?Overall performance
PrecisionDự đoán Positive chính xác không?Giảm False Positive
RecallCó bỏ sót Positive không?Giảm False Negative
F1-ScoreCân bằng Precision va RecallTrade-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ệnhPredict Có bệnh
Thực tế Không bệnhTN = 60FP = 10
Thực tế Có bệnhFN = 5TP = 25

3.2 Tính tung Metric

Accuracy: Accuracy=25+6025+60+10+5=85100=0.85=85%Accuracy = \frac{25 + 60}{25 + 60 + 10 + 5} = \frac{85}{100} = 0.85 = 85\%

Precision: Precision=2525+10=2535=0.714=71.4%Precision = \frac{25}{25 + 10} = \frac{25}{35} = 0.714 = 71.4\%

"Trong 35 người dự đoán co benh, 25 người thực sự có bệnh"

Recall (Sensitivity): Recall=2525+5=2530=0.833=83.3%Recall = \frac{25}{25 + 5} = \frac{25}{30} = 0.833 = 83.3\%

"Trong 30 người thực sự có bệnh, phát hiện được 25 người"

F1-Score: F1=2\tıˋmes0.714\tıˋmes0.8330.714+0.833=2\tıˋmes0.5951.547=0.769=76.9%F1 = 2 \tìmes \frac{0.714 \tìmes 0.833}{0.714 + 0.833} = 2 \tìmes \frac{0.595}{1.547} = 0.769 = 76.9\%

3.3 Diễn giải ket qua

MetricGia triDiễn giải
Accuracy85%85% dự đoán dung
Precision71.4%71.4% dự đoán "co benh" la dung
Recall83.3%Phat hien duoc 83.3% người benh
F176.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ợpMetricLý do
Data balancedAccuracyPhản ánh đúng performance
Data imbalancedF1-ScoreAccuracy gây hiểu lầm
FP cost caoPrecisionTranh dự đoán sai Positive
FN cost caoRecallTrá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

Python
1import numpy as np
2from sklearn.metrics import (
3 confusion_matrix,
4 accuracy_score,
5 precision_score,
6 recall_score,
7 f1_score,
8 classification_report
9)
10import seaborn as sns
11import matplotlib.pyplot as plt
12
13# Dữ liệu mau
14y_true = [1]*25 + [0]*60 + [1]*5 + [0]*10 # Actual
15y_pred = [1]*25 + [0]*60 + [0]*5 + [1]*10 # Predicted
16
17# Confusion Matrix
18cm = confusion_matrix(y_true, y_pred)
19print("Confusion Matrix:")
20print(cm)
21
22# Visualize
23plt.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()
31
32# Metrics
33print(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}")
37
38# Classification Report
39print("\nClassification Report:")
40print(classification_report(y_true, y_pred,
41 target_names=['Negative', 'Positive']))

5.2 Output mẫu

Text
1Confusion Matrix:
2[[60 10]
3 [ 5 25]]
4
5Accuracy: 0.8500
6Precision: 0.7143
7Recall: 0.8333
8F1-Score: 0.7692
9
10Classification Report:
11 precision recall f1-score support
12 Negative 0.92 0.86 0.89 70
13 Positive 0.71 0.83 0.77 30
14 accuracy 0.85 100

6. Specificity va cac Metrics khac

6.1 Specificity (True Negative Rate)

Specificity=TNTN+FPSpecificity = \frac{TN}{TN + FP}

"Trong nhung người khong benh, bao nhieu % duoc nhan dung la khong benh"

6.2 Bảng tổng hợp

MetricCông thứcÝ nghĩa
Sensitivity/Recall/TPRTP/(TP+FN)Ty le positive dung
Specificity/TNRTN/(TN+FP)Ty le negative dung
Precision/PPVTP/(TP+FP)Do chinh xac positive
NPVTN/(TN+FN)Do chinh xac negative
FPRFP/(FP+TN)Ty le false positive

Bài tập tự luyện

  1. Bai tap 1: Tính cac metrics cho CM: TP=80, TN=120, FP=20, FN=30
  2. Bai tap 2: Giải thích tai sao Accuracy cao nhung Recall thấp la nguy hiem trong y te
  3. Bai tap 3: Train model tren imbalanced data va so sanh cac metrics

Tài liệu tham khảo