Huấn luyện PCA trên tập train chỉ là nửa chặng đường — production cần chiếu điểm mới (inference) bằng cùng subspace đã học. Bài này theo Chương 5 Python Machine Learning — phần projecting new points, tập trung transform, công thức toán và workflow deploy.
Mục tiêu
- Phân biệt
fit,transform,fit_transformvà khi nào dùng từng cái. - Viết công thức chiếu điểm mới lên PC đã fit.
- Triển khai đúng train/test split và serialize Pipeline.
Lý thuyết
Công thức transform
Sau khi pca.fit(X_train), sklearn lưu:
mean_: vector trung bình từng feature (trên train).components_: ma trận $k \times d$ — mỗi hàng là một PC (đơn vị, ortogonal).
Điểm mới $\mathbf{x}$ (shape $d$):
$$\mathbf{z} = (\mathbf{x} - \boldsymbol{\mu})^T \mathbf{V}^T = \text{pca.transform}(\mathbf{x})$$
Output $\mathbf{z} \in \mathbb{R}^k$. Không gọi lại fit trên điểm mới — dùng $\boldsymbol{\mu}$ và $\mathbf{V}$ cố định từ train.
fit_transform vs transform
| Hàm | Dùng khi |
|---|---|
fit_transform(X_train) |
Học subspace + chiếu train (chỉ trên train!) |
transform(X_test) |
Chiếu test/new bằng subspace đã học |
fit(X_new) |
Sai nếu $X_new$ là test — học lại PC, leakage |
Nếu dùng StandardScaler trước PCA:
scaler.fit(X_train)
X_train_std = scaler.transform(X_train)
pca.fit(X_train_std)
X_test_std = scaler.transform(X_test) # mean/std từ train
X_test_pca = pca.transform(X_test_std) # components từ train
Out-of-sample và reconstruction
- Transform: Chiếu xuống subspace $k$-chiều — luôn định nghĩa được.
- Inverse transform: $\hat{\mathbf{x}} = \mathbf{z} \mathbf{V} + \boldsymbol{\mu}$ — xấp xỉ nếu $k < d$.
- Điểm mới rất xa training cloud có thể có projection atypical — monitor reconstruction error trong production.
Kernel PCA — transform phức tạp hơn
Kernel PCA lưu training data (hoặc representation) để tính $k(\mathbf{x}_{\text{new}}, \mathbf{x}i)$. Transform điểm mới = kernel vector với all training points × eigenvectors. Chi phí inference $O(n{\text{train}} \cdot k)$ — khác PCA tuyến tính $O(d \cdot k)$.
Serialize cho deploy
Lưu cả Pipeline([("scaler", ...), ("pca", ...)]) bằng joblib.dump — inference:
pipe = joblib.load("pca_pipeline.joblib")
z_new = pipe.transform(x_new.reshape(1, -1))
Một object đảm bảo cùng thứ tự scale + PCA.
Tài liệu: PCA.transform và Transformers API.
Code Python
Train/test split trên Breast Cancer — demo transform đúng cách:
import numpy as np
import joblib
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
pipe = Pipeline([
("scaler", StandardScaler()),
("pca", PCA(n_components=0.95)),
("clf", LogisticRegression(max_iter=2000)),
])
# Chỉ fit trên train
pipe.fit(X_train, y_train)
# Transform / predict điểm mới (test)
X_test_pca = pipe.named_steps["pca"].transform(
pipe.named_steps["scaler"].transform(X_test)
)
y_pred = pipe.predict(X_test)
acc = accuracy_score(y_test, y_pred)
print(f"Test accuracy: {acc:.4f}")
print(f"X_test_pca shape: {X_test_pca.shape}")
print(f"n_components_: {pipe.named_steps['pca'].n_components_}")
# Một điểm mới giả lập
x_new = X_test[0:1]
z_new = pipe[:-1].transform(x_new) # scale + PCA, không qua clf
print(f"Single point projection shape: {z_new.shape}")
# Serialize
joblib.dump(pipe, "/tmp/breast_cancer_pca_pipe.joblib")
pipe_loaded = joblib.load("/tmp/breast_cancer_pca_pipe.joblib")
assert np.allclose(z_new, pipe_loaded[:-1].transform(x_new))
print("Serialize + transform OK")
Đoạn pipe[:-1].transform minh họa transform feature trước classifier — pattern phổ biến khi export embedding.
Lỗi thường gặp
pca.fit(X_train)rồipca.transform(X_train)thay vì dùng transform cho test only: Không sai nhưng dễ nhầm — nhớ test dùngtransformonly.- Fit scaler trên train+test: Mean/std lẫn test → leakage nhẹ; fit scaler chỉ train.
- Chiều input sai khi transform: Điểm mới phải cùng $d$ features, cùng thứ tự cột như lúc fit.
- Refit PCA định kỳ trên production stream mà không versioning: PC drift — cần chiến lược retrain có kiểm soát.
Bài tập
- Tự luận: Viết công thức transform từng bước khi Pipeline có
StandardScaler→PCA(2)→SVM. Chỉ rõ object nào fit trên train. - Thực hành: Wine dataset — fit PCA(3) trên 80% train. Transform 20% test và vẽ 3D scatter tô màu class. So sánh với
fit_transformtrên toàn bộ Wine (minh họa leakage khác biệt). - Deploy: Lưu Pipeline Iris bằng joblib, load lại, transform 5 hoa mới từ
X[-5:]. In khoảng cách Euclidean giữa projection manual và pipeline.
Tóm tắt
Chiếu điểm mới sau PCA = trừ mean_ đã học, nhân với components_ — qua transform, không fit lại. Kết hợp scaler: transform scaler trước, PCA sau. Pipeline + joblib là cách deploy an toàn, tránh leakage và đảm bảo reproducibility.
Tiếp tục lộ trình tại khóa Machine Learning cơ bản — bài cuối chương: tổng hợp dimensionality reduction và Kernel PCA sklearn.