Dataset thực tế thường mất cân bằng lớp: gian lận 0.1%, bệnh hiếm 2%, click quảng cáo 3%. Bài cuối Kungfutech Chương 6 — Class imbalance — tổng hợp chiến lược đánh giá và huấn luyện khi minority class là điều bạn thực sự cần phát hiện.
Mục tiêu
- Nhận diện khi accuracy misleading và chọn metric (recall, F1, PR-AUC, balanced accuracy).
- Dùng
class_weight='balanced'và tham số tương đương trong sklearn. - Giới thiệu resampling (undersample/oversample) và
StratifiedKFoldbắt buộc.
Lý thuyết
Vấn đề imbalance
Giả sử tỷ lệ negative:positive = 99:1. Classifier dự đoán luôn negative đạt accuracy 99% nhưng recall positive = 0 — vô dụng cho phát hiện gian lận/bệnh.
Breast Cancer nhẹ imbalance (357 benign vs 212 malignant, ~63/37) — accuracy còn tạm chấp nhận. Khi tỷ lệ 95/5 hoặc 99/1, bắt buộc đổi metric và chiến lược training.
Metric phù hợp
| Metric | Ưu | Nhược |
|---|---|---|
| Recall (minority) | Đo bắt được bao nhiêu case hiếm | Bỏ qua FP |
| Precision | Đo false alarm | Bỏ qua FN |
| F1 / macro-F1 | Cân bằng P/R | Một số tổng hợp |
| Balanced accuracy | Trung bình recall từng lớp | — |
| PR-AUC | Tốt khi imbalance mạnh | Cần probability |
| ROC-AUC | Threshold-free | Có thể optimistic khi imbalance cực |
balanced_accuracy_score = mean per-class recall.
Grid Search: scoring='f1', 'f1_macro', 'balanced_accuracy', hoặc custom scorer — không dùng accuracy mặc định khi minority quan trọng.
class_weight trong sklearn
Nhiều classifier hỗ trợ class_weight='balanced':
$$w_c = \frac{n}{K \cdot n_c}$$
$n$ = tổng mẫu, $n_c$ = số mẫu lớp $c$, $K$ = số lớp. Penalty loss cao hơn khi misclassify lớp hiếm → model ưu tiên recall minority.
Áp dụng cho LogisticRegression, SVC, RandomForestClassifier, v.v.
Dict custom: class_weight={0: 10, 1: 1} khi biết chi phí FN >> FP.
Resampling
- Random oversampling minority — duplicate mẫu hiếm (risk overfit minority).
- Random undersampling majority — mất thông tin majority.
- SMOTE (imbalanced-learn package) — synthetic minority — ngoài sklearn core nhưng phổ biến.
Resampling chỉ trên train fold trong Pipeline/CV — không resample test. Pattern: imblearn.pipeline.Pipeline nếu dùng imbalanced-learn.
Stratified split và CV
Luôn stratify=y trong train_test_split và StratifiedKFold — đảm bảo mỗi split có minority. Với cực hiếm, cân nhắc stratified với ít fold hơn hoặc repeated stratified CV.
Threshold adjustment
Sau khi train, hạ threshold trên $P(\text{positive})$ để tăng recall minority — trade-off precision. FixedThresholdClassifier (sklearn >= 1.5) hoặc manual trên predict_proba.
Code Python
So sánh model không weight vs balanced trên Breast Cancer (giả lập imbalance mạnh hơn bằng undersample malignant):
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
classification_report, balanced_accuracy_score,
f1_score, confusion_matrix
)
X, y = load_breast_cancer(return_X_y=True)
bc = load_breast_cancer()
# Giả lập imbalance: giữ 80 malignant (0), toàn bộ benign (1)
idx_mal = np.where(y == 0)[0][:80]
idx_ben = np.where(y == 1)[0]
idx = np.concatenate([idx_mal, idx_ben])
X_sub, y_sub = X[idx], y[idx]
print(f"Imbalanced subset: malignant={ (y_sub==0).sum() }, benign={ (y_sub==1).sum() }")
X_train, X_test, y_train, y_test = train_test_split(
X_sub, y_sub, test_size=0.25, random_state=42, stratify=y_sub
)
def eval_model(class_weight):
pipe = Pipeline([
('scaler', StandardScaler()),
('lr', LogisticRegression(
max_iter=1000, class_weight=class_weight, random_state=42
)),
])
pipe.fit(X_train, y_train)
y_pred = pipe.predict(X_test)
acc = pipe.score(X_test, y_test)
bal_acc = balanced_accuracy_score(y_test, y_pred)
f1_min = f1_score(y_test, y_pred, pos_label=0) # malignant
return acc, bal_acc, f1_min, y_pred
for cw, label in [(None, 'No weight'), ('balanced', 'Balanced weight')]:
acc, bal, f1, y_pred = eval_model(cw)
print(f"\n--- {label} ---")
print(f"Accuracy: {acc:.4f} | Balanced acc: {bal:.4f} | F1 malignant: {f1:.4f}")
print(classification_report(y_test, y_pred, target_names=bc.target_names))
# CV với scoring phù hợp
pipe = Pipeline([
('scaler', StandardScaler()),
('lr', LogisticRegression(max_iter=1000, class_weight='balanced')),
])
scores = cross_val_score(pipe, X_sub, y_sub, cv=5, scoring='balanced_accuracy')
print(f"\nCV balanced_accuracy: {scores.mean():.4f} (+/- {scores.std():.4f})")
Thường thấy class_weight='balanced' tăng recall malignant (F1 minority) dù accuracy có thể giảm nhẹ.
Lỗi thường gặp
- Resample trước train_test_split: Leakage — distribution test không còn realistic; resample trong CV train only.
- Chỉ báo cáo accuracy: Misleading trên imbalance — kèm confusion matrix và recall minority.
- SMOTE trên toàn dataset: Synthetic samples từ test leak — chỉ SMOTE train fold.
- Quên stratify: Một fold CV không có minority → metric undefined hoặc unstable.
Bài tập
- Metric Grid Search: Trên subset imbalanced ở trên, chạy
GridSearchCVvớiscoring='balanced_accuracy'vsscoring='accuracy'. So sánhbest_params_và recall malignant trên test. - Dummy baseline: Dùng
DummyClassifier(strategy='most_frequent'). Accuracy và balanced accuracy của dummy là bao nhiêu? Model của bạn beat dummy ở metric nào? - Tổng kết chương: Liệt kê 5 kỹ thuật từ Ch.6 (Pipeline, CV, Grid Search, nested CV, metrics) bạn sẽ áp dụng cho một project phân loại email spam 99:1.
Tóm tắt
Imbalanced classification đòi hỏi metric và chiến lược training khác accuracy mặc định: class_weight, resampling có kiểm soát, stratified CV, và PR/recall-focused evaluation. Đây là điểm kết Kungfutech Chương 6 — từ workflow đánh giá đến hyperparameter tuning và metrics phản ánh đúng mục tiêu business.
Tiếp tục lộ trình tại khóa Machine Learning cơ bản — hoàn thành Chương 6 Model Evaluation & Hyperparameter Tuning.