Thư viện scikit-learn đóng gói PCA thành estimator chuẩn — cùng pattern fit / transform như mọi transformer khác. Bài này theo Chương 5 Python Machine Learning — phần PCA in sklearn, tập trung API thực hành và tích hợp Pipeline.
Mục tiêu
- Sử dụng thành thạo
sklearn.decomposition.PCA. - Chọn
n_componentsbằng số, float (variance threshold), hoặc'mle'. - Kết hợp PCA với
Pipelinevà tránh data leakage.
Lý thuyết
Estimator interface
PCA kế thừa BaseEstimator, TransformerMixin:
| Phương thức | Vai trò |
|---|---|
fit(X) |
Học mean, tính SVD, lưu components_, explained_variance_ |
transform(X) |
Chiếu $\mathbf{X}$ sang không gian PC: $\mathbf{Z} = (\mathbf{X}-\boldsymbol{\mu})\mathbf{V}^T$ |
fit_transform(X) |
Gộp fit + transform |
inverse_transform(Z) |
Khôi phục xấp xỉ $\hat{\mathbf{X}}$ từ $k$ PC — mất thông tin nếu $k < d$ |
Thuộc tính quan trọng sau fit:
n_components_: số PC thực tế (có thể khác tham số nếu dùng float).explained_variance_ratio_: tỷ lệ phương sai từng PC.singular_values_: giá trị suy biến SVD.
Tham số n_components
- Integer: Giữ đúng $k$ PC.
- Float (0, 1): Chọn ít PC nhất sao cho tổng explained variance $\geq$ ngưỡng (ví dụ
0.95). None: Giữ tất cả PC ($\min(n_{\text{samples}}, n_{\text{features}})$).'mle': Số chiều theo tiêu chí Minka's MLE — tự động nhưng chỉ khisvd_solver='full'.
Randomized PCA
Với $d$ rất lớn, svd_solver='randomized' và n_components nhỏ cho xấp xỉ nhanh — phù hợp visualization hoặc pre-processing sơ bộ. Xem User guide — PCA.
Pipeline chuẩn
Thứ tự điển hình:
Pipeline([
("scaler", StandardScaler()),
("pca", PCA(n_components=0.95)),
("clf", LogisticRegression()),
])
StandardScaler trước PCA là best practice khi feature khác scale. Cross-validation phải fit pipeline trên fold train — không fit PCA riêng trên toàn X.
Giới hạn tái tạo
inverse_transform cho $\hat{\mathbf{X}} = \mathbf{Z}\mathbf{V}_k + \boldsymbol{\mu}$ — là projection ngược lên subspace $k$-chiều, không khôi phục hoàn hảo nếu bỏ PC. Dùng đánh giá reconstruction error: $|\mathbf{X} - \hat{\mathbf{X}}|_F^2$.
Code Python
Pipeline PCA + classifier trên Breast Cancer, so sánh accuracy có/không giảm chiều:
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
pipe_full = Pipeline([
("scaler", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
scores_full = cross_val_score(pipe_full, X, y, cv=cv, scoring="accuracy")
pipe_pca = Pipeline([
("scaler", StandardScaler()),
("pca", PCA(n_components=0.95)), # giữ 95% variance
("clf", LogisticRegression(max_iter=1000)),
])
scores_pca = cross_val_score(pipe_pca, X, y, cv=cv, scoring="accuracy")
# Inspect PCA sau fit trên toàn bộ (chỉ demo thuộc tính)
pipe_pca.fit(X, y)
pca_step = pipe_pca.named_steps["pca"]
print(f"n_components_ chosen: {pca_step.n_components_}")
print(f"Explained variance sum: {pca_step.explained_variance_ratio_.sum():.4f}")
print(f"Accuracy full features: {scores_full.mean():.4f} (+/- {scores_full.std():.4f})")
print(f"Accuracy with PCA: {scores_pca.mean():.4f} (+/- {scores_pca.std():.4f})")
# Reconstruction error demo
X_std = StandardScaler().fit_transform(X)
pca2 = PCA(n_components=2).fit(X_std)
X_proj = pca2.inverse_transform(pca2.transform(X_std))
mse = np.mean((X_std - X_proj) ** 2)
print(f"MSE reconstruction (2 PC): {mse:.4f}")
Breast Cancer có 30 features; PCA 95% thường giữ khoảng 10–17 PC — vẫn có thể giữ accuracy tương đương logistic regression.
Các tham số nâng cao
random_state: Dùng vớisvd_solver='arpack'hoặc'randomized'để reproducibility.iterated_power: Số lần lặp power method cho'randomized'— tăng nếu cần độ chính xác eigenvalue cao hơn.copy: Mặc địnhTrue— copy input khi center; đặtFalsenếu muốn tiết kiệm bộ nhớ và chấp nhận mutate array (cẩn thận trong Pipeline).
Visualization với Iris
Iris là dataset chuẩn để demo API:
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
X, y = load_iris(return_X_y=True)
pipe = Pipeline([
("scaler", StandardScaler()),
("pca", PCA(n_components=2)),
])
X2 = pipe.fit_transform(X)
plt.scatter(X2[:, 0], X2[:, 1], c=y)
plt.xlabel("PC1"); plt.ylabel("PC2")
plt.title("Iris — PCA 2D")
plt.savefig("iris_pca2.png")
Hai PC đầu thường tách Setosa khỏi hai species còn lại — minh họa trực quan vì sao PCA hữu ích cho EDA dù không dùng nhãn lúc fit.
Lỗi thường gặp
- Fit PCA trên test set: Chỉ
fittrên train;transformtest bằngcomponents_đã học. - Dùng
PCAkhông scale trên dữ liệu mixed units: Luôn cân nhắcStandardScalertrong Pipeline. n_components='mle'với solver sai: MLE yêu cầusvd_solver='full'— nếu không sẽ lỗi hoặc cảnh báo.- Kỳ vọng PCA luôn cải thiện accuracy: Giảm chiều có thể loại signal phân loại — đo bằng CV, không giả định.
Bài tập
- Thực hành: Trên Iris, thử
PCA(n_components=2)vàPCA(n_components=0.99). Inn_components_và vẽ scatter PC1–PC2 tô màu theo species. - So sánh: Dùng
cross_val_scorevớin_componentstừ 1 đến 4 trên Iris +KNeighborsClassifier(n_neighbors=3). PC nào cho accuracy cao nhất? - Đọc docs: Liệt kê 3 giá trị hợp lệ của
svd_solvervà khi nào sklearn chọn'randomized'tự động.
Tóm tắt
PCA sklearn cung cấp API nhất quán: fit học subspace, transform chiếu dữ liệu, explained_variance_ratio_ hỗ trợ chọn chiều. Kết hợp StandardScaler + Pipeline + cross-validation là workflow production-ready cho giảm chiều trước classification.
Tiếp tục lộ trình tại khóa Machine Learning cơ bản — bài tiếp theo: so sánh LDA và PCA.