Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Principal Component Analysis (PCA)

KTH JupyterHub Open In Colab Binder

Principal Component Analysis (PCA) is an unsupervised learning method that finds the axes of maximum variation in your data and projects the data onto them. In biotechnology it is used to find the major sources of variation in gene expression data, to visualize how samples relate to each other, to detect batch effects and outliers, and as a preprocessing step before clustering.

Decomposition of a matrix

X=u⊗v=uvT=[u1u2u3u4][v1v2v3]=[u1v1u1v2u1v3u2v1u2v2u2v3u3v1u3v2u3v3u4v1u4v2u4v3].\mathbf{X} = \mathbf{u} \otimes \mathbf{v} = \mathbf{u} \mathbf{v}^{\textsf{T}} = \begin{bmatrix} u_1 \\ u_2 \\ u_3 \\ u_4 \end{bmatrix} \begin{bmatrix} v_1 & v_2 & v_3 \end{bmatrix} = \begin{bmatrix} u_1 v_1 & u_1 v_2 & u_1 v_3 \\ u_2 v_1 & u_2 v_2 & u_2 v_3 \\ u_3 v_1 & u_3 v_2 & u_3 v_3 \\ u_4 v_1 & u_4 v_2 & u_4 v_3 \end{bmatrix}.

A scenario where this might be useful

In PCA, we often deal with a matrix that encapsulates multiple sources of variation. Imagine a scenario where we’re studying gene expression levels across several samples. Here, the gene expression levels might be influenced by two key factors:

  1. Gene-Specific Effects: These are inherent to each gene, such as its baseline expression level or potential for expression. For example, some genes may generally be expressed at high levels across all conditions, while others have lower baseline expression.

  2. Sample-Specific Effects: These capture the influence of each sample (environmental condition, patient, disease state) on gene expression. For instance, one condition might increase expression levels across many genes, while another has a weaker or even suppressive effect.

If the expression matrix is the outer product of these two effects, X=uvT\mathbf{X} = \mathbf{u}\mathbf{v}^{\textsf{T}}, then u\mathbf{u} holds the gene-specific effects and v\mathbf{v} the sample-specific effects.

A toy example

Let us make this concrete with 4 genes and 4 samples. Let the gene-specific effects be u=[2,1,0.5,3]T\mathbf{u} = [2, 1, 0.5, 3]^{\textsf{T}} and the sample-specific effects v=[1,0.8,1.2,0.5]T\mathbf{v} = [1, 0.8, 1.2, 0.5]^{\textsf{T}}. Each entry of the outer product is Xij=uivjX_{ij} = u_i v_j:

X=[210.53][10.81.20.5]=[21.62.4110.81.20.50.50.40.60.2532.43.61.5]\mathbf{X} = \begin{bmatrix} 2 \\ 1 \\ 0.5 \\ 3 \end{bmatrix} \begin{bmatrix} 1 & 0.8 & 1.2 & 0.5 \end{bmatrix} = \begin{bmatrix} 2 & 1.6 & 2.4 & 1 \\ 1 & 0.8 & 1.2 & 0.5 \\ 0.5 & 0.4 & 0.6 & 0.25 \\ 3 & 2.4 & 3.6 & 1.5 \end{bmatrix}

In practice we only observe X\mathbf{X}, and PCA has to find the underlying factors. This toy matrix was built from a single pair of vectors, so it has rank 1: the first principal component reproduces X\mathbf{X} exactly, and all further components are zero. Real data are never exactly of rank 1, and the later components then describe the variation that the first one leaves unexplained.

Scaling the components

The magnitude of a component can be moved freely between u\mathbf{u} and v\mathbf{v}: if we scale u\mathbf{u} by a factor α\alpha and v\mathbf{v} by 1/α1/\alpha, the product uvT\mathbf{u}\mathbf{v}^{\textsf{T}} stays the same. To make the decomposition unique, we scale both vectors to unit length,

∥u∥=1,∥v∥=1,\| \mathbf{u} \| = 1, \quad \| \mathbf{v} \| = 1,

and collect the whole magnitude in a scalar SS:

X≈S uvT.\mathbf{X} \approx S\,\mathbf{u}\mathbf{v}^{\textsf{T}}.

