Accuracy cho một con số duy nhất, nhưng không cho biết mô hình nhầm loại nào. Confusion matrix (ma trận nhầm lẫn) là bảng đếm dự đoán đúng/sai theo từng cặp lớp thực tế vs dự đoán. Bài theo Kungfutech Chương 6 — Confusion matrix, dựa trên confusion_matrix.
Mục tiêu
- Xây dựng confusion matrix bằng
confusion_matrixvà visualize bằngConfusionMatrixDisplay. - Định nghĩa TP, TN, FP, FN cho bài toán nhị phân.
- Giải thích hạn chế của accuracy khi lớp mất cân bằng.
Lý thuyết
Cấu trúc ma trận nhị phân
Với lớp positive (1) và negative (0), ma trận $2 \times 2$:
| Pred 0 | Pred 1 | |
|---|---|---|
| True 0 | TN | FP |
| True 1 | FN | TP |
- TP (True Positive): Thực tế dương, dự đoán dương — chẩn đoán ung thư đúng (malignant).
- TN (True Negative): Thực tế âm, dự đoán âm — benign đúng.
- FP (False Positive): Type I error — benign bị gọi malignant (báo động giả).
- FN (False Negative): Type II error — malignant bị bỏ sót (nguy hiểm trong y tế).
Trên Breast Cancer, target=0 là malignant, target=1 là benign — cần kiểm tra labels và target_names khi gán TP/FN; sklearn mặc định sort labels theo thứ tự xuất hiện.
Accuracy từ confusion matrix
$$\text{Accuracy} = \frac{TP + TN}{TP + TN + FP + FN}$$
Với 357 benign và 212 malignant, nếu model dự đoán luôn benign, accuracy $\approx 357/569 \approx 62.7%$ — cao v seemingly nhưng 0% recall malignant. Confusion matrix làm lộ hành vi này ngay.
Multiclass confusion matrix
Với $K$ lớp (Iris $K=3$), ma trận $K \times K$: hàng $i$ = lớp thật $i$, cột $j$ = dự đoán $j$. Đường chéo = dự đoán đúng; off-diagonal = loại nhầm lẫn cụ thể (ví dụ virginica bị gọi versicolor).
Normalized confusion matrix
Chia mỗi hàng cho tổng hàng → recall per class (tỷ lệ mỗi lớp thật được phân loại đúng). Tham số normalize='true' trong confusion_matrix. Hữu ích khi lớp imbalanced.
Theo Classification metrics, confusion matrix là basis cho precision, recall, F1 (bài 10).
Đọc ma trận trong thực tế
Khi trình bày cho stakeholder không kỹ thuật, gắn nhãn hàng/cột bằng tên lớp (display_labels) thay vì số 0/1. Với Breast Cancer, hãy thống nhất team: “positive” là malignant hay benign trước khi tính precision/recall — nhầm lẫn ở bước này dẫn đến quyết định sai về ngưỡng cảnh báo. Ma trận trên tập validation/out-of-fold cũng quan trọng như test cuối khi bạn lặp lại thí nghiệm nhiều lần trong quá trình phát triển.
Code Python
Confusion matrix trên Breast Cancer với SVM đã tune đơn giản:
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 confusion_matrix, ConfusionMatrixDisplay, 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, gamma='scale')),
])
pipe.fit(X_train, y_train)
y_pred = pipe.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
print("Confusion matrix (raw counts):")
print(cm)
print(f"\nLabels order: {bc.target_names}") # ['malignant', 'benign']
# classification_report kèm precision/recall per class
print(classification_report(y_test, y_pred, target_names=bc.target_names))
# Visualize
disp = ConfusionMatrixDisplay(
confusion_matrix=cm,
display_labels=bc.target_names,
)
disp.plot(cmap='Blues')
plt.title('Breast Cancer — Confusion Matrix')
plt.tight_layout()
plt.savefig('confusion_matrix_bc.png', dpi=120)
print(f"Accuracy thủ công: {(cm[0,0]+cm[1,1]) / cm.sum():.4f}")
Đọc output: phần tử cm[0,1] = malignant bị dự đoán benign (FN nguy hiểm nếu 0=malignant).
Lỗi thường gặp
- Đảo nhầm hàng/cột: sklearn:
C[i,j]= true class i, pred class j. Một số tài liệu đảo convention. - Không chỉ rõ positive class: Precision/recall phụ thuộc
pos_label; mặc địnhpos_label=1(benign) — có thể không phải class bạn quan tâm y tế. - Chỉ nhìn accuracy trên imbalanced data: Luôn kèm confusion matrix hoặc per-class metrics.
- Đánh giá trên train set: Ma trận trên train overfit — dùng test hoặc CV out-of-fold predictions.
Bài tập
- Iris multiclass: Train
RandomForestClassifiertrên Iris, vẽ confusion matrix $3 \times 3$. Cặp loài nào hay bị nhầm nhất? - Normalized: Tạo
confusion_matrix(..., normalize='true'). Lớp nào có recall thấp nhất? - Tự luận: Trong chẩn đoán ung thư, FP và FN cái nào tốn kém hơn về mặt lâm sàng? Ảnh hưởng đến việc chọn metric?
Tóm tắt
Confusion matrix cho cái nhìn chi tiết TP/TN/FP/FN, nền tảng để hiểu precision, recall và F1. Kungfutech Chương 6 dùng nó chuyển từ "accuracy bao nhiêu" sang "sai kiểu gì, ở lớp nào".
Tiếp tục lộ trình tại khóa Machine Learning cơ bản — bài tiếp theo: Precision, Recall, F1 và ROC.