Motivation
Ordinary PCA finds linear directions in the measured features. A curved pattern may become easier to describe after a nonlinear feature map: a scalar measurement can, for example, contribute both its value and its square. Applying PCA to those features gives coordinates that are nonlinear functions of the original measurement. Kernel PCA performs this calculation through inner products, so the transformed features need not be explicitly stored.
The important changes are mathematical rather than procedural. Centering now takes place in feature space. An eigenvector of the observation-by-observation Gram matrix is not itself a unit principal direction in that space. Finally, a new observation must be measured relative to the same feature mean as the training observations. Deriving these three facts gives a complete projection rule, including its normalization and every mean term.
Definitions
Let , with , be training observations. As in ordinary PCA, observations occupy rows. A feature map sends each observation into an inner-product space. When this space has finite dimension , write with row equal to . The formulas using finite sums of feature vectors also apply when the feature space has infinitely many dimensions.
Definition 2.3.1
(Kernel and Gram matrix)
A kernel computes feature inner products:
Thus in the finite-dimensional case. A positive semidefinite kernel is a symmetric function for which every finite Gram matrix satisfies for all real coefficient vectors .
The matrix compares observations; acts on feature directions. These are different matrices, although their positive eigenvalues agree. Working with is attractive when the feature space is much larger than the number of observations. Its entries describe similarities through the chosen feature geometry, rather than arbitrary resemblance scores.
Two standard choices, with parameters that preserve positive semidefiniteness, are the Gaussian radial basis kernel and the polynomial kernel:
For the polynomial kernel, expansion expresses the function as a sum of inner products of monomial features with nonnegative weights. The Gaussian kernel can be written as a positive factor depending on , a positive factor depending on , and . The exponential series is a sum of nonnegative multiples of polynomial inner-product kernels. This explains why the squared distance and the parameter sign matter. Positive semidefiniteness concerns quadratic forms; individual kernel entries can be negative, as they can for an ordinary linear inner product.
Definition 2.3.2
(Centered features and centered kernel)
Define the training-feature mean and centering matrix by
The centered Gram matrix has entries . Here always subtracts the training mean, including when is a new observation.
For a nonlinear feature map, centering the raw observations does not generally center the features. The mean of a square, for example, is not the square of the mean. Kernel centering is therefore required even if each original feature column already has mean zero.
Theorem and proposition
Theorem 2.3.3
(Feature centering gives a positive semidefinite centered Gram matrix)
The centered Gram matrix is
It is symmetric positive semidefinite, , and .
If , then . The corresponding sample covariance in feature space is . If a positive Gram eigenvalue is , the associated covariance eigenvalue is . Consequently, explained variance fractions are ratios of the positive themselves. These eigenvalues already equal squared singular values; squaring them again would change the variance criterion.
Theorem 2.3.4
(Unit principal directions and projection scores)
Suppose , with and . Choose the orthonormally. Then
define orthonormal principal directions in feature space. For a training observation, its score on component is
For any new observation , form . Its component score is .
The loading direction , Gram eigenvector , and coefficient vector have different meanings. The last two both have entries, but their normalizations differ. A unit Euclidean norm for becomes a unit feature-space norm for only after division by .
A finite eigenproblem for nonlinear features
The principal direction solves the same variance problem as before, now in feature space:
Write for the empirical feature-space covariance operator. Every direction perpendicular to the span of the centered training features has zero score on every training observation. It therefore contributes zero training variance. Every principal direction corresponding to a positive covariance eigenvalue lies in this span, whose dimension is at most : if with , then belongs to the range of , which is contained in that span. A direction outside the span can still have positive variance through its component within it. If every centered feature is zero, the span is and there are no positive-variance principal components; we do not choose a unit vector in the zero space. This is the reason a finite Gram matrix suffices even for an infinite-dimensional feature map: the eigenproblem describes the part of feature space supported by the training observations. The nonlinear map changes that space's geometry, while the PCA step remains an orthogonal linear projection inside it.
Order the positive eigenvalues as , where , and take an integer . The first directions then capture the largest available energies. If , the total centered energy is zero: there are no positive components and an explained-variance fraction is undefined, since its denominator would be zero.
For a retained number of components , the total squared reconstruction error of the centered training features is
The trace adds the squared lengths of the centered feature vectors, and the retained eigenvalues add the energy captured by their orthogonal projections. Dividing this energy by converts it to sample variance. Ratios do not need that division because the same factor appears in numerator and denominator. Retaining all positive components reproduces the training features exactly, even though the feature map may have many more coordinates.
This reconstruction is a feature-space statement. A projected feature vector need not equal for any original input , since a nonlinear map's image need not be a linear subspace. Kernel PCA supplies coordinates and an optimal feature-space projection; converting that projection back to an original measurement is a further problem. Its reconstruction error should therefore be interpreted in the kernel's geometry, rather than automatically as squared error in the original measured variables.
Kernel PCA also determines a distance geometry. The distance between two feature vectors follows from the two diagonal Gram entries and their pairwise inner product. Subtracting a shared mean leaves pairwise differences unchanged, so centering changes the coordinate origin without changing those feature-space distances. The choice of kernel introduces the nonlinear geometry; centering then positions that geometry around its training mean before the projection selects its dominant directions.
Proof sketch or proof idea
Proof
(Deriving centering and normalization)
Expand . The four terms are the raw kernel entry, two training averages, and the training grand average. Collecting them in matrix form gives . Alternatively, immediately gives . For any , . Since and has rank , the null-vector and rank claims follow.
Next,
This equals one when and zero otherwise. Multiplying gives , proving the training-score formula. The covariance operator applied to gives , so these are precisely feature-space PCA directions.
Proof X-ray
Feature-space lengths become eigenvalue arithmetic
Every statement about feature-space vectors is turned into a statement about : a combination has squared length . The eigen-equation then does the work. For a unit eigenvector with , this squared length is , which explains the division by . The positivity hypothesis is essential: if , the same identity shows that is the zero vector, so it gives no direction to normalize.
For the new-observation rule, define the fixed training row means, grand mean, and raw kernel vector by
Expanding the centered feature inner product gives
The new vector's average appears because it computes using the existing training mean. It does not add the new observation to the training set or recompute that mean. Saving the training observations, , , and the normalized coefficient vectors is enough to apply the same projection later.
Positive-eigenvalue eigenvectors have zero sum. Indeed, , so . This can simplify the score calculation: terms constant over the training index disappear when dotted with . The projection may thus also be written as
The stored row means remain essential. Their contribution is not generally constant across observations, and zero-sum coefficients do not remove it. The full four-term formula remains useful for constructing and interpreting the centered kernel vector itself.
Worked examples
Worked example 2.3.5
(1. Raw centering does not center nonlinear features)
Take scalar observations , , , and . Their raw mean is zero, but
The kernel is . Computing it without storing features gives
Each row of sums to zero. Direct multiplication of gives the same entries. Leaving the raw scalar data unchanged because its mean is zero would leave the square feature with mean ; it would solve an uncentered feature-space problem.
This simple map separates two nonlinear effects. The first feature preserves the sign of the scalar, while the second records its squared magnitude. The observations at minus one and one agree in the second feature even though they differ in the first. Kernel PCA can find variation along both of these feature directions, using only the pairwise values in the displayed Gram matrix.
Worked example 2.3.6
(2. Eigenvalues, normalized coefficients, and training scores)
For the centered matrix above, orthonormal eigenvectors can be chosen as
The remaining eigenvalue is zero, with eigenvector . Dividing by the square roots of the positive eigenvalues gives
The columns of are and . In the explicit feature space, and , confirming unit directions. Sample score variances are and because . The first component explains of feature-space variation. Its discarded squared reconstruction error in feature space is .
The eigenvalues of the centered Gram matrix are already nonnegative energies. They correspond to in the SVD of the centered feature table. This is why ordinary PCA's squared-singular-value formula becomes an unsquared Gram-eigenvalue formula. The two methods agree exactly when the same explicit features and the same centering are used.
Worked example 2.3.7
(3. Projecting a new observation with the training mean)
Keep the same three training observations and consider . The raw kernel vector, stored row means, and stored grand mean are
The new vector's average is . Thus
For example, . The explicit centered feature vector is also . This independently checks both coordinates. Including the new point when recomputing the mean would instead change the fitted feature space coordinates for every observation.
Computing the projection
The following code uses only the kernel formula, then compares the magnitudes of the new scores with the exact example. An eigensolver may reverse the sign of an eigenvector; the corresponding coordinate reverses with it.
import numpy as np
def kernel(x, y):
t = x * y
return t + t**2
train = np.array([-1., 0., 1.])
K = kernel(train[:, None], train[None, :])
row_mean = K.mean(axis=1)
grand_mean = K.mean()
Kc = K - row_mean[:, None] - row_mean[None, :] + grand_mean
mu, a = np.linalg.eigh(Kc)
order = np.argsort(mu)[::-1]
mu, a = mu[order], a[:, order]
tol = 1e-12 * np.linalg.norm(Kc, ord=2)
assert mu.min() >= -tol
positive = mu > tol
mu, a = mu[positive], a[:, positive]
alpha = a / np.sqrt(mu)
training_scores = Kc @ alpha
raw_new = kernel(train, 2.)
centered_new = raw_new - row_mean - raw_new.mean() + grand_mean
new_scores = centered_new @ alpha
print(mu) # [2., 0.66666667]
print(np.abs(new_scores)) # [2., 3.33333333]
An exact zero eigenvalue represents a zero linear combination of centered feature vectors, so it cannot supply a unit feature direction by division. It is omitted. In floating-point arithmetic, an eigenvalue very close to zero can have a small negative sign; classify it relative to the matrix scale. A substantially negative eigenvalue has a different meaning: the computed matrix is not positive semidefinite to that accuracy. Replacing it with its absolute value would change the geometry rather than normalize the same PCA.
Counterexample mode
A Gaussian formula with the wrong sign is not a kernel
Take in the Gaussian formula, so , and two scalar observations , . Then
and is an eigenvector of both and with eigenvalue . A feature map would force , but gives . No inner-product space realizes this function, so there is no principal direction to normalize; the negative eigenvalue is a modelling error, not roundoff. With the same two points give off-diagonal entries and eigenvalues , both positive.
Kernel choice determines which nonlinear variations receive large feature norms. For an RBF kernel, increasing makes similarity decay over shorter original-space distances. For polynomial features, degree and input scale change the relative contributions of different powers. These parameters define the feature metric; maximizing its variance alone does not select them or optimize separation of labeled classes.
Units also interact directly with the Gaussian parameter. Multiplying every input coordinate by a scalar multiplies squared distances by . Replacing by then gives exactly the same Gram matrix. Keeping fixed instead selects a different similarity geometry. This simple identity helps distinguish a change of measurement units from an intentional change of the model's length scale.
Common mistakes
Common mistake
(Confusing Gram eigenvectors with feature-space directions)
Using directly as the coefficient vector creates a feature direction with squared norm , not one. The correct coefficient is . Likewise, centering a new kernel vector by subtracting only its own average misses the stored training row means and grand mean. All four terms in the centered-kernel formula arise from one feature-space inner product.
Summary
A kernel supplies a positive semidefinite observation Gram matrix. Centering its features gives . Positive eigenpairs provide normalized coefficients and training scores . A new observation uses kernel values centered with the existing training-feature mean. The resulting coordinates describe nonlinear features of the original data; their variance and reconstruction error are measured in that feature space.
Exercises
Quick check
(1. For three observations with Gram matrix , find the centered Gram matrix and its eigenvalues. What fraction of the feature-space variation does one principal component retain?)
Use the centering matrix and its action on constant and zero-sum vectors.
Quick check
(2. For six training observations, suppose a centered Gram matrix has positive eigenvalues and . For a unit eigenvector associated with , find its normalized coefficient vector, training score vector, and sample score variance.)
Distinguish the Gram eigenvalue from the covariance eigenvalue.
Quick check
(3. In the polynomial example, project the new observation onto both displayed principal directions using the fixed training mean. Give its raw kernel vector, centered kernel vector, and scores.)
The stored row means and grand mean remain unchanged.
Solutions
Solution · 1. A centered identity Gram matrix
Since , . Its eigenvalues are : it fixes every zero-sum vector and annihilates the constant vector. One component retains of the variation. The leading direction is not unique because the positive eigenvalue is repeated.
Solution · 2. The three normalizations
The coefficient vector is , the training score vector is , and its sample variance is . The other component's variance is . Gram eigenvalues must be divided by for sample variances, while the explained fraction for the first component is .
Solution · 3. A new point on the opposite side
The raw vector is , with average . Subtracting the training row means and adding gives . Dotting with the two coefficient vectors gives scores . This agrees with .