Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Principal component analysis and kernel PCA

ProblemFind the orthogonal directions of greatest variance and project data onto the first few; extend this to nonlinear structure through a kernel
Devised byKarl Pearson (1901), lines of closest fit; Harold Hotelling (1933), principal components; Kari Karhunen (1946) and Michel Loève (1955), the continuous expansion; Bernhard Schölkopf, Alexander Smola and Klaus-Robert Müller (1998), kernel PCA
AccuracyExact up to the eigensolver; the variances agree with NumPy’s SVD to (table below)
CostPCA: via the covariance matrix. Kernel PCA: via the Gram matrix
Read firstThe singular value decomposition
APIPca (new(components), components, explained_variance, explained_variance_ratio, inverse_transform), KernelPca (new(kernel, components), eigenvalues); both implement Transformer

Overview

Measured features are often redundant: height and weight, or the prices of related stocks, move together. Principal component analysis (PCA) rotates the data to new axes, the principal components, ordered so that the first captures as much variance as possible, the second as much of the rest, and so on. Keeping the first few gives a lower-dimensional summary that loses the least variance, for visualisation, compression, denoising or as input to another model. Kernel PCA does the same in the feature space of a kernel, where curved structure in the original space can become linear.

Where it is used

PCA finds the directions along which data vary most.

  • Dimensionality reduction. Compressing images, spectra and sensor arrays to a few components for storage, visualisation and further analysis.
  • Denoising. Dropping the small components removes noise, as in hyperspectral imaging.
  • Finance and genomics. The main modes of variation of yield curves or of population genetic data.
  • Signal processing. The Karhunen-Loeve transform; PCA of a covariance matrix is the same as its eigendecomposition; kernel PCA extends it to curved structure.

History

Karl Pearson (1901) sought the line and plane of closest fit to a cloud of points. Harold Hotelling (1933), analysing psychological test scores, introduced the name principal components and the eigenvector formulation. The same expansion for random processes is the Karhunen-Loève transform (Kari Karhunen, 1946; Michel Loève), and in other fields PCA is known as empirical orthogonal functions (meteorology) or proper orthogonal decomposition (fluid mechanics). Bernhard Schölkopf, Alexander Smola and Klaus-Robert Müller (1998) expressed PCA through inner products only, so that a kernel could replace them.

The idea

Directions of greatest variance

PCA looks for the directions along which the data vary most. The assumption behind it is that directions of large variation carry the structure of the data, and directions of small variation are mostly noise.

Setting up. Subtract the mean from every point, , so that the cloud of points is centred on the origin, and form the sample covariance matrix

Its diagonal entries are the variances of the individual features, and its off-diagonal entries say how pairs of features vary together.

The first direction. Project the points onto a unit vector : the coordinate of point along it is . The variance of these coordinates is

We want the unit vector that maximises . Since is symmetric it has orthonormal eigenvectors with eigenvalues . Writing with gives , a weighted average of the eigenvalues. It is largest when all the weight is on the largest eigenvalue: , and the variance along it is . (The expression for unit is the Rayleigh quotient of .)

The other directions. The second direction maximises the variance among unit vectors orthogonal to the first. By the same argument it is , with variance , and so on. The principal axes are therefore the eigenvectors of the covariance matrix, ordered by eigenvalue:

where holds the first eigenvectors as columns. The scores are the coordinates of the points along the first axes, a description of each point by numbers instead of . The variance of the -th score is , and different scores are uncorrelated, because in the eigenvector basis the covariance matrix is diagonal.

Figure 12.8. Principal axes.

Best low-rank reconstruction

The same axes solve a second problem, which gives another reason to use them. Suppose we keep only the scores of each point and want to recover the point as well as possible. The reconstruction from the scores is

the projection of the point onto the -dimensional subspace spanned by the axes (shifted back by the mean). Among all -dimensional subspaces, this one minimises the sum of squared distances from the points to their projections. This is the Eckart-Young theorem applied to the matrix of centred data. Maximising the variance kept and minimising the error discarded are the same thing, because by Pythagoras the squared length of each centred point is the sum of the two.

The error is exactly the variance in the directions thrown away: the mean squared reconstruction error equals the sum of the discarded eigenvalues (times , and divided by for a per-feature mean):

Table 12.12. Variance explained and reconstruction error of PCA.

components keptvariance explainedreconstruction mean squared errordiscarded eigenvalues ÷ features
10.75693.88883.8888
20.93840.98460.9846
30.98830.18700.1870
40.99000.15980.1598
60.99300.11250.1125

The last two columns agree to every printed digit.

How many components?

The explained variance ratio shows how much each component matters. For data generated from three hidden factors in 12 dimensions plus noise:

Figure 12.9. Scree plot.

The first three components carry 98.8% of the variance, and the remaining nine share the noise equally. A scree plot like this, or a target fraction such as 95%, is the usual way to choose . PCA depends on the units: a feature measured in millimetres dominates one in metres, so features on different scales should be standardised first, which amounts to PCA of the correlation matrix.

Testing against NumPy

On 200 points in five dimensions driven by two factors, the library’s variances agree with those from NumPy’s SVD of the centred data to relative, and the two leading axes (up to sign) to ; see the reference table. The trailing axes span nearly equal noise variances and are only defined up to rotation, so they are not compared.

Kernel PCA

PCA only finds linear structure. Two concentric rings have no direction of high variance that separates them. Kernel PCA maps each point to features and performs PCA there, using only inner products (kernels). Every principal axis is a combination of the mapped training points, , and the coefficients solve an eigenproblem of the centred Gram matrix

where is the matrix with every entry , which centres the features. The scores of a new point are , with scaled to so that the axis has unit length in feature space.

Linear PCA only rotates the rings. With an RBF kernel, the first two components describe the angle around the rings (a degenerate pair, like a sine and a cosine), and the third separates the inner ring from the outer one. The eigenvalues come in such pairs:

Figure 12.10. Kernel PCA eigenvalues.

The centred Gram matrix always has the eigenvalue zero (the constant vector) and, for smooth kernels, many tiny ones.

Algorithm

PCA.

  1. Centre. Subtract from each column of the data matrix its mean, and store the means.
  2. Covariance. Form .
  3. Eigendecomposition. Compute the eigenvalues and eigenvectors of with the symmetric eigensolver.
  4. Select. Keep the eigenvectors of the largest eigenvalues as the principal axes. An eigenvector is defined only up to sign, so each is given the sign that makes its largest entry positive, which makes the result reproducible.
  5. Transform a point: subtract the stored means and take the dot product with each axis. Reconstruct it: multiply the scores by the axes and add the means back.

Forming costs and its eigendecomposition .

Kernel PCA.

  1. Gram matrix. Compute for all pairs of training points.
  2. Centre it. Subtract from each entry its row mean and its column mean, and add the overall mean (the formula for above). Store the row means and the overall mean.
  3. Eigendecomposition. Compute the eigenvalues and eigenvectors of , and keep the largest. Scale each eigenvector by .
  4. Transform a new point: compute its kernel values with all the training points, centre that row with the stored means, and take its dot product with each scaled eigenvector.

The eigendecomposition of the Gram matrix costs : kernel PCA scales with the number of points, not the number of features.

Implementation

        self.mean = x.mean_axis(ndarray::Axis(0)).expect("non-empty");
        let centred = &x - &self.mean;
        let cov = centred.t().dot(&centred) / (n as f64 - 1.0);
        let (vals, vecs) = cov.eigh(UPLO::Lower).map_err(|_| ErrorsJSL::RuntimeError("The covariance eigendecomposition failed."))?;
        // eigh returns ascending eigenvalues; take the largest.
        let order: Vec<usize> = (0..p).rev().take(self.components).collect();
        self.variances = order.iter().map(|&i| vals[i].max(0.0)).collect();
        self.total_variance = vals.iter().map(|v| v.max(0.0)).sum();
        self.axes = R2D::from_shape_fn((self.components, p), |(c, j)| vecs[[j, order[c]]]);
        let k = self.kernel.gram(x);
        self.row_means = k.mean_axis(ndarray::Axis(1)).expect("non-empty");
        self.total_mean = self.row_means.sum() / n as f64;
        // Double centring: Kc = K - 1K - K1 + 1K1.
        let kc = R2D::from_shape_fn((n, n), |(i, j)| k[[i, j]] - self.row_means[i] - self.row_means[j] + self.total_mean);
        let (vals, vecs) = kc.eigh(UPLO::Lower).map_err(|_| ErrorsJSL::RuntimeError("The Gram matrix eigendecomposition failed."))?;
        let order: Vec<usize> = (0..n).rev().take(self.components).collect();
        self.eigenvalues = order.iter().map(|&i| vals[i].max(0.0)).collect();
        self.alphas = R2D::from_shape_fn((n, self.components), |(i, c)| {
            let lambda = vals[order[c]];
            if lambda > 1e-12 { vecs[[i, order[c]]] / lambda.sqrt() } else { 0.0 }
        });
  • PCA works through the covariance matrix, which is efficient when . For wide data (), or for the best accuracy, the SVD of the centred data matrix is preferable: forming squares the condition number.
  • Kernel PCA stores the training data and needs a cross-kernel row per new point. With the linear kernel its scores equal Pca’s up to sign: both are for the eigenpairs of .

In practice

//! Principal component analysis and kernel PCA.

use lib_jsl_core::R2D;
use lib_jsl_machine_learning::common::{MlRng, Transformer};
use lib_jsl_machine_learning::datasets::make_circles;
use lib_jsl_machine_learning::kernels::Kernel;
use lib_jsl_machine_learning::unsupervised::reduction::{KernelPca, Pca};

fn main() {
    // Five measured features driven by two hidden factors, plus noise.
    let mut rng = MlRng::new(1);
    let z = R2D::from_shape_fn((300, 2), |_| rng.gaussian(0.0, 1.0));
    let mix = ndarray::arr2(&[[3.0, 1.0, 0.0, 2.0, -1.0], [0.0, 2.0, 1.0, -1.0, 1.0]]);
    let x = z.dot(&mix) + R2D::from_shape_fn((300, 5), |_| rng.gaussian(0.0, 0.3));
    let mut pca = Pca::new(5);
    pca.fit(x.view()).unwrap();
    println!("explained variance ratio {:.4?}", pca.explained_variance_ratio());
    let mut two = Pca::new(2);
    let scores = two.fit_transform(x.view()).unwrap();
    let back = two.inverse_transform(scores.view()).unwrap();
    let rms = ((&back - &x).mapv(|v| v * v).mean().unwrap()).sqrt();
    println!("two components: reconstruction RMS error {rms:.3} (noise level 0.3)");
    println!("first axis {:.3}", two.components().row(0));

    // Rings: the third RBF kernel PCA component separates them.
    let (rings, labels) = make_circles(100, 0.03, 0.45, 1);
    let mut kp = KernelPca::new(Kernel::Rbf { gamma: 2.0 }, 3);
    let k = kp.fit_transform(rings.view()).unwrap();
    let mean = |c: usize| k.column(2).iter().zip(&labels).filter(|(_, l)| **l == c).map(|(v, _)| *v).sum::<f64>() / 100.0;
    println!("kernel PCA eigenvalues {:.2?}; component 3 means: outer {:.3}, inner {:.3}", kp.eigenvalues(), mean(0), mean(1));
}
explained variance ratio [0.6842, 0.3046, 0.0042, 0.0035, 0.0035]
two components: reconstruction RMS error 0.228 (noise level 0.3)
first axis [0.776, 0.247, -0.012, 0.519, -0.261]
kernel PCA eigenvalues [30.85, 30.23, 18.68]; component 3 means: outer 0.304, inner -0.304

Two components explain 99% of the variance. The reconstruction error is below the noise level, because the part of the noise that lies in the two-dimensional subspace is kept.

Strengths

  • Fast, exact and parameter-free; uncorrelated scores; the optimal linear compression.
  • Kernel PCA finds nonlinear structure with the same linear algebra.

Weaknesses

  • Linear PCA misses curved structure; the components need not be interpretable or relevant to a later prediction task.
  • Sensitive to feature scales and outliers.
  • Kernel PCA costs , keeps the training set, and has no simple inverse mapping back to the inputs.

Exercises

  1. Show that the first principal axis maximises subject to , using a Lagrange multiplier.
  2. Show that the principal axes are the right singular vectors of the centred data matrix, and relate the singular values to the eigenvalues of .
  3. Prove that the reconstruction error with components is per point.
  4. Show that kernel PCA with the linear kernel reproduces the PCA scores exactly, up to sign.
  5. Derive the double-centring formula from .
Hints and answers
  1. With the stationarity condition is , and the value is : take the largest eigenvalue.
  2. With centred data , , so the principal axes are the columns of and .
  3. The reconstruction error of with components is the squared norm of its projection on the discarded axes; averaging over the data gives .
  4. The Gram matrix of the centred data is , so the kernel PCA scores equal the PCA scores , up to the sign of each eigenvector.
  5. With centred features , , i.e. with .

Further reading

  • I. T. Jolliffe, Principal Component Analysis, 2nd ed., Springer, 2002.
  • H. Hotelling, “Analysis of a complex of statistical variables into principal components”, Journal of Educational Psychology 24 (1933) 417–441, 498–520.
  • B. Schölkopf, A. Smola and K.-R. Müller, “Nonlinear component analysis as a kernel eigenvalue problem”, Neural Computation 10 (1998) 1299–1319.
  • I. T. Jolliffe and J. Cadima, “Principal component analysis: a review and recent developments”, Philosophical Transactions of the Royal Society A 374 (2016) 20150202.