Sau khi biết PCA là gì, bước tiếp theo là hiểu cách trích xuất từng Principal Component — không chỉ công thức mà cả hình học trong không gian đặc trưng. Bài này theo Chương 5 Python Machine Learning — phần extracting principal components, bổ sung góc nhìn SVD mà sklearn sử dụng nội bộ.
Mục tiêu
- Hiểu hình học: PC là trục của ellipsoid phương sai dữ liệu.
- Trích xuất eigenvector từ ma trận hiệp phương sai và liên hệ với SVD.
- Đọc được
components_,explained_variance_trong sklearn sau khi fit.
Lý thuyết
Hình học của Principal Components
Hình dạng đám mây dữ liệu centered thường giống ellipsoid trong $\mathbb{R}^d$. Trục dài nhất của ellipsoid trùng với PC1 — hướng dữ liệu "trải dài" nhiều nhất. PC2 vuông góc PC1, là trục dài tiếp theo trong mặt phẳng vuông góc PC1. Các PC luôn pairwise orthogonal vì eigenvector của ma trận hiệp phương sai (đối xứng) tương ứng eigenvalue khác nhau là ortogonal.
Eigen decomposition
Ma trận hiệp phương sai $\mathbf{S}$ là đối xứng, positive semi-definite. Phân tích:
$$\mathbf{S} = \mathbf{V}\mathbf{\Lambda}\mathbf{V}^T$$
- $\mathbf{V} = [\mathbf{v}_1, \ldots, \mathbf{v}_d]$: cột là eigenvector (principal axes).
- $\mathbf{\Lambda} = \text{diag}(\lambda_1, \ldots, \lambda_d)$: eigenvalue sắp giảm dần.
Mỗi $\mathbf{v}_i$ là một principal component (hướng). Hệ số chiếu của mẫu $\mathbf{x}$ lên PC $i$: $z_i = \mathbf{x}^T \mathbf{v}_i$.
SVD — cách sklearn thực hiện
Với $\mathbf{X}_{\text{centered}}$ kích thước $n \times d$, sklearn dùng SVD:
$$\mathbf{X} = \mathbf{U}\mathbf{\Sigma}\mathbf{V}^T$$
Cột của $\mathbf{V}$ (hoặc hàng của $\mathbf{V}^T$ tùy convention) là PC. Eigenvalue của hiệp phương sai liên hệ: $\lambda_i = \sigma_i^2 / (n-1)$ với $\sigma_i$ là singular value. SVD ổn định số học hơn khi $n \gg d$ hoặc ngược lại.
Tham số svd_solver trong PCA: 'auto', 'full', 'arpack', 'randomized' — ảnh hưởng tốc độ và bộ nhớ với dữ liệu lớn.
Loadings và interpretation
Vector $\mathbf{v}_i$ cho biết trọng số mỗi feature gốc đóng góp vào PC $i$. Ví dụ trên Iris, PC1 thường có loading đồng dấu trên petal length và petal width — phản ánh correlation giữa hai đặc trưng cánh hoa. Loadings không phải hệ số hồi quy; chúng mô tả hướng trong không gian gốc.
Số chiều và rank
Số PC tối đa là $\min(n-1, d)$. Nếu dữ liệu nằm trên subspace rank-deficient (ví dụ feature dư thừa), một số eigenvalue $\approx 0$ — có thể bỏ an toàn.
Whitening (tùy chọn)
Sau PCA, có thể chia $z_i$ cho $\sqrt{\lambda_i}$ để mỗi PC có phương sai đơn vị — tham số whiten=True trong sklearn. Hữu ích cho một số pipeline (ví dụ trước clustering) nhưng thay đổi scale so với PC thuần.
Code Python
Trích PC từ Wine dataset, so sánh eigen approach và truy cập thuộc tính sklearn:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_wine
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
X, y = load_wine(return_X_y=True)
X_std = StandardScaler().fit_transform(X)
# Eigen-based extraction
cov = np.cov(X_std.T)
eigenvalues, eigenvectors = np.linalg.eigh(cov)
order = np.argsort(eigenvalues)[::-1]
eigenvalues = eigenvalues[order]
eigenvectors = eigenvectors[:, order]
pca = PCA(n_components=X_std.shape[1])
X_transformed = pca.fit_transform(X_std)
print("Eigenvalues (manual):", eigenvalues[:5])
print("Explained variance (sklearn):", pca.explained_variance_[:5])
print("Shape components_:", pca.components_.shape) # (n_components, n_features)
# Loadings PC1
pc1_loadings = pca.components_[0]
top_features = np.argsort(np.abs(pc1_loadings))[::-1][:3]
feature_names = load_wine().feature_names
print("Top features on PC1:", [feature_names[i] for i in top_features])
# Scree plot
plt.figure(figsize=(6, 4))
plt.bar(range(1, len(eigenvalues) + 1), eigenvalues)
plt.xlabel("Principal Component")
plt.ylabel("Eigenvalue")
plt.title("Scree plot — Wine dataset")
plt.tight_layout()
plt.savefig("scree_wine.png", dpi=100)
print("Đã lưu scree_wine.png")
pca.components_[i] là vector hàng thứ $i$ — hướng PC trong không gian feature đã chuẩn hóa.
Lỗi thường gặp
- Nhầm chiều của
components_: Trong sklearn, mỗi hàng là một PC; không transpose nhầm khi nhân tay với $\mathbf{X}$. - Dùng
np.linalg.eigthay vìeigh: Ma trận hiệp phương sai đối xứng —eighnhanh hơn và tránh eigenvalue ảo nhỏ do sai số số học. - Quên center data trước khi tính cov: PCA yêu cầu dữ liệu centered; sklearn tự center khi
fit, nhưng code NumPy thủ công phải trừ mean. - Giải thích PC như feature gốc: PC là tổ hợp tuyến tính — không thể nói "PC1 = alcohol" đơn thuần mà phải xem loadings.
Bài tập
- Tự luận: Chứng minh ngắn gọn rằng PC1 là hướng tối đa hóa $\mathbf{w}^T\mathbf{S}\mathbf{w}$ với $|\mathbf{w}|=1$. Gợi ý: dùng Lagrange multiplier.
- Thực hành: Với Breast Cancer (
load_breast_cancer), fit PCA full rank. Bao nhiêu PC cần để explained variance cumulative $\geq 0.99$? - Mở rộng: Thử
PCA(svd_solver='randomized', n_components=10)trên Wine. So sánh thời gian vàexplained_variance_ratio_vớisvd_solver='full'.
Tóm tắt
Principal Component Analysis ở bước trích xuất là tìm eigenvector (hoặc right singular vector) của dữ liệu centered — mỗi vector là một trục ortogonal, sắp theo phương sai giảm dần. Hiểu SVD và thuộc tính components_, explained_variance_ giúp bạn debug pipeline và diễn giải kết quả đúng cách.
Tiếp tục lộ trình tại khóa Machine Learning cơ bản — bài tiếp theo: PCA trong scikit-learn API đầy đủ.