Sub topic 14
Beyond plain PCA: kernel, sparse, incremental and nonlinear methods
This chapter assumes you have read the earlier chapters on PCA. You should know that PCA finds directions of maximum variance in centered data and that it can be computed from the covariance matrix or the SVD. You should also be comfortable with scikit-learn estimators (fit, transform, pipelines).
Plain PCA is linear, dense, and needs all the data in memory. Each variant below drops one of those limits. Each also gives up something in return: speed, simplicity, an exact inverse, or a stable result. The goal is to recognize which limit you have hit and pick the smallest change that fixes it.
Which limit are you hitting?
Start from the symptom, not the method name.
Kernel PCA: curved structure
Linear PCA can only rotate and drop axes. If classes lie on concentric circles, no straight direction separates them, so the first component mixes both circles.
Kernel PCA applies PCA in a higher-dimensional feature space without building that space. It uses a kernel function k(x, x'), which returns the inner product of two points after an implicit mapping. The algorithm builds the n x n kernel matrix, centers it in feature space, and takes its top eigenvectors. Each eigenvector gives the scores of the training points on one nonlinear component.
The next example compares linear PCA and an RBF kernel on two noisy circles. Each reduces the data to one component, and a classifier then tries to separate the classes.
from sklearn.datasets import make_circles
from sklearn.decomposition import PCA, KernelPCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
X, y = make_circles(n_samples=400, factor=0.3, noise=0.05, random_state=0)
linear = make_pipeline(PCA(n_components=1), LogisticRegression())
kernel = make_pipeline(
KernelPCA(n_components=1, kernel="rbf", gamma=5.0),
LogisticRegression(),
)
print("linear PCA accuracy:", cross_val_score(linear, X, y, cv=5).mean())
print("kernel PCA accuracy:", cross_val_score(kernel, X, y, cv=5).mean())Linear PCA scores near chance because the circles are centered on the same point. The RBF version scores close to 1.0 because the radius becomes the leading nonlinear direction.
Costs and gotchas of kernel PCA
- Memory and time grow with the number of samples. The kernel matrix is
n x n, and the eigendecomposition costs roughlyO(n^3)for the dense solver. Plain PCA scales with the number of features instead. Kernel PCA becomes painful beyond a few tens of thousands of rows. - Hyperparameters matter. For the RBF kernel,
gammacontrols how local the similarity is. Too large and every point is only similar to itself. Too small and the result approaches linear PCA. There is no explained-variance rule to tune it against. Use a downstream metric or reconstruction error. - There is no exact inverse. Mapping a score back to the original space is a pre-image problem. Scikit-learn approximates it with ridge regression when you set
fit_inverse_transform=True. Treat the result as an approximation. - Components have no loadings. The axes live in the implicit feature space, so there is no weight per original feature to read.
- Scaling still applies. An RBF kernel uses distances, so unscaled features dominate it just as they dominate covariance.
Sparse PCA: readable components
In plain PCA every component is a weighted sum of all features. With 5,000 genes or 20,000 words, a component with 5,000 small non-zero weights is hard to interpret.
Sparse PCA adds an L1 penalty on the component weights, as in the lasso. Many weights become exactly zero, so each component involves a handful of features. The strength of the penalty is set by alpha.
from sklearn.datasets import load_iris
from sklearn.decomposition import SparsePCA
from sklearn.preprocessing import StandardScaler
X, _ = load_iris(return_X_y=True)
X_std = StandardScaler().fit_transform(X)
sparse = SparsePCA(n_components=2, alpha=1.0, random_state=0)
scores = sparse.fit_transform(X_std)
print(sparse.components_.round(2))
print("zero weights:", (sparse.components_ == 0).sum())Try alpha=0.1 and then alpha=3.0. Small values give dense components that resemble PCA. Large values zero out more weights and can zero out an entire component.
Know these trade-offs before using it:
- Sparse components are not orthogonal and are not ordered by variance. The explained-variance ratios from plain PCA do not carry over.
- The optimization is not a single eigendecomposition. It is slower, and results depend on
alphaand on the solver's starting point. - You gain interpretability and lose some variance captured per component.
Incremental PCA: data that does not fit in memory
Plain PCA needs the whole centered matrix, or at least its covariance matrix, at once. IncrementalPCA processes the data in batches. It keeps a running mean and a compact SVD summary, and updates both with each batch.
import numpy as np
from sklearn.decomposition import IncrementalPCA
rng = np.random.default_rng(0)
ipca = IncrementalPCA(n_components=5)
for _ in range(10):
batch = rng.normal(size=(500, 50))
ipca.partial_fit(batch)
print(ipca.n_samples_seen_)
print(ipca.explained_variance_ratio_)
new_batch = rng.normal(size=(100, 50))
print(ipca.transform(new_batch).shape)Every batch must contain at least n_components rows. If your data lives in a file, fit also accepts a batch_size argument and works through a memory-mapped array such as np.load(..., mmap_mode="r").
The result is close to plain PCA, but not identical, and the approximation can drift when early batches are not representative. Shuffle rows before batching if the file is sorted. Incremental PCA also helps when data arrives as a stream and you want to update the projection over time.
If the data fits in memory but is large, you may not need incremental PCA. PCA(svd_solver="randomized") computes only the top components using random projections. It is usually much faster when n_components is far smaller than the number of features.
TruncatedSVD: sparse input
PCA centers the data. Subtracting the mean from a sparse matrix makes it dense, which can exhaust memory for something like a document-term matrix with 100,000 columns. TruncatedSVD skips centering and runs SVD directly on the sparse matrix.
import scipy.sparse as sp
from sklearn.decomposition import TruncatedSVD
X = sp.random(2000, 10000, density=0.01, format="csr", random_state=0)
svd = TruncatedSVD(n_components=20, random_state=0)
Z = svd.fit_transform(X)
print(Z.shape)
print(svd.explained_variance_ratio_[:5])Without centering, the first component often just tracks the overall magnitude or mean of the rows. The directions are not directions of maximum variance, so do not describe them that way. On text this method is known as latent semantic analysis (LSA).
Nonlinear and manifold methods
Some data lies on a curved surface (a manifold) inside a high-dimensional space. Several methods try to unfold it.
| Method | Idea | Main use | Main caveat |
|---|---|---|---|
| Isomap | Preserve geodesic distances along a neighbor graph | Smooth manifolds | Breaks if the graph has shortcuts or gaps |
| t-SNE | Preserve local neighbor probabilities | 2D or 3D visualization | Distances between clusters and cluster sizes are not meaningful. Results vary with `perplexity` and the seed. No `transform` for new points. |
| UMAP | Similar goal built on a fuzzy neighbor graph | Visualization and general embedding | Separate package (`umap-learn`). Sensitive to `n_neighbors` and `min_dist`. |
| Autoencoder | Neural network that compresses and reconstructs | Large data, flexible nonlinear codes | Needs training, tuning and a validation set. A linear autoencoder recovers the PCA subspace. |
Two practical points apply to all of these. First, they do not give you an explained-variance ratio, so choosing the number of dimensions is a judgment call. Second, a common workflow is to run PCA first, down to 30 to 50 components, to remove noise and cut cost, and then run t-SNE or UMAP on the result.
Choosing between them
Prefer the plainest method that solves your actual problem.
- If the data fits in memory and the structure is roughly linear, use
PCA, with the randomized solver if it is large. - If the data does not fit in memory, use
IncrementalPCA. - If the matrix is sparse and centering would densify it, use
TruncatedSVD. - If you must explain components in terms of a few original features, try
SparsePCA. - If a linear projection demonstrably fails (a downstream model scores poorly, reconstruction error stays high with many components), try
KernelPCAor a manifold method.
Whichever you choose, evaluate it on a task or a reconstruction metric on held-out data, and fit the reducer inside a pipeline so that test data does not leak into the fit.
Exercise
You have a 500,000 x 200,000 document-term matrix stored as a SciPy sparse matrix with 0.1% non-zero entries. You want 100 dimensions for a downstream classifier. Why is PCA a poor first choice here, and which estimator would you use instead? Name one thing you lose by switching.
Show answer
PCA subtracts the column means, which turns the sparse matrix into a dense one with 500,000 x 200,000 entries (about 800 GB as float64), so it does not fit in memory. Use TruncatedSVD(n_components=100), which works on the sparse matrix directly without centering. What you lose is exact PCA semantics: because the data is not centered, the components are not directions of maximum variance, and the first one often just reflects the overall size of the rows.
Exercise
A colleague fits KernelPCA(kernel="rbf", gamma=50) on 80,000 samples and the job runs out of memory. Explain why, and give two options to fix it.
Show answer
Kernel PCA builds an n x n kernel matrix, so 80,000 samples need 6.4 billion entries (about 51 GB as float64) before the eigendecomposition. Options: fit on a random subsample of the rows (for example a few thousand) and transform the rest; use an approximation such as Nystroem kernel approximation followed by ordinary PCA or a linear model; or switch to a method whose cost does not grow with n squared, such as an autoencoder or plain PCA if the structure is nearly linear.