Chương 5 Kungfutech kết thúc với bức tranh toàn cảnh dimensionality reduction — từ PCA tuyến tính, LDA có giám sát, đến Kernel PCA trong sklearn. Bài tổng hợp giúp bạn chọn công cụ, ghép Pipeline và tránh lỗi hệ thống khi triển khai.
Mục tiêu
- So sánh PCA, LDA, Kernel PCA trong một workflow thống nhất.
- Nắm checklist chọn phương pháp theo bài toán và kích thước dữ liệu.
- Hoàn thiện ví dụ end-to-end: scale → giảm chiều → classifier trên nhiều dataset.
Lý thuyết
Ba trụ cột Chương 5
| Phương pháp | Loại | Mục tiêu | sklearn class |
|---|---|---|---|
| PCA | Unsupervised | Max variance | decomposition.PCA |
| LDA | Supervised | Max class separation | discriminant_analysis.LinearDiscriminantAnalysis |
| Kernel PCA | Unsupervised (nonlinear) | PCA trong feature space | decomposition.KernelPCA |
Tất cả implement TransformerMixin: fit / transform / fit_transform, tích hợp Pipeline và GridSearchCV.
Quy trình chọn phương pháp
- Có nhãn và mục tiêu classification? → Thử LDA (hoặc PCA + classifier nếu $d$ không quá lớn).
- Chỉ EDA / visualization / không nhãn? → PCA; nếu scatter 2D không có cấu trúc → Kernel PCA (RBF).
- $n$ hoặc $d$ rất lớn? → PCA
svd_solver='randomized'; tránh Kernel PCA $O(n^3)$ — cân nhắcNystroem+ PCA. - Cần interpret feature? → PCA loadings có giới hạn; cân nhắc không giảm chiều hoặc feature selection thay thế.
- Deploy inference nhanh? → PCA > LDA > Kernel PCA (kernel cần store training data).
Kernel PCA trong sklearn — điểm cần nhớ
- API song song PCA:
n_components,fit_transform,transform. - Hyperparameters:
kernel,gamma,degree,coef0. eigenvalues_thay choexplained_variance_— chọn $k$ tương tự scree plot.fit_inverse_transformcho denoising — không bắt buộc cho classification pipeline.- User guide: Kernel PCA.
Kết hợp và mở rộng (ngoài sách)
- TruncatedSVD / LSA: Sparse text — không center, phù hợp TF-IDF.
- NMF: Non-negative data (images, counts).
- t-SNE, UMAP: Visualization only — không dùng
transformproduction như PCA. - Autoencoders: Deep learning alternative — ngoài phạm vi chương này.
Checklist tránh lỗi hệ thống
-
StandardScalertrước PCA/LDA khi scale khác nhau. - Fit mọi transformer chỉ trên train trong CV.
- LDA:
n_components ≤ C-1. - Kernel PCA: tune
gammatrên validation. - Serialize full Pipeline, không chỉ PCA riêng lẻ.
Code Python
Benchmark ngắn trên Iris, Wine, Breast Cancer — PCA vs LDA vs Kernel PCA + LogisticRegression:
import warnings
import numpy as np
from sklearn.datasets import load_iris, load_wine, load_breast_cancer
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA, KernelPCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
warnings.filterwarnings("ignore", category=FutureWarning)
datasets = {
"iris": load_iris(),
"wine": load_wine(),
"breast_cancer": load_breast_cancer(),
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
clf = LogisticRegression(max_iter=2000)
def make_pipelines(n_classes):
n_lda = min(2, n_classes - 1)
return {
"PCA(0.95)": Pipeline([
("scaler", StandardScaler()),
("dr", PCA(n_components=0.95)),
("clf", clf),
]),
"LDA": Pipeline([
("scaler", StandardScaler()),
("dr", LinearDiscriminantAnalysis(n_components=n_lda)),
("clf", clf),
]),
"KernelPCA-RBF": Pipeline([
("scaler", StandardScaler()),
("dr", KernelPCA(n_components=n_lda, kernel="rbf", gamma=0.1)),
("clf", clf),
]),
}
for name, bundle in datasets.items():
X, y = bundle.data, bundle.target
n_classes = len(np.unique(y))
pipes = make_pipelines(n_classes)
print(f"\n=== {name} (n={len(y)}, d={X.shape[1]}, classes={n_classes}) ===")
for pname, pipe in pipes.items():
scores = cross_val_score(pipe, X, y, cv=cv, scoring="accuracy")
print(f" {pname:18s} accuracy: {scores.mean():.4f} (+/- {scores.std():.4f})")
Kết quả typcial: tabular datasets gần tuyến tính — PCA và LDA cạnh tranh; Kernel PCA có thể không vượt trội nếu gamma chưa tune — nhắc nhở luôn validate, không mặc định kernel tốt hơn.
Template Pipeline production
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import KernelPCA
from sklearn.svm import SVC
model = Pipeline([
("scaler", StandardScaler()),
("kpca", KernelPCA(n_components=10, kernel="rbf", gamma=0.05)),
("svc", SVC(kernel="rbf")),
])
# model.fit(X_train, y_train); model.predict(X_test)
Lỗi thường gặp
- Dùng Kernel PCA mọi nơi: Overkill trên tabular low-d — tốn thời gian, khó tune.
- So sánh không công bằng: PCA 95% variance vs LDA 2 components vs kPCA 2 — align
n_componentshoặc tune từng pipeline. - Quên stratify CV trên imbalanced data: Breast Cancer cần
stratify=ykhi split. - Bỏ qua baseline không giảm chiều: Luôn so với classifier trên feature gốc — giảm chiều không guaranteed giúp ích.
Bài tập
- Tổng hợp: Vẽ sơ đồ quyết định (flowchart) chọn PCA / LDA / Kernel PCA theo 4 câu hỏi: có nhãn? cần nonlinear? $n$ lớn? cần transform nhanh?
- Thực hành: Chạy benchmark script trên 3 dataset. Ghi pipeline nào thắng mỗi dataset và giải thích ngắn (2–3 câu/dataset).
- Capstone: Xây
GridSearchCVtrên Wine vớiPipeline(StandardScaler, KernelPCA, LogisticRegression)— searchgammavàn_components. In best params và CV score.
Tóm tắt
Dimensionality reduction trong Kungfutech Chương 5 xoay quanh PCA (variance), LDA (class separation), và Kernel PCA (nonlinear sklearn). Workflow chung: chuẩn hóa → fit transformer trên train → transform → downstream task. Chọn theo nhãn, cấu trúc dữ liệu và ràng buộc deploy — luôn đối chiếu baseline và tránh leakage.
Chúc mừng bạn hoàn thành Chương 5! Tiếp tục lộ trình tại khóa Machine Learning cơ bản — các chương tiếp theo đi sâu vào ensemble learning và model tuning.