Breast Cancer có 2 lớp; nhiều bài toán thực tế có 3+ lớp — phân loại loài hoa Iris, chữ số MNIST, sentiment 3 mức. Bài này theo Kungfutech Chương 6 — Multiclass metrics, mở rộng precision/recall/F1 với average='macro'|'micro'|'weighted' theo sklearn multiclass.
Mục tiêu
- Tính per-class và aggregated metrics cho phân loại $K$ lớp trên Iris.
- Phân biệt macro, micro, weighted averaging và khi nào dùng từng loại.
- Dùng
classification_reportvà confusion matrix multiclass để interpret.
Lý thuyết
One-vs-Rest (OvR) per class
Với mỗi lớp $c$, coi $c$ là positive, các lớp khác là negative → tính TP, FP, FN → precision/recall/F1 riêng cho lớp $c$.
Iris 3 lớp → 3 bộ metric per-class. Cần aggregate thành một số để so sánh model.
Macro average
$$\text{F1}{macro} = \frac{1}{K} \sum{c=1}^{K} F1_c$$
Coi mọi lớp như nhau — lớp hiếm có trọng số bằng lớp phổ biến. Phù hợp khi mọi lớp đều quan trọng (phân loại loài, phân loại bệnh hiếm).
Nhược: Lớp khó/hiếm kéo macro xuống dù accuracy tổng cao.
Micro average
Gộp TP, FP, FN toàn cục rồi tính metric một lần:
$$\text{Precision}_{micro} = \frac{\sum TP}{\sum TP + \sum FP}$$
Với single-label multiclass, micro-F1 = accuracy (mỗi mẫu đóng góp như nhau). Phù hợp khi quan tâm tổng số dự đoán đúng, không cân bằng per-class.
Weighted average
Trung bình per-class metric, trọng số theo support (số mẫu mỗi lớp):
$$\text{F1}{weighted} = \sum{c=1}^{K} \frac{n_c}{N} F1_c$$
Giữa macro và micro — phản ánh imbalance nhẹ (Iris cân bằng 50/50/50 nên weighted ≈ macro).
Bảng so sánh nhanh
| average | Trọng số lớp | Bằng accuracy? | Khi dùng |
|---|---|---|---|
| macro | Đều | Không | Mọi lớp quan trọng |
| micro | Theo mẫu | F1_micro = acc | Tổng thể |
| weighted | Theo support | Không | Imbalance vừa |
Multiclass ROC-AUC
roc_auc_score với multi_class='ovr' hoặc 'ovo', average='macro'. Cần predict_proba shape (n_samples, n_classes).
- OvR (one-vs-rest): Mỗi lớp một binary ROC, macro-average AUC — phổ biến, nhanh.
- OvO (one-vs-one): Mỗi cặp lớp một classifier — $K(K-1)/2$ cặp với Iris; chính xác hơn về lý thuyết nhưng tốn kém hơn.
Khi báo cáo multiclass, luôn kèm confusion matrix và per-class recall — một macro-F1 cao vẫn có thể che lớp “yếu” nếu không đọc từng hàng ma trận.
Code Python
Multiclass metrics trên Iris với SVM:
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import (
classification_report, confusion_matrix,
precision_score, recall_score, f1_score,
roc_auc_score
)
iris = load_iris()
X, y = iris.data, iris.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42, stratify=y
)
pipe = Pipeline([
('scaler', StandardScaler()),
('svc', SVC(kernel='rbf', C=1, probability=True, random_state=42)),
])
pipe.fit(X_train, y_train)
y_pred = pipe.predict(X_test)
print("=== Classification Report ===")
print(classification_report(y_test, y_pred, target_names=iris.target_names))
print("=== Aggregated F1 ===")
for avg in ['macro', 'micro', 'weighted']:
f1 = f1_score(y_test, y_pred, average=avg)
print(f"F1 ({avg}): {f1:.4f}")
print("\n=== Per-class precision ===")
for i, name in enumerate(iris.target_names):
p = precision_score(y_test, y_pred, labels=[i], average='macro', zero_division=0)
# Hoặc dùng report — ở đây minh họa labels
print(f" {name}: included in report above")
print("\nConfusion matrix:")
print(confusion_matrix(y_test, y_pred))
# ROC-AUC multiclass OvR
y_proba = pipe.predict_proba(X_test)
auc_macro = roc_auc_score(y_test, y_proba, multi_class='ovr', average='macro')
print(f"\nROC-AUC (OvR, macro): {auc_macro:.4f}")
# CV với scoring multiclass
cv_f1_macro = cross_val_score(pipe, X, y, cv=5, scoring='f1_macro')
print(f"CV f1_macro: {cv_f1_macro.mean():.4f} (+/- {cv_f1_macro.std():.4f})")
Iris balanced → macro, weighted, micro F1 thường gần nhau (~0.95+).
Lỗi thường gặp
- Dùng
average='binary'cho 3+ lớp: Lỗi — cần macro/micro/weighted. - So sánh model chỉ bằng accuracy khi lớp imbalanced: Dùng macro-F1 hoặc weighted-F1.
- Nhầm micro-F1 với macro-F1 trên imbalanced data: Micro ≈ accuracy, che lấp performance lớp hiếm.
- ROC multiclass không chỉ
average: Cầnmulti_class='ovr'hoặc'ovo'rõ ràng.
Bài tập
- Giả lập imbalance: Từ Iris, undersample class
setosacòn 10 mẫu (giữ train/test stratify nếu có thể). So sánh macro vs weighted F1. - Grid Search:
GridSearchCVvớiscoring='f1_macro'vsscoring='accuracy'—best_params_có khác không? - Confusion matrix: Lớp Iris nào thường bị nhầm với lớp nào? Liên hệ với per-class recall trong report.
Tóm tắt
Multiclass classification metrics mở rộng precision/recall/F1 qua macro (công bằng giữa lớp), micro (theo mẫu), weighted (theo support). Kungfutech Chương 6 dùng Iris làm ví dụ chuẩn trước khi xử lý imbalance thực sự ở bài cuối.
Tiếp tục lộ trình tại khóa Machine Learning cơ bản — bài tiếp theo: Class Imbalance.