Sub topic 3
Using PCA in scikit-learn
Assume you know basic Python, NumPy arrays, matrix multiplication, and feature scaling. In scikit-learn, PCA learns directions that preserve variance. Fit it on training data, then use the fitted object to transform new data.
Using PCA in scikit-learn
Scale features first when their units or ranges differ. Put scaling and PCA in a pipeline so both steps are applied consistently.
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
pipe = make_pipeline(StandardScaler(), PCA(n_components=2))
Z = pipe.fit_transform(X)
pca = pipe.named_steps["pca"]
print(Z.shape)
print(pca.explained_variance_ratio_)
print(pca.components_)Z contains two scores for each sample. explained_variance_ratio_ reports the fraction of standardized variance retained. The pipeline must be fitted only on training data when you evaluate a model.
PCA through the singular value decomposition
PCA can use the singular value decomposition (SVD), which factors the centered data matrix:
\[ X_c = U S V^T \]
The rows of Vt are principal directions. The covariance eigenvalues are:
\[ \lambdai = \frac{Si^2}{n-1} \]
import numpy as np
X = np.array([[1., 2.], [2., 3.], [4., 5.]])
mean = X.mean(axis=0)
Xc = X - mean
U, S, Vt = np.linalg.svd(Xc, full_matrices=False)
components = Vt[:1]
scores = Xc @ components.T
reconstructed = scores @ components + mean
print(scores)
print(reconstructed)The reconstruction keeps only one direction, so some information is lost.
Reading loadings and scores
A component’s loadings are its feature weights. Large absolute values indicate features that strongly influence that direction. A score tells where one sample lies along a component. Component signs are arbitrary: multiplying one component and all its scores by -1 changes no result.
Limitations and common pitfalls
- PCA is linear. It cannot represent curved structure well.
- High variance is not automatically useful variance.
- Unscaled features can dominate the result.
- Fit preprocessing on training data only.
- Missing values usually require imputation first.
- Outliers can rotate the components.
- Component labels do not prove causation.
Beyond plain PCA
Kernel PCA can capture selected nonlinear patterns. Sparse PCA encourages components that use fewer features, which can improve interpretability. Incremental PCA processes batches and suits data that does not fit in memory. Other nonlinear methods, such as UMAP or t-SNE, are mainly useful for visualization and do not preserve distances in the same way as PCA.
Exercise
Why should a scaler and PCA be fitted inside a training pipeline?
Show answer
To learn means, scales, and components from training data only, preventing information from the test set leaking into the model.