Kernel PCA
Kernel PCA finds curved patterns that ordinary PCA cannot see, by measuring similarity between points instead of rotating axes.
- 7 min read
- 3 reading levels
- Published
Read these first
On this page 5
One lesson, three depths. Pick the one that fits you today — you can switch any time.
Beginner — No maths. Plain English.
Kernel PCA is PCA for curved patterns — it can unroll shapes that no straight viewpoint reveals.
Think of a design printed on a rolled-up carpet. However you turn the roll and however you light it, no shadow on the wall shows you the design — the pattern lives along the curl. To see it, you cannot rotate; you must unroll.
Ordinary PCA can only rotate. It searches every straight viewpoint for the most informative one. If your data's pattern is a spiral, a ring, or a rolled sheet, every straight viewpoint is equally useless. Kernel PCA is the unrolling machine.
Why it exists
Real data curves. Points recorded from a turning wheel trace a circle. Sensor readings across a day trace loops. A ring of "risky" customers can surround a core of "safe" ones. In each case, the meaningful coordinate is position along the curve — something no straight axis measures.
The fix sounds extravagant: invent extra dimensions. A ring drawn flat cannot be split by a straight line. But lift each point upward by its distance from the centre. The inner ring now floats above the outer one. A flat sheet of paper separates them. Curved-in-few-dimensions becomes straight-in-more-dimensions.
How it works
The expensive part would be actually computing those extra dimensions. The kernel trick skips it. A kernel is a formula giving the similarity between two points as if they had been lifted into the richer space — without ever building it. Kernel PCA runs PCA using only that table of similarities.
flat view: o o o o o lifted view: inner ring
o x x o ● ● ● <- floats up
o x x o ────────> ____________
o x x o lift by o o o o o o <- outer
o o o o o centre-dist stays lowA real example you have seen
A city's metro map versus its road map. Distance "as the crow flies" (straight-line thinking) says two stations across a river are close. The realistic notion — travel time — says they are far. A kernel is a chosen notion of "realistically similar", and kernel PCA organises your data by that notion instead of by raw straight-line position.
Remember this
- PCA rotates; kernel PCA effectively unrolls.
- A kernel measures similarity as if the data lived in a richer space, never built.
- Use it when the pattern you care about is a curve, ring or roll.
What to learn next
- t-SNE — nonlinear reduction built specifically for visualisation.
- Truncated SVD and LSA — back to linear, but for sparse text matrices.
- Autoencoders — learning the lift instead of choosing a kernel.
Developer — Code and libraries.
Setup
pip install scikit-learnOutputs verified with scikit-learn 1.7.2.
A ring inside a ring
make_circles creates the classic PCA-killer: one class encircling the other. We score each representation by whether a straight line can separate the classes in it.
from sklearn.datasets import make_circles
from sklearn.decomposition import PCA, KernelPCA
from sklearn.linear_model import LogisticRegression
# a ring inside a ring -- no straight line separates them
X, y = make_circles(n_samples=400, factor=0.3, noise=0.05, random_state=0)
def line_score(Z, y):
"""How well a straight line separates the classes in this space."""
return LogisticRegression().fit(Z, y).score(Z, y)
print(f"original 2-D space: {line_score(X, y):.2f}")
Z_pca = PCA(n_components=2).fit_transform(X)
print(f"after ordinary PCA: {line_score(Z_pca, y):.2f}")
Z_kpca = KernelPCA(n_components=2, kernel="rbf", gamma=4).fit_transform(X)
print(f"after kernel PCA (rbf): {line_score(Z_kpca, y):.2f}")original 2-D space: 0.50 after ordinary PCA: 0.50 after kernel PCA (rbf): 1.00
The walkthrough
0.50 is a coin flip. In the original space, the best straight line gets half the points right — the rings are concentric, so every line cuts both. Ordinary PCA "helps" by rotating a circle, which changes nothing: still 0.50. Kernel PCA's output is perfectly separable: 1.00.
kernel="rbf" is the radial basis function kernel — similarity decays smoothly with distance, like the warmth of a fire fading as you step away. It is the default choice for "I know it curves, I do not know how". Polynomial and cosine kernels suit other shapes.
gamma is the zoom knob, and it is the parameter that decides success. It sets how fast similarity fades with distance. Too small and everything looks similar — the unrolling flattens nothing. Too large and only immediate neighbours look similar — the data shatters into confetti. There is no formula; tune it. A reasonable starting range is 0.1 to 10 on standardised data, searched on a log scale.
No labels were used in the unrolling. line_score uses labels only to measure the spaces. Kernel PCA itself is unsupervised, like PCA — it found the ring structure on its own.
Common mistakes
Leaving gamma at the default and concluding kernel PCA is useless. The default (1/n_features) is a placeholder, not a recommendation. On this same dataset, gamma=0.01 scores 0.50 — indistinguishable from failure. Sweep it before judging.
Running it on big datasets without thinking. Kernel PCA builds the full similarity table: all pairs of points. 50,000 rows means 2.5 billion entries — memory death long before the maths finishes. Past roughly 10,000 rows, use the Nystroem approximation (sklearn.kernel_approximation.Nystroem) followed by ordinary PCA.
Expecting a clean reverse mapping. PCA can reconstruct originals from components. Kernel PCA's components live in the never-built lifted space, and mapping back (fit_inverse_transform=True) is approximate — a fitted model, not an inversion. Reconstructions can be poor even when the embedding is excellent.
Skipping scaling. The RBF kernel measures distance, and unscaled columns distort distance exactly as they did for k-NN. Standardise first.
Try it yourself
Sweep gamma through 0.01, 0.1, 1, 4, 20, 100, printing the line score for each. Find the plateau of good values, then explain the failures at both ends using the zoom-knob picture.
What to learn next
- t-SNE — nonlinear reduction built specifically for visualisation.
- Truncated SVD and LSA — back to linear, but for sparse text matrices.
- Autoencoders — learning the lift instead of choosing a kernel.
Researcher — Mathematics and papers.
The construction
Scholkopf, Smola and Muller (1998), Nonlinear component analysis as a kernel eigenvalue problem, Neural Computation. Given a feature map phi: R^d -> H into a reproducing-kernel Hilbert space with kernel k(x, x') = <phi(x), phi(x')>, PCA in H requires eigenvectors of the covariance of phi(x_i) — an object we cannot form. But each eigenvector lies in the span of the mapped data, v = sum_i alpha_i phi(x_i), which converts the problem to the n x n kernel (Gram) matrix K_ij = k(x_i, x_j):
K alpha = n lambda alpha
Component scores of x are then sum_i alpha_i k(x_i, x). Centring in feature space is done on K directly: K_c = K - 1_n K - K 1_n + 1_n K 1_n, with 1_n the matrix of 1/n entries — forgetting this step is a classic implementation bug.
Costs and the honest trade
Building K costs O(n^2 d); the eigendecomposition O(n^3); storing K, O(n^2). Compare PCA's O(n d^2 + d^3): kernel PCA swaps dependence on dimension for dependence on sample count, which is a catastrophe for large n. Nystroem approximation (Williams and Seeger, 2001) samples m landmark points and approximates K at rank m for O(n m d + m^3) — with m in the hundreds this converts kernel PCA into "random features, then linear PCA". Random Fourier features (Rahimi and Recht, 2007) achieve the same via explicit randomised feature maps for shift-invariant kernels.
The pre-image problem
Reconstruction requires finding z in R^d with phi(z) closest to a given point in H — the pre-image problem. Exact pre-images generally do not exist (H is infinite-dimensional for RBF), so one solves a nonlinear least-squares problem (Mika et al., 1999) or fits a regression from components back to inputs (Bakir et al., 2004) — the latter is sklearn's fit_inverse_transform. Denoising applications live or die on this step.
Placement in the family
Kernel PCA with specific kernels reproduces or approximates several classical embeddings: metric MDS (with a centred distance-derived kernel), Isomap (geodesic-distance kernel), and spectral clustering's embedding (normalised graph Laplacian eigenvectors). Ham et al. (2004) give the unifying view: most "manifold learning" is kernel PCA with a data-dependent kernel. Its practical successors for visualisation are t-SNE and UMAP; its supervised cousin is the kernel SVM; its scalable descendant is the autoencoder.
What to learn next
- t-SNE — nonlinear reduction built specifically for visualisation.
- Truncated SVD and LSA — back to linear, but for sparse text matrices.
- Autoencoders — learning the lift instead of choosing a kernel.