u\mathbf{u} (one entry per gene) and v\mathbf{v} (one entry per sample) then only give directions, while SS measures the strength of the component. The variance that the component explains is proportional to S2S^2.

More than one principal component

An illustration of PCA

Sample 1Sample 2Sample 3Sample MMGene specific
u(1)\mathbf{u}^{(1)}
Gene specific
u(2)\mathbf{u}^{(2)}
Gene 1X11X_{11}X12X_{12}X13X_{13}…\ldotsX1MX_{1M}u1(1)u^{(1)}_1u1(2)u^{(2)}_1
Gene 2X21X_{21}X22X_{22}X23X_{23}…\ldotsX2MX_{2M}u2(1)u^{(1)}_2u2(2)u^{(2)}_2
Gene 3X31X_{31}X32X_{32}X33X_{33}…\ldotsX3MX_{3M}u3(1)u^{(1)}_3u3(2)u^{(2)}_3
⋮\vdots⋮\vdots⋮\vdots⋮\vdots⋱\ddots⋮\vdots⋮\vdots⋮\vdots
Gene NNXN1X_{N1}XN2X_{N2}XN3X_{N3}…\ldotsXNMX_{NM}uN(1)u^{(1)}_NuN(2)u^{(2)}_N
Sample specific v(1)T\mathbf{v}^{(1)\textsf{T}}v1(1)v^{(1)}_1v2(1)v^{(1)}_2v3(1)v^{(1)}_3…\ldotsvM(1)v^{(1)}_MS1S_1
Sample specific v(2)T\mathbf{v}^{(2)\textsf{T}}v1(2)v^{(2)}_1v2(2)v^{(2)}_2v3(2)v^{(2)}_3…\ldotsvM(2)v^{(2)}_MS2S_2

Principal Components

PCA aims to identify the directions, or principal components, in the data that describe the most variance. These directions are essentially the new axes into which the original data is projected, and they help us gain insight into the underlying structure and patterns. The principal components are ordered such that the first principal component describes the largest possible variance, while each subsequent component describes as much of the remaining variance as possible, subject to being orthogonal to the preceding components.

The gene-specific vector u(i)\mathbf{u}^{(i)} and the sample-specific vector v(i)\mathbf{v}^{(i)} come in pairs. Together, the first few pairs give the best low-dimensional description of X\mathbf{X}, in the sense that they minimize the sum of squared residuals. The two members of a pair are linked by projection:

So u(1)\mathbf{u}^{(1)} is, up to the scaling factor S1S_1, the projection of X\mathbf{X} on v(1)\mathbf{v}^{(1)}, and vice versa. The entries of v\mathbf{v} are used as sample-specific scores, which show where each sample lies along a component, and the entries of u\mathbf{u} as gene-specific loadings, which show which genes drive the component.

Dimensionality Reduction and Explained Variance

Keeping only the first few components is a form of dimensionality reduction: each sample is described by its scores on a handful of components instead of by thousands of gene expression values. The share of the total variance that a component describes is called its explained variance. It decreases from the first component onwards, and a plot of the explained variance per component, a scree plot, shows how many components are needed to capture most of the variation.

Geometrically, PCA is an affine transformation: it subtracts the mean (a translation) and rotates the data onto new axes. Keeping only the first few axes then projects the data onto a lower-dimensional subspace. Because this projection is linear, it can flatten the data but cannot unfold a curved structure.

Singular Value Decomposition (SVD)

Principal components are calculated with the singular value decomposition (SVD). Before the decomposition, the data are centered: the mean of each variable (for example, each gene’s mean expression across the samples) is subtracted, so that the components describe the variation around the mean rather than the mean itself. The SVD then decomposes the centered data matrix X\mathbf{X} as

X=USVT\mathbf{X} = \mathbf{U}\mathbf{S}\mathbf{V}^{\textsf{T}}

where

Since the variance described by a component is proportional to Si2S_i^2, the fraction of the variance explained by component ii is Ri2=Si2∑jSj2R^2_i=\frac{S^2_i}{\sum_j S^2_j}. Without centering, the first component would mostly describe the mean, and this ratio would be a fraction of the sum of squares rather than of the variance.

