Sau preprocessing — impute, encode, scale — bạn có thể vẫn còn quá nhiều feature so với số mẫu, hoặc nhiều cột nhiễu/redundant. Feature selection giảm chiều, tăng interpretability và đôi khi cải thiện generalization. Kungfutech Chương 4 kết thúc với sequential feature selection và Random Forest feature importance — hai hướng filter/wrapper và embedded phổ biến trong sklearn.
Mục tiêu
- Phân biệt filter, wrapper, embedded feature selection.
- Dùng
SequentialFeatureSelector(SFS) forward/backward. - Đọc và giới hạn feature_importances_ từ
RandomForestClassifier.
Lý thuyết
Ba nhóm phương pháp
| Loại | Ý tưởng | Ví dụ sklearn |
|---|---|---|
| Filter | Score feature độc lập model | SelectKBest, correlation, mutual info |
| Wrapper | Subset feature + đánh giá model | SequentialFeatureSelector, RFE |
| Embedded | Selection trong quá trình fit | Lasso (L1), Tree importance |
Kungfutech nhấn SFS (wrapper) và RF importance (embedded) — bổ sung cho L1 Lasso bài trước.
Sequential Feature Selector (SFS)
Forward selection: Bắt đầu tập rỗng, mỗi bước thêm feature cải thiện score CV nhiều nhất.
Backward elimination: Bắt đầu full set, mỗi bước bỏ feature ít hại nhất.
Floating variants (direction='forward' + tol, n_features_to_select):
n_features_to_select=5— dừng khi đủ 5 featuren_features_to_select='auto'+tol— dừng khi cải thiện < tol
SFS tốn tính toán — mỗi bước fit model nhiều lần CV. Dùng estimator nhanh ( logistic, small RF) khi explore; dataset lớn cân nhắc filter trước.
from sklearn.feature_selection import SequentialFeatureSelector
sfs = SequentialFeatureSelector(
estimator=LogisticRegression(max_iter=1000),
n_features_to_select=5,
direction="forward",
cv=5,
scoring="accuracy",
)
sfs.fit(X_train, y_train)
X_train_selected = sfs.transform(X_train)
get_support() → mask feature được chọn.
Recursive Feature Elimination (RFE)
RFE — fit model, bỏ feature có coef/importance thấp nhất, lặp. Liên quan backward SFS nhưng dùng ranking một lần mỗi vòng.
Random Forest feature importance
Sau rf.fit(X, y):
rf.feature_importances_
Gini importance (default): Giảm impurity trung bình khi split theo feature — biased với feature cardinality cao hoặc continuous nhiều giá trị.
Permutation importance (permutation_importance) — shuffle một cột, đo drop metric — ưu tiên khi interpret nghiêm túc.
Kungfutech dùng Gini importance cho intuition nhanh trên Wine/Breast Cancer.
Feature selection và preprocessing pipeline
Thứ tự điển hình:
Pipeline([
("prep", ColumnTransformer(...)), # impute, scale, encode
("sfs", SequentialFeatureSelector(...)),
("clf", RandomForestClassifier()),
])
Hoặc select trên đã transformed numeric matrix — cẩn thận map tên feature sau one-hot.
Chỉ fit selector trên train — giống mọi bước preprocessing.
Curse of dimensionality liên hệ
$n$ mẫu, $d$ feature — $d$ lớn so với $n$ → overfit. Feature selection giảm $d$ effective. Kungfutech Chương 4 + Ch.3: regularization (L1) và selection bổ sung nhau.
Không thay thế domain knowledge
Importance cao không chứng minh causation — có thể proxy correlated feature. Luôn validate với permutation importance và expert review.
Code Python
SFS + RF importance trên Breast Cancer:
import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.feature_selection import SequentialFeatureSelector
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
data = load_breast_cancer()
X, y = data.data, data.target
feature_names = data.feature_names
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
# --- Sequential Feature Selector (forward, k=10) ---
base_clf = LogisticRegression(max_iter=2000, random_state=42)
sfs = SequentialFeatureSelector(
base_clf,
n_features_to_select=10,
direction="forward",
cv=3,
scoring="accuracy",
n_jobs=-1,
)
pipe_sfs = Pipeline([
("scaler", StandardScaler()),
("sfs", sfs),
("clf", LogisticRegression(max_iter=2000, random_state=42)),
])
pipe_sfs.fit(X_train, y_train)
selected_mask = pipe_sfs.named_steps["sfs"].get_support()
selected_features = feature_names[selected_mask]
print("SFS selected 10 features:")
for f in selected_features:
print(f" - {f}")
test_acc_sfs = pipe_sfs.score(X_test, y_test)
print(f"\nSFS pipeline test accuracy: {test_acc_sfs:.3f}")
# Baseline: all features
pipe_full = Pipeline([
("scaler", StandardScaler()),
("clf", LogisticRegression(max_iter=2000, random_state=42)),
])
pipe_full.fit(X_train, y_train)
print(f"Full features test accuracy: {pipe_full.score(X_test, y_test):.3f}")
# --- Random Forest importance ---
rf = RandomForestClassifier(n_estimators=200, random_state=42, n_jobs=-1)
rf.fit(X_train, y_train)
importance_df = pd.DataFrame({
"feature": feature_names,
"gini_importance": rf.feature_importances_,
}).sort_values("gini_importance", ascending=False)
print("\nTop 10 RF Gini importance:")
print(importance_df.head(10).to_string(index=False))
# Permutation importance (reliable hơn)
perm = permutation_importance(
rf, X_test, y_test, n_repeats=10, random_state=42, n_jobs=-1
)
perm_df = pd.DataFrame({
"feature": feature_names,
"perm_mean": perm.importances_mean,
}).sort_values("perm_mean", ascending=False)
print("\nTop 5 permutation importance:")
print(perm_df.head(5).to_string(index=False))
So SFS subset vs full — nếu accuracy tương đương, model đơn giản hơn prefer.
Lỗi thường gặp
- SFS trên toàn X trước split: Leakage — gói SFS trong Pipeline fit train only.
- Tin Gini importance mù quáng: Bias cardinality — dùng permutation importance confirm.
- Chọn feature rồi tune hyperparameter trên cùng CV fold: Nested CV khi cần unbiased estimate — SFS bên trong mỗi outer fold.
- Selection trên test: Tuyệt đối không — mọi quyết định feature từ train.
Bài tập
- Backward SFS: Trên Wine (13 feature), chạy
direction='backward'chọn 6 feature. Subset có overlap với forward không? - RF vs Lasso: So top-5 feature từ RF Gini vs Lasso coef ≠ 0 (alpha=0.1, scaled) trên cùng Breast Cancer split.
- Đọc docs:
SequentialFeatureSelector—tolhoạt động thế nào vớin_features_to_select='auto'?
Tóm tắt
Feature selection tinh gọn tập đặc trưng sau preprocessing — SequentialFeatureSelector (wrapper forward/backward) và Random Forest feature importance (embedded) là hai công cụ Kungfutech Chương 4. Fit selector trên train; ưu tiên permutation importance khi interpret. Kết hợp với scaling, regularization L1/L2 để xây pipeline ML robust từ raw data đến model gọn.
Tiếp tục tại khóa Machine Learning cơ bản — hoàn thành Chương 4 Preprocessing, sẵn sàng cho các thuật toán học sâu hơn.