Từ confusion matrix, Kungfutech Chương 6 đi sâu các metric phân loại nhị phân: precision, recall, F1 và ROC-AUC. Bài này giải thích công thức, khi nào ưu tiên metric nào, và cách tính bằng sklearn.metrics.
Mục tiêu
- Tính precision, recall, F1 từ TP/FP/FN và qua
precision_score,recall_score,f1_score. - Hiểu ROC curve và AUC; vẽ bằng
RocCurveDisplay. - Chọn metric phù hợp khi FP và FN có chi phí khác nhau (ví dụ y tế).
Lý thuyết
Precision và Recall
Precision (độ chính xác dương tính): trong số dự đoán positive, bao nhiêu đúng?
$$\text{Precision} = \frac{TP}{TP + FP}$$
Cao khi ít false alarm. Quan trọng khi FP đắt (ví dụ spam filter gửi nhầm email quan trọng vào spam).
Recall (độ nhạy, sensitivity): trong số thực tế positive, bắt được bao nhiêu?
$$\text{Recall} = \frac{TP}{TP + FN}$$
Cao khi ít bỏ sót. Quan trọng khi FN đắt (bỏ sót ung thư).
Hai metric trade-off khi thay đổi ngưỡng quyết định (threshold) trên xác suất dự đoán.
F1-score
Harmonic mean cân bằng precision và recall:
$$F_1 = 2 \cdot \frac{\text{Precision} \cdot \text{Recall}}{\text{Precision} + \text{Recall}} = \frac{2TP}{2TP + FP + FN}$$
Dùng khi cần một số tổng hợp và classes tương đối cân bằng. Không thay thế phân tích FP/FN riêng trong y tế.
average parameter: 'binary' (2 lớp), 'macro', 'weighted' (multiclass — bài 11).
ROC và AUC
ROC curve vẽ True Positive Rate (TPR = Recall) theo False Positive Rate (FPR):
$$\text{FPR} = \frac{FP}{FP + TN}$$
Khi thay threshold từ 1 → 0, điểm trượt dọc đường cong ROC.
AUC (Area Under Curve): xác suất model xếp hạng random positive cao hơn random negative.
- AUC = 1.0 — hoàn hảo
- AUC = 0.5 — ngẫu nhiên
- AUC < 0.5 — worse than random (đảo nhãn)
ROC ít bị ảnh hưởng bởi class imbalance hơn accuracy, nhưng vẫn có thể misleading khi imbalance cực đoan — cân nhắc PR curve (PrecisionRecallDisplay).
Cần predict_proba hoặc decision_function — SVC mặc định không có probability; dùng SVC(probability=True) hoặc decision_function.
Threshold tuning
Classifier mặc định threshold = 0.5 trên probability. Giảm threshold → recall tăng, precision giảm. Trong production, chọn threshold theo chi phí business, không cố định 0.5.
Precision-Recall curve
average_precision_score tổng hợp đường PR thành một số — hữu ích khi positive hiếm. PR curve nhấn mạnh performance vùng positive; ROC đôi khi “đẹp” dù recall minority thấp. Quy tắc thực hành: imbalance mạnh → ưu tiên PR-AUC và recall minority; cân bằng → ROC-AUC và F1 vẫn ổn.
Tài liệu sklearn khuyên dùng classification_report làm báo cáo nhanh vì gom precision/recall/F1/support per class trong một bảng.
Code Python
Metrics và ROC trên Breast Cancer (positive class = malignant, pos_label=0):
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import (
precision_score, recall_score, f1_score,
roc_auc_score, RocCurveDisplay, classification_report
)
import matplotlib.pyplot as plt
X, y = load_breast_cancer(return_X_y=True)
bc = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
pipe = Pipeline([
('scaler', StandardScaler()),
('svc', SVC(kernel='rbf', C=10, probability=True, random_state=42)),
])
pipe.fit(X_train, y_train)
y_pred = pipe.predict(X_test)
y_proba = pipe.predict_proba(X_test)[:, 0] # P(malignant) — class 0
# Metrics cho malignant (pos_label=0)
print(f"Precision (malignant): {precision_score(y_test, y_pred, pos_label=0):.4f}")
print(f"Recall (malignant): {recall_score(y_test, y_pred, pos_label=0):.4f}")
print(f"F1 (malignant): {f1_score(y_test, y_pred, pos_label=0):.4f}")
print(classification_report(y_test, y_pred, target_names=bc.target_names))
# ROC-AUC: malignant as positive
auc = roc_auc_score(y_test, y_proba)
print(f"ROC-AUC (malignant): {auc:.4f}")
RocCurveDisplay.from_predictions(
y_test, y_proba, pos_label=0, name='SVM RBF'
)
plt.title('ROC — malignant vs rest')
plt.savefig('roc_bc.png', dpi=120)
classification_report in precision/recall/F1 cho cả hai lớp cùng macro/weighted avg.
Lỗi thường gặp
- Sai pos_label: Mặc định
pos_label=1(benign) — metric "positive" không khớp mục tiêu y tế. - ROC trên hard predictions: Cần scores liên tục (
predict_proba), không dùngy_pred0/1 cho curve (chỉ 1 điểm). - Quên
probability=Truevới SVC:predict_probalỗi nếu không bật. - Chỉ optimize accuracy trên imbalanced data: Model bỏ qua minority vẫn accuracy cao — theo dõi recall minority.
Bài tập
- Threshold: Với
y_proba, thử threshold 0.3, 0.5, 0.7. Ghi precision/recall malignant mỗi threshold. - So sánh model: Train
LogisticRegressionvà SVC, so sánh ROC-AUC trên cùng test split. - PR curve: Vẽ
PrecisionRecallDisplaycho malignant. Khi nào PR curve informative hơn ROC?
Tóm tắt
Precision, recall, F1 mô tả chất lượng phân loại chi tiết hơn accuracy; ROC-AUC đánh giá khả năng ranking qua mọi threshold. Kungfutech Chương 6 dùng chúng khi chi phí loại lỗi không đối xứng — đặc biệt trước bài multiclass và imbalanced.
Tiếp tục lộ trình tại khóa Machine Learning cơ bản — bài tiếp theo: Multiclass Metrics.