Kernel PCA: center, normalize and project
核主成分分析
Derive feature-space axes from a centered Gram matrix, transform new points, and handle zero and repeated eigenvalues.
kernel-pcaOne measurement can have two kinds of variation
A device records signed calibration offsets: −2, −1, 0, 1 and 2. Ordinary PCA sees one numerical coordinate. But direction and magnitude can tell different stories: the sign says which way the calibration drifts, while a squared offset treats both extremes alike. We could add those features manually, then run PCA. Kernel PCA performs the feature-space calculation through inner products supplied by a kernel.
It is still PCA: choose orthogonal directions with high empirical variance. The nonlinearity comes from the feature representation, not from replacing variance with an unspecified measure of “interestingness.” The original paper by Schölkopf, Smola and Müller derives this kernel eigenproblem and its projection rule.
This chapter follows a new observation all the way through training centering, axis normalization and projection. It also handles two easily confused cases: an eigenvalue of zero, which supplies no positive-variance axis, and two equal positive eigenvalues, which define a subspace without a unique ordered pair of axes.
Center features, then normalize axes in the right space
The objective lives in feature space
Let a positive-semidefinite kernel represent inner products of feature vectors. Subtract the training feature mean and define an empirical covariance using denominator n:
The outer-product operator maps a vector to its inner product with a feature vector, times that feature vector. Subsequent axes maximize the same objective while being orthogonal to preceding axes. Equivalently, the leading subspace minimizes mean squared reconstruction error in feature space. The first axis need not be the best predictor of a label, and the variance is not measured in the original input units.
Double centering is not input centering
Form the training Gram matrix from kernel evaluations. With the centering matrix H, its centered counterpart is:
Expanding the inner product of two mean-subtracted feature vectors gives the final expression. Its row sums vanish, and it remains positive semidefinite. Even if raw inputs have mean zero, their nonlinear features generally do not. In our offset example the mean input is zero but the mean square is two. Centering the square feature is still necessary. Appendix B of the original paper derives both training and test-point centering.
A Gram eigenvector is not yet a unit feature-space axis
Let v be a Euclidean unit eigenvector of the centered Gram matrix, with a positive eigenvalue lambda. Define the feature-space direction and the coordinates by:
Its squared norm is v-transpose times the centered Gram matrix times v, divided by lambda, hence one. Applying C verifies the covariance eigenvalue lambda/n. Conversely, any covariance eigenvector with positive eigenvalue lies in the span of the training features, because applying C already produces a vector in that span. This derives the relevant kernel solution without cancelling a possibly singular Gram matrix.
The feature-space expansion coefficients are v divided by the square root of lambda. Dividing by lambda instead gives the wrong norm. Zero eigenvalues cannot be used in that normalization and add no training variance. Centering limits the number of positive modes to at most n − 1, also bounded by the feature dimension.
Our variance denominator is n. A covariance convention using n − 1 changes the reported variance to lambda/(n − 1), but not these unit axes or their projection coordinates. The fixed scikit-learn API calls its stored values eigenvalues of the centered kernel matrix; they should not be read directly as covariance variances.
Project a new point using the training mean
For a new observation z, compute a column of kernel similarities to the training observations. Center it against the same training mean:
The average in this expression is over training points for that one query. It is not an average over the current query batch. Transforming z alone or beside another observation must give the same coordinates. Neither the training mean nor the principal axes are refitted during projection.
An exact Gram matrix with a small numerical eigensystem
Use this valid one-dimensional polynomial kernel:
After feature centering, the constant coordinate vanishes, leaving at most two positive modes. The program takes advantage of that specific rank bound. It builds and centers the Gram matrix with Fraction, determines rank from exact trace identities, constructs an orthonormal basis from Gram columns, then diagonalizes only the resulting one- or two-dimensional range. The fitting code never constructs the explicit feature map above.
If t is the trace and q is the sum of squared entries of the centered Gram matrix, its two possible nonzero eigenvalues satisfy:
These identities do not apply to an arbitrary rank-three kernel matrix. In code, the smaller positive root is obtained from the product divided by the larger root, avoiding a subtraction of nearly equal floats. Gram entries and the rank test are exact; eigenvectors and projection coordinates are floating-point approximations audited afterward.
Training accepts 2–20 integer or Fraction inputs in [−100, 100], including duplicates. Request one or two components; fewer are returned if the exact rank is smaller. Rank zero returns zero-dimensional coordinates. When the two positive eigenvalues are exactly equal, requesting both returns an orthonormal basis of their shared space; requesting only one raises an error because the leading axis is not unique under this contract.
Additional numerical guards reject nonzero trace below 1e-12, a second/first eigenvalue ratio below 1e-10, or distinct positive eigenvalues whose relative gap is at most 1e-8. These cases remain mathematically valid; this small implementation declines to resolve them. Pass an unmodified fitted model to project. Query lists may be empty, and query coordinates use the same type and range restrictions. There is no whitening, kernel selection or inverse mapping.
from fractions import Fraction as F
from math import atan2,cos,sin,sqrt
def points(values, training=False):
if not isinstance(values,(list,tuple)):
raise ValueError('coordinates must be a list or tuple')
if training and not 2 <= len(values) <= 20:
raise ValueError('training requires 2 to 20 coordinates')
if any(type(x) not in (int,F) or abs(x)>100 for x in values):
raise ValueError('use integers/Fractions in [-100,100], not bool/float')
return tuple(map(F,values))
def kernel(x,z):
return (1+x*z)**2
def project(model,values):
queries=points(values)
result=[];n=len(model['points'])
for z in queries:
row=[kernel(x,z) for x in model['points']]
mean=sum(row,F(0))/n
centered=[w-r-mean+model['grand_mean'] for w,r in zip(row,model['row_means'])]
result.append(tuple(sum(float(w)*a for w,a in zip(centered,alpha))
for alpha in model['alphas']))
return tuple(result)
def kernel_pca(values,components=2):
"""Kernel-only fit for k(x,z)=(1+x*z)^2; centered rank is at most two."""
x=points(values,training=True);n=len(x)
if type(components) is not int or components not in (1,2):
raise ValueError('components must be 1 or 2')
K=tuple(tuple(kernel(a,b) for b in x) for a in x)
means=tuple(sum(row,F(0))/n for row in K)
grand=sum(means,F(0))/n
H=tuple(tuple(K[i][j]-means[i]-means[j]+grand for j in range(n)) for i in range(n))
trace=sum((H[i][i] for i in range(n)),F(0))
squares=sum((v*v for row in H for v in row),F(0))
product=(trace*trace-squares)/2
discriminant=2*squares-trace*trace
assert trace>=0 and product>=0 and discriminant>=0
rank=0 if trace==0 else (1 if product==0 else 2)
eigenvalues=[];vectors=[]
if rank:
if float(trace)<1e-12:
raise ArithmeticError('nonzero variance is below the teaching precision guard')
large=(float(trace)+sqrt(float(discriminant)))/2
eigenvalues=[large] if rank==1 else [large,float(product)/large]
if rank==2:
if eigenvalues[1]/large<1e-10:
raise ArithmeticError('second positive mode is numerically unresolved')
if discriminant==0 and components==1:
raise ArithmeticError('one axis cannot uniquely split an exact eigenvalue tie')
if discriminant and sqrt(float(discriminant))/large<=1e-8:
raise ArithmeticError('distinct eigenvalues are too close for this example')
# Find a basis of range(H) using pivoted Gram-column orthogonalization.
basis=[]
for _ in range(rank):
candidates=[]
for j in range(n):
v=[float(H[i][j]) for i in range(n)]
for q in basis:
dot=sum(a*b for a,b in zip(v,q))
v=[a-dot*b for a,b in zip(v,q)]
candidates.append(v)
v=max(candidates,key=lambda a:sum(t*t for t in a))
norm=sqrt(sum(t*t for t in v))
if norm==0:raise ArithmeticError('range basis lost numerical rank')
basis.append(tuple(t/norm for t in v))
if rank==1 or discriminant==0:
vectors=basis
else:
def bilinear(a,b):
return sum(a[i]*float(H[i][j])*b[j] for i in range(n) for j in range(n))
q,r=basis;aa=bilinear(q,q);bb=bilinear(r,r);ab=bilinear(q,r)
theta=atan2(2*ab,aa-bb)/2;c=cos(theta);s=sin(theta)
vectors=[tuple(c*a+s*b for a,b in zip(q,r)),
tuple(-s*a+c*b for a,b in zip(q,r))]
vectors=[tuple(-a for a in v) if v[max(range(n),key=lambda i:abs(v[i]))]<0 else v
for v in vectors]
orthogonality=max((abs(sum(a*b for a,b in zip(u,v))-float(i==j))
for i,u in enumerate(vectors) for j,v in enumerate(vectors)),default=0.0)
residual=max((abs(sum(float(H[i][j])*v[j] for j in range(n))-lam*v[i])
for lam,v in zip(eigenvalues,vectors) for i in range(n)),default=0.0)
if orthogonality>1e-8 or residual>1e-8*float(trace):
raise ArithmeticError('eigenpair audit failed')
keep=min(components,rank)
selected=tuple(eigenvalues[:keep])
model=dict(points=x,row_means=means,grand_mean=grand,centered_gram=H,rank=rank,
eigenvalues=selected,eigenvectors=tuple(vectors[:keep]),
alphas=tuple(tuple(a/sqrt(lam) for a in v)
for lam,v in zip(selected,vectors[:keep])),
variances=tuple(lam/n for lam in selected),total_variance=trace/n,
ratios=tuple(lam/float(trace) for lam in selected),
residual=residual,orthogonality=orthogonality)
model['coordinates']=project(model,x)
return model
if __name__=='__main__':
model=kernel_pca([-2,-1,0,1,2])
print('Gram eigenvalues:',tuple(round(v,6) for v in model['eigenvalues']))
print('component variances:',tuple(round(v,6) for v in model['variances']))
print('total feature variance:',model['total_variance'])
print('training coordinates:',tuple(tuple(round(v,6) for v in row) for row in model['coordinates']))
print('new point 3:',tuple(round(v,6) for v in project(model,[3])[0]))
print('constant data:',kernel_pca([1,1,1])['coordinates'])
print('tied full space:',tuple(round(v,6) for v in kernel_pca([-2,0,0,2])['eigenvalues']))
try:kernel_pca([-2,0,0,2],1)
except ArithmeticError:print('one tied axis: rejected')
Gram eigenvalues: (20.0, 14.0)
component variances: (4.0, 2.8)
total feature variance: 34/5
training coordinates: ((2.828427, 2.0), (1.414214, -1.0), (0.0, -2.0), (-1.414214, -1.0), (-2.828427, 2.0))
new point 3: (-4.242641, 7.0)
constant data: ((), (), ())
tied full space: (16.0, 16.0)
one tied axis: rejected
The two covariance variances are 20/5 and 14/5, summing to 34/5. Their proportions are 10/17 and 7/17. With the displayed sign choices, the first coordinate is minus square-root-two times the input, and the second is the input squared minus two. The new offset three therefore maps to approximately (−4.242641, 7). Its second coordinate measures deviation from the training mean square, not from the query’s own square.
The original one-dimensional measurement has become two feature coordinates. Kernel PCA can expand input dimensionality while still reducing a larger feature space. “Kernel PCA” does not, by itself, promise that the output dimension will be smaller than the original input dimension.
For this fixed rank-two kernel, fitting uses quadratic time and storage in n under unit-cost arithmetic: the Gram matrix, its trace identities, two basis vectors and their audits each require at most quadratic work. Projecting m queries takes O(1 + mn) work for at most two retained axes; the stored Gram matrix makes model storage quadratic. Large rational numerators and denominators add bit costs. General dense kernel PCA has no such rank-two shortcut and a full eigendecomposition typically takes cubic work with quadratic matrix storage.
Variance preservation is not an inverse or a task score
Kernel choice decides which variation becomes large. A nonlinear kernel can amplify irrelevant effects as readily as useful ones. Comparing explained-variance percentages across different kernels does not compare the same geometry. Multiplying a kernel by a positive constant multiplies its variances and scales coordinates by the constant’s square root, while leaving variance ratios unchanged. Changing a kernel’s shape can change the axes themselves.
Eigenvector signs are arbitrary. Repeated positive eigenvalues allow rotations within their eigenspace, so comparing axis values one by one can be misleading. Compare projection subspaces or coordinate inner products when the full tied space is retained. Our program permits that complete tied space but explicitly rejects a request to cut through it with one component.
Keeping all positive training modes reconstructs the centered training Gram matrix through coordinate inner products. It does not imply every new feature vector lies in the training span. Even an approximate reconstruction inside feature space need not correspond to an actual input. For this polynomial map, an arbitrary pair of linear and squared coordinates need not satisfy the required square relation. The original paper discusses this preimage problem in sections 4.4–4.5. The scikit-learn inverse transform learns an approximate preimage through kernel ridge regression; it is not an exact inverse supplied by the eigendecomposition.
Fit preprocessing, kernel parameters and principal directions using training data. Validation or test observations may be projected with that fitted state, but including them when centering or choosing axes changes the training procedure. This unsupervised step can still leak evaluation information. See kernel ridge regression for a supervised kernel objective and spectral clustering for graph separation; neither objective is interchangeable with feature-space variance.
Keep track of the mean, the norm and the span
-
The training offsets already average to zero. Why does the point zero project to (0, −2), rather than (0, 0), in the example?
Answer: The linear feature has mean zero, but the square feature has mean two. The centered features of zero are therefore zero and minus two, under the displayed axes. Zero-mean inputs do not make all nonlinear feature means vanish.
-
The Gram eigenvalues are twenty and fourteen for five observations. Give the covariance variances with denominator n, the retained variance ratio for one component, and the variances with denominator n − 1.
Answer: They are four and 14/5 with denominator n; the leading ratio is 10/17. With denominator n − 1 the variances are five and 7/2. The axes and their projection coordinates stay unchanged when only this reporting convention changes.
-
For (−2, 0, 0, 2), both Gram eigenvalues are sixteen. Does a valid two-axis result have to match another implementation coordinate by coordinate? Why reject a one-axis request here?
Answer: No. Rotating an orthonormal basis of the tied two-dimensional space preserves the represented subspace and coordinate inner products. There is no unique best one-dimensional direction inside it. This program returns a deterministic full basis but declines to choose one arbitrary leading direction.
-
Train on (0, 1), keep its one positive mode, and project the new input two. Does retaining every positive training mode reproduce the entire centered feature vector of two?
Answer: No. Its centered feature vector in the nonconstant coordinates is (3 times square-root-two divided by two, 7/2), with squared norm 67/4. Its projection onto the training direction has squared norm 169/12. The omitted squared norm is 8/3. All training modes span the training features, not necessarily every future feature vector; an exact input-space inverse requires still more conditions.
Kernelize the covariance calculation, not the interpretation
Schölkopf, Smola and Müller, 1998 show how a feature-space covariance problem can be expressed through a finite kernel matrix. The positive-mode normalization in section 2, the nullspace discussion in appendix A and the train/test centering formulas in appendix B are complementary: solving an eigenproblem alone is not enough to obtain correctly scaled new-point coordinates.
The paper also separates nonlinear feature extraction from reconstruction. Kernel evaluation avoids explicitly building a large feature vector, but it does not automatically turn a feature-space direction into an interpretable input or an invertible coordinate system. That distinction remains relevant when a visualization looks convincing.
The fixed scikit-learn documentation provides several numerical solvers, zero-eigenvalue handling and an optional learned inverse transform. For further study, compare PCA, where the feature map is linear, and the kernel trick, which explains when a function can serve as a feature-space inner product. Always state the kernel, centering convention and retained modes before interpreting the resulting coordinates.
Make a prediction, then check
A centered Gram matrix has a unit eigenvector v and positive eigenvalue lambda. Which coefficients form a unit feature-space principal axis?
Learning objectives
- Derive feature centering and the square-root Gram eigenvalue normalization.
- Project new observations using the stored training mean without query-batch dependence.
- Distinguish Gram and covariance eigenvalues, zero modes, tied subspaces and the preimage problem.
Prerequisites & connections
Explore related knowledge →References
- Nonlinear Component Analysis as a Kernel Eigenvalue Problem
Bernhard Schölkopf; Alexander Smola; Klaus-Robert Müller · 1998 - KernelPCA — scikit-learn 1.7
scikit-learn developers
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Seven tests passed. Eight explicit-feature models independently verify exact centered Grams, twelve unit feature axes and covariance eigen-equations, seven top-variance PSD certificates, and 24 new query projections. This reference reconstructs feature-space directions and covariance rather than repeating Gram-column orthogonalization and the rank-two eigensolver.
- Checked n versus n-1 variance reporting, rank-zero/rank-one output, one-mode truncation, exact positive ties, retained tied-space inner products under row permutation, stored training centering, query batching and empty queries, invalid inputs and numerical guards. A new point outside a rank-one training span leaves squared feature residual 8/3 despite retaining every positive training mode.
- Complete original bilingual text, identical Python and eight actual stdout lines, six displays, six stable anchors and four answered exercises. Strict MDX/KaTeX and actual React HTML passed; six math annotations match. Humanizer reread; AI author checks only, written pending independent review. Draft only; no repository edits or sklearn execution.
- Independent AI review found a missing backslash in the third display: the second factor of the unit-norm identity now correctly reads v subscript ell in both languages. This semantic formula correction does not change code or computed results; independent review is still in progress.
- Seven final author tests pass. Independent squared-distance centering, Leibniz characteristic polynomials and singular linear-system solutions check ten fits over seven datasets, seven exact characteristic polynomials, 63 full-space query inner products and 27 truncated-mode inner products. A polynomial spectral projector checks the leading mode without fitting explicit feature axes or repeating Gram-column orthogonalization. Exact new-span residual is 8/3.
- Fully reread bilingual text, implementation, six formulas, exercises and metadata. Checked covariance/Gram scaling, positive-mode normalization, rank-zero/one, exact ties and numerical rejection contracts, training-only centering and fixed rank-two operation bounds. Independent strict MDX/KaTeX and actual React HTML/MathML pass six matching displays, six anchors and four answers.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Nonlinear Component Analysis as a Kernel Eigenvalue Problem · Actually opened the 21-page author-hosted PDF. Read title/journal line on printed page 1299; section 2 pages 1300–1302, equations 2.5–2.15 on covariance normalization, positive span and coefficient norm; section 3 kernel inner products; sections 4.4–4.5 pages 1308–1309 on preimages and reconstruction; appendix A pages 1315–1316 on nullspace coefficients; appendix B pages 1316–1317, B.1–B.4 and the rectangular test-kernel centering formula. Received 1996/accepted 1997 footer is not mistaken for journal year 1998. No visual scan inspection or reproduction of handwriting experiments claimed. Derivations and the rank-two computation are original.
- KernelPCA — scikit-learn 1.7 · Actually read the fixed /1.7 API, rendered 1.7.2: components/kernel parameters 636–657, inverse regression alpha 662–670, solver choices 672–687, zero-mode option 706–707, centered-kernel eigenvalue/vector attributes 729–748, approximate learned preimage 932–940 and references. The code is an original fixed rank-two polynomial-kernel implementation, not a library run or a reproduction of default kernel/degree settings.
- Nonlinear Component Analysis as a Kernel Eigenvalue Problem · Independently read original author-hosted 21-page PDF: printed 1299 publication line, §2 printed 1300–1302 covariance denominator/span, eigenproblem and normalization (2.5)–(2.15), §§4.4–4.5 preimages and reconstruction, and Appendix B train/test centering. Used extracted text, not visual figure inspection; no handwriting experiments reproduced.
- KernelPCA — scikit-learn 1.7 · Independently read fixed 1.7 API rendered as 1.7.2: centered-kernel eigenvalue attributes, numerical solvers, inverse ridge parameter and learned approximate preimage at lines 662–673 and 932–940. No library fit or inverse transform executed.
Related topics