An example of reconstruction with PCA, Eigenfaces

Notebook Cell
downloading Olivetti faces from https://ndownloader.figshare.com/files/5976027 to /home/runner/scikit_learn_data
Dataset consists of 400 faces
Fitting PCA model to faces dataset...
<Figure size 800x1150 with 21 Axes>
<Figure size 1000x920 with 21 Axes>
<Figure size 1000x920 with 21 Axes>
Explained variance ratio of components:  [0.18154664 0.10176543 0.07104147 0.05596606 0.04068943 0.03342149
 0.02613544 0.0258631  0.02152119 0.02033983 0.01828899 0.01626766
 0.01529054 0.01358849 0.01275673 0.01195727 0.0107786  0.00958755
 0.00953734 0.00904233]
<Figure size 800x500 with 1 Axes>

In this example, we reconstruct facial images from a low-dimensional representation. The Olivetti faces dataset contains 400 photos of 40 people, each of 64 × 64 = 4,096 pixels. Each photo is a sample and each pixel a variable. PCA needs every pixel to have mean zero across the photos. scikit-learn’s PCA subtracts these means itself, so the explicit global centering in the code is not needed for the PCA, but it makes the plotted faces show deviations from the average face. The local centering subtracts each photo’s own mean, which removes differences in overall brightness between the photos.

The principal components of this dataset are called eigenfaces. Each eigenface is a pattern over all 4,096 pixels that captures a direction of large variation between the faces (e.g., eyes, nose, or general facial structure). An eigenface plays the role of the gene-specific vector u\mathbf{u}: it holds one value per pixel. The matching photo-specific scores play the role of the sample-specific vector v\mathbf{v}: they say how much of each eigenface is present in each photo.

Projecting a face onto the 20 eigenfaces turns its 4,096 pixel values into 20 scores. The reconstruction (inverse_transform) reverses the process by adding up the eigenfaces, weighted by the face’s scores. The reconstructed faces are blurred but still recognizable, although each of them is described by 20 numbers instead of 4,096. The last plot shows why they are not perfect: the first eigenface explains 18% of the variance and the 20 eigenfaces together about 70%, so the remaining 30% of the variation, the finer detail, is lost.

What you should know after reading this chapter

You should be able to:

  1. Calculate the outer product uvT\mathbf{u}\mathbf{v}^{\textsf{T}} of two small vectors by hand, and explain how PCA does the reverse by finding the vectors u\mathbf{u} and v\mathbf{v} for which X≈uvT\mathbf{X} \approx \mathbf{u}\mathbf{v}^{\textsf{T}}.

  2. Interpret u\mathbf{u} as gene-specific effects and v\mathbf{v} as sample-specific effects of a genes ×\times samples matrix. Explain that u(1)\mathbf{u}^{(1)} is, up to a scaling factor, the projection of X\mathbf{X} on v(1)\mathbf{v}^{(1)}, and vice versa.

  3. Explain why the magnitude of a component can be moved freely between u\mathbf{u} and v\mathbf{v}, and how scaling both to unit length, ∥u∥=∥v∥=1\|\mathbf{u}\| = \|\mathbf{v}\| = 1, puts the whole magnitude in the singular value SS.

  4. Describe how the second and later principal components are found by decomposing the residual X−S1u(1)v(1)T\mathbf{X} - S_1\mathbf{u}^{(1)}\mathbf{v}^{(1)\textsf{T}}, and state how many components a matrix can have at most.

  5. Explain why the data are centered before PCA. Write down the singular value decomposition X=USVT\mathbf{X} = \mathbf{U}\mathbf{S}\mathbf{V}^{\textsf{T}}, and identify which matrix holds the gene-specific effects, the sample-specific effects and the singular values. Calculate the fraction of variance explained by component ii, Ri2=Si2/∑jSj2R^2_i = S^2_i / \sum_j S^2_j, from a set of singular values.

  6. Explain how PCA reduces the dimensionality of data, and interpret a scree plot of the explained variance per component to judge how many components to keep.

  7. Explain how a sample is reconstructed approximately as a weighted sum of a few principal components, as when the eigenfaces example represents each 4,096-pixel face by only 20 numbers.