 #jsDisabledContent { display:none; } My Account | Register | Help Flag as Inappropriate This article will be permanently flagged as inappropriate and made unaccessible to everyone. Are you certain this article is inappropriate?          Excessive Violence          Sexual Content          Political / Social Email this Article Email Address:

# Karhunen–Loève transform

Article Id: WHEBN0027001101
Reproduction Date:

 Title: Karhunen–Loève transform Author: World Heritage Encyclopedia Language: English Subject: Collection: Publisher: World Heritage Encyclopedia Publication Date:

### Karhunen–Loève transform

Principal component analysis (PCA) is a mathematical procedure that uses orthogonal transformation to convert a set of observations of possibly correlated variables into a set of values of linearly uncorrelated variables called principal components. The number of principal components is less than or equal to the number of original variables. This transformation is defined in such a way that the first principal component has the largest possible variance (that is, accounts for as much of the variability in the data as possible), and each succeeding component in turn has the highest variance possible under the constraint that it be orthogonal to (i.e., uncorrelated with) the preceding components. Principal components are guaranteed to be independent if the data set is jointly normally distributed. PCA is sensitive to the relative scaling of the original variables.

Depending on the field of application, it is also named the discrete Karhunen–Loève transform (KLT) in signal processing, the Hotelling transform in multivariate quality control, proper orthogonal decomposition (POD) in mechanical engineering, singular value decomposition (SVD) of X (Golub and Van Loan, 1983), eigenvalue decomposition (EVD) of XTX in linear algebra, factor analysis, Eckart–Young theorem (Harman, 1960), or Schmidt–Mirsky theorem in psychometrics, empirical orthogonal functions (EOF) in meteorological science, empirical eigenfunction decomposition (Sirovich, 1987), empirical component analysis (Lorenz, 1956), quasiharmonic modes (Brooks et al., 1988), spectral decomposition in noise and vibration, and empirical modal analysis in structural dynamics.

PCA was invented in 1901 by Karl Pearson, as an analogue of the principal axes theorem in mechanics; it was later independently developed (and named) by Harold Hotelling in the 1930s. The method is mostly used as a tool in exploratory data analysis and for making predictive models. PCA can be done by eigenvalue decomposition of a data covariance (or correlation) matrix or singular value decomposition of a data matrix, usually after mean centering (and normalizing or using Z-scores) the data matrix for each attribute. The results of a PCA are usually discussed in terms of component scores, sometimes called factor scores (the transformed variable values corresponding to a particular data point), and loadings (the weight by which each standardized original variable should be multiplied to get the component score).

PCA is the simplest of the true eigenvector-based multivariate analyses. Often, its operation can be thought of as revealing the internal structure of the data in a way that best explains the variance in the data. If a multivariate dataset is visualised as a set of coordinates in a high-dimensional data space (1 axis per variable), PCA can supply the user with a lower-dimensional picture, a "shadow" of this object when viewed from its (in some sense; see below) most informative viewpoint. This is done by using only the first few principal components so that the dimensionality of the transformed data is reduced.

PCA is closely related to factor analysis. Factor analysis typically incorporates more domain specific assumptions about the underlying structure and solves eigenvectors of a slightly different matrix.

PCA is also related to canonical correlation analysis (CCA). CCA defines coordinate systems that optimally describe the cross-covariance between two datasets while PCA defines a new orthogonal coordinate system that optimally describes variance in a single dataset.

## Details

PCA is mathematically defined as an orthogonal linear transformation that transforms the data to a new coordinate system such that the greatest variance by any projection of the data comes to lie on the first coordinate (called the first principal component), the second greatest variance on the second coordinate, and so on.

Consider a data matrix, X, with zero empirical mean (the empirical (sample) mean of the distribution has been subtracted from the data set), where each of the n rows represents a different repetition of the experiment, and each of the p columns gives a particular kind of datum (say, the results from a particular probe).

Mathematically, the transformation is defined by a set of p-dimensional vectors of weights or loadings $\mathbf\left\{w\right\}_\left\{\left(k\right)\right\} = \left(w_1, \dots, w_p\right)_\left\{\left(k\right)\right\}$ that map each row vector $\mathbf\left\{x\right\}_\left\{\left(i\right)\right\}$ of X to a new vector of principal component scores $\mathbf\left\{t\right\}_\left\{\left(i\right)\right\} = \left(t_1, \dots, t_p\right)_\left\{\left(i\right)\right\}$, given by

$\left\{t_\left\{k\right\}\right\}_\left\{\left(i\right)\right\} = \mathbf\left\{x\right\}_\left\{\left(i\right)\right\} \cdot \mathbf\left\{w\right\}_\left\{\left(k\right)\right\}$

in such a way that the individual variables of t considered over the data set successively inherit the maximum possible variance from x, with each loading vector w constrained to be a unit vector.

### First component

$\mathbf\left\{w\right\}_\left\{\left(1\right)\right\}$
= \underset{\Vert \mathbf{w} \Vert = 1}{\operatorname{\arg\,max}}\,\{ \sum_i \left(t_{1}\right)^2_{(i)} \}
= \underset{\Vert \mathbf{w} \Vert = 1}{\operatorname{\arg\,max}}\, \sum_i \left(\mathbf{x}_{(i)} \cdot \mathbf{w} \right)^2


Equivalently, writing this in matrix form gives

$\mathbf\left\{w\right\}_\left\{\left(1\right)\right\}$
= \underset{\Vert \mathbf{w} \Vert = 1}{\operatorname{\arg\,max}}\, \{ \Vert \mathbf{Xw} \Vert^2 \}
= \underset{\Vert \mathbf{w} \Vert = 1}{\operatorname{\arg\,max}}\, \{ \mathbf{w}^T \mathbf{X}^T \mathbf{X w} \}


Since w(1) has been defined to be a unit vector, it equivalently also satisfies

$\mathbf\left\{w\right\}_\left\{\left(1\right)\right\}$
 = \underset{\Vert \mathbf{w} \Vert = 1}{\operatorname{\arg\,max}}\, \left\{ \frac{\mathbf{w}^T\mathbf{X}^T \mathbf{X w}}{\mathbf{w}^T \mathbf{w}} \right\}


The quantity to be maximised can be recognised as a Rayleigh quotient. A standard result for a symmetric matrix such as XTX is that the quotient's maximum possible value is the largest eigenvalue of the matrix, which occurs when w is the corresponding eigenvector.

With w(1) found, the first component of a data vector x(i) can then be given as a score t1(i) = x(i)w(1) in the transformed co-ordinates, or as the corresponding vector in the original variables, {x(i)w(1)} w(1).

### Further components

The kth component can be found by subtracting the first k − 1 principal components from X:

$\mathbf\left\{\hat\left\{X\right\}\right\}_\left\{k - 1\right\}$
= \mathbf{X} -
\sum_{s = 1}^{k - 1}
\mathbf{X} \mathbf{w}_{(s)} \mathbf{w}_{(s)}^{\rm T}


and then finding the loading vector which extracts the maximum variance from this new data matrix

$\mathbf\left\{w\right\}_\left\{\left(k\right)\right\}$
= \underset{\Vert \mathbf{w} \Vert = 1}{\operatorname{arg\,max}} \left\{


\Vert \mathbf{\hat{X}}_{k - 1} \mathbf{w} \Vert^2 \right\}

 = \underset{\Vert \mathbf{w} \Vert = 1}{\operatorname{\arg\,max}}\, \left\{ \tfrac{\mathbf{w}^T\mathbf{\hat{X}}_{k - 1}^T \mathbf{\hat{X}}_{k - 1} \mathbf{w}}{\mathbf{w}^T \mathbf{w}} \right\}


It turns out that this gives the remaining eigenvectors of XTX, with the maximum values for the quantity in brackets given by their corresponding eigenvalues.

The kth principal component of a data vector x(i) can therefore be given as a score tk(i) = x(i)w(k) in the transformed co-ordinates, or as the corresponding vector in the space of the original variables, {x(i)w(k)} w(k), where w(k) is the kth eigenvector of XTX.

The full principal components decomposition of X can therefore be given as

$\mathbf\left\{T\right\} = \mathbf\left\{X\right\} \mathbf\left\{W\right\}$

where W is a p-by-p matrix whose columns are the eigenvectors of XTX

### Covariances

XTX itself can be recognised as proportional to the empirical sample covariance matrix of the dataset X.

The sample covariance Q between two of the different principal components over the dataset is given by

\begin\left\{align\right\}

Q(\mathrm{PC}_{(j)}, \mathrm{PC}_{(k)}) & \propto (\mathbf{X}\mathbf{w}_{(j)}) \cdot (\mathbf{X}\mathbf{w}_{(k)}) \\ & = \mathbf{w}_{(j)}^T \mathbf{X}^T \mathbf{X} \mathbf{w}_{(k)} \\ & = \mathbf{w}_{(j)}^T \lambda_{(k)} \mathbf{w}_{(k)} \\ & = \lambda_{(k)} \mathbf{w}_{(j)}^T \mathbf{w}_{(k)} \end{align}

where the eigenvector property of w(k) has been used to move from line 2 to line 3. However eigenvectors w(j) and w(k) corresponding to eigenvalues of a symmetric matrix are orthogonal (if the eigenvalues are different), or can be orthogonalised (if the vectors happen to share an equal repeated value). The product in the final line is therefore zero; there is no sample covariance between different principal components over the dataset.

Another way to characterise the principal components transformation is therefore as the transformation to coordinates which diagonalise the empirical sample covariance matrix.

In matrix form, the empirical covariance matrix for the original variables can be written

$\mathbf\left\{Q\right\} \propto \mathbf\left\{X\right\}^T \mathbf\left\{X\right\} = \mathbf\left\{W\right\} \mathbf\left\{\Lambda\right\} \mathbf\left\{W\right\}^T$

The empirical covariance matrix between the principal components becomes

$\mathbf\left\{W\right\}^T \mathbf\left\{Q\right\} \mathbf\left\{W\right\} \propto \mathbf\left\{W\right\}^T \mathbf\left\{W\right\} \, \mathbf\left\{\Lambda\right\} \, \mathbf\left\{W\right\}^T \mathbf\left\{W\right\}$

= \mathbf{\Lambda}

where Λ is the diagonal matrix of eigenvalues λ(k) of XTX

(k) being equal to the sum of the squares over the dataset associated with each component k: λ(k) = Σi tk2(i) = Σi (x(i)w(k))2)

### Dimensionality reduction

The faithful transformation T = X W maps a data vector x(i) from an original space of p variables to a new space of p variables which are uncorrelated over the dataset. However, not all the principal components need to be kept. Keeping only the first L principal components, produced by using only the first L loading vectors, gives the truncated transformation

$\mathbf\left\{T\right\}_L = \mathbf\left\{X\right\} \mathbf\left\{W\right\}_L$

where the matrix TL now has n rows but only L columns. By construction, of all the transformed data matrices with only L columns, this score matrix maximises the variance in the original data that has been preserved, while minimising the total squared reconstruction error ||T − TL||2.

Such dimensionality reduction can be a very useful step for visualising and processing high-dimensional datasets, while still retaining as much of the variance in the dataset as possible. For example, selecting L = 2 and keeping only the first two principal components finds the two-dimensional plane through the high-dimensional dataset in which the data is most spread out, so if the data contains clusters these too may be most spread out, and therefore most visible to be plotted out in a two-dimensional diagram; whereas if two directions through the data (or two of the original variables) are chosen at random, the clusters may be much less spread apart from each other, and may in fact be much more likely to substantially overlay each other, making them indistinguishable.

Similarly, in regression analysis, the larger the number of explanatory variables allowed, the greater is the chance of overfitting the model, producing conclusions that fail to generalise to other datasets. One approach, especially when there are strong correlations between different possible explanatory variables, is to reduce them to a few principal components and then run the regression against them, a method called principal component regression.

Dimensionality reduction may also be appropriate when the variables in a dataset are noisy. If each column of the dataset contains independent identically distributed Gaussian noise, then the columns of T will also contain similarly identically distributed Gaussian noise (such a distribution is invariant under the effects of the matrix W, which can be thought of as a high-dimensional rotation of the co-ordinate axes). However, with more of the total variance concentrated in the first few principal components compared to the same noise variance, the proportionate effect of the noise is less -- the first components achieve a higher signal-to-noise ratio. PCA thus can have the effect of concentrating much of the signal into the first few principal components, which can usefully be captured by dimensionality reduction; while the later principal components may be dominated by noise, and so disposed of without great loss.

### Singular value decomposition

The principal components transformation can also be associated with another matrix factorisation, the singular value decomposition (SVD) of X,

$\mathbf\left\{X\right\} = \mathbf\left\{U\right\}\mathbf\left\{\Sigma\right\}\mathbf\left\{W\right\}^T$

Here Σ is a p-by-p diagonal matrix of positive numbers σ(k), called the singular values of X; U is an n-by-p matrix, the columns of which are orthogonal unit vectors of length n called the left singular vectors of X; and W is a p-by-p whose columns are orthogonal unit vectors of length p and called the right singular vectors of X.

In terms of this factorisation, the matrix XTX can be written

\begin\left\{align\right\}

\mathbf{X}^T\mathbf{X} & = \mathbf{W}\mathbf{\Sigma}\mathbf{U}^T \mathbf{U}\mathbf{\Sigma}\mathbf{W}^T \\

                      & = \mathbf{W}\mathbf{\Sigma}^2\mathbf{W}^T


\end{align}

Comparison with the eigenvector factorisation of XTX establishes that the right singular vectors W of X are equivalent to the eigenvectors of XTX, while the singular values σ(k) of X are equal to the square roots of the eigenvalues λ(k) of XTX.

Using the singular value decomposition the score matrix T can be written

\begin\left\{align\right\}

\mathbf{T} & = \mathbf{X} \mathbf{W} \\

          & = \mathbf{U}\mathbf{\Sigma}\mathbf{W}^T \mathbf{W} \\
& = \mathbf{U}\mathbf{\Sigma}


\end{align} so each column of T is given by one of the left singular vectors of X multiplied by the corresponding singular value.

Efficient algorithms exist to calculate the SVD of X without having to form the matrix XTX, so computing the SVD is now the standard way to calculate a principal components analysis from a data matrix, unless only a handful of components are required.

As with the eigendecomposition, a truncated n-by-L score matrix TL can be obtained by considering only the first L largest singular values and their singular vectors:

$\mathbf\left\{T\right\}_L = \mathbf\left\{U\right\}_L\mathbf\left\{\Sigma\right\}_L = \mathbf\left\{X\right\} \mathbf\left\{W\right\}_L$

The truncation of a matrix M or T using a truncated singular value decomposition in this way produces a truncated matrix that is the nearest possible matrix of rank L to the original matrix, in the sense of the difference between the two having the smallest possible Frobenius norm, a result known as the Eckart–Young theorem .

## Further considerations

Given a set of points in Euclidean space, the first principal component corresponds to a line that passes through the multidimensional mean and minimizes the sum of squares of the distances of the points from the line. The second principal component corresponds to the same concept after all correlation with the first principal component has been subtracted from the points. The singular values (in Σ) are the square roots of the eigenvalues of the matrix XTX. Each eigenvalue is proportional to the portion of the "variance" (more correctly of the sum of the squared distances of the points from their multidimensional mean) that is correlated with each eigenvector. The sum of all the eigenvalues is equal to the sum of the squared distances of the points from their multidimensional mean. PCA essentially rotates the set of points around their mean in order to align with the principal components. This moves as much of the variance as possible (using an orthogonal transformation) into the first few dimensions. The values in the remaining dimensions, therefore, tend to be small and may be dropped with minimal loss of information (see below). PCA is often used in this manner for dimensionality reduction. PCA has the distinction of being the optimal orthogonal transformation for keeping the subspace that has largest "variance" (as defined above). This advantage, however, comes at the price of greater computational requirements if compared, for example and when applicable, to the discrete cosine transform, and in particular to the DCT-II which is simply known as the "DCT". Nonlinear dimensionality reduction techniques tend to be more computationally demanding than PCA.

PCA is sensitive to the scaling of the variables. If we have just two variables and they have the same sample variance and are positively correlated, then the PCA will entail a rotation by 45° and the "loadings" for the two variables with respect to the principal component will be equal. But if we multiply all values of the first variable by 100, then the principal component will be almost the same as that variable, with a small contribution from the other variable, whereas the second component will be almost aligned with the second original variable. This means that whenever the different variables have different units (like temperature and mass), PCA is a somewhat arbitrary method of analysis. (Different results would be obtained if one used Fahrenheit rather than Celsius for example.) Note that Pearson's original paper was entitled "On Lines and Planes of Closest Fit to Systems of Points in Space" – "in space" implies physical Euclidean space where such concerns do not arise. One way of making the PCA less arbitrary is to use variables scaled so as to have unit variance, by standardizing the data and hence use the autocorrelation matrix instead of the autocovariance matrix as a basis for PCA. However, this compresses the fluctuations in all dimensions of the signal space to unit variance.

Mean subtraction (a.k.a. "mean centering") is necessary for performing PCA to ensure that the first principal component describes the direction of maximum variance. If mean subtraction is not performed, the first principal component might instead correspond more or less to the mean of the data. A mean of zero is needed for finding a basis that minimizes the mean square error of the approximation of the data.

PCA is equivalent to empirical orthogonal functions (EOF), a name which is used in meteorology.

An autoencoder neural network with a linear hidden layer is similar to PCA. Upon convergence, the weight vectors of the K neurons in the hidden layer will form a basis for the space spanned by the first K principal components. Unlike PCA, this technique will not necessarily produce orthogonal vectors.

PCA is a popular primary technique in pattern recognition. It is not, however, optimized for class separability. An alternative is the linear discriminant analysis, which does take this into account.

## Table of symbols and abbreviations

Symbol Meaning Dimensions Indices
$\mathbf\left\{X\right\} = \\left\{ X\left[i,j\right] \\right\}$ data matrix, consisting of the set of all data vectors, one vector per row $n \times p$ $i = 1 \ldots n$
$j = 1 \ldots p$
$n \,$ the number of row vectors in the data set $1 \times 1$ scalar
$p \,$ the number of elements in each row vector (dimension) $1 \times 1$ scalar
$L \,$ the number of dimensions in the dimensionally reduced subspace, $1 \le L \le p$ $1 \times 1$ scalar
$\mathbf\left\{u\right\} = \\left\{ u\left[j\right] \\right\}$ vector of empirical means, one mean for each column j of the data matrix $p \times 1$ $j = 1 \ldots p$
$\mathbf\left\{s\right\} = \\left\{ s\left[j\right] \\right\}$ vector of empirical standard deviations, one standard deviation for each column j of the data matrix $p \times 1$ $j = 1 \ldots p$
$\mathbf\left\{h\right\} = \\left\{ h\left[i\right] \\right\}$ vector of all 1's $1 \times n$ $i = 1 \ldots n$
$\mathbf\left\{B\right\} = \\left\{ B\left[i,j\right] \\right\}$ deviations from the mean of each column j of the data matrix $n \times p$ $i = 1 \ldots n$
$j = 1 \ldots p$
$\mathbf\left\{Z\right\} = \\left\{ Z\left[m,n\right] \\right\}$ z-scores, computed using the mean and standard deviation for each row m of the data matrix $n \times p$ $i = 1 \ldots n$
$j = 1 \ldots p$
$\mathbf\left\{C\right\} = \\left\{ C\left[k, l\right] \\right\}$ covariance matrix $p \times p$ $k = 1 \ldots p$
$l = 1 \ldots p$
$\mathbf\left\{R\right\} = \\left\{ R\left[k, l\right] \\right\}$ correlation matrix $p \times p$ $k = 1 \ldots p$
$l = 1 \ldots p$
$\mathbf\left\{V\right\} = \\left\{ V\left[j, k\right] \\right\}$ matrix consisting of the set of all eigenvectors of C, one eigenvector per column $p \times p$ $j = 1 \ldots p$
$k = 1 \ldots p$
$\mathbf\left\{D\right\} = \\left\{ D\left[k, l\right] \\right\}$ diagonal matrix consisting of the set of all eigenvalues of C along its principal diagonal, and 0 for all other elements $p \times p$ $k = 1 \ldots p$
$l = 1 \ldots p$
$\mathbf\left\{W\right\} = \\left\{ W\left[j, k\right] \\right\}$ matrix of basis vectors, one vector per column, where each basis vector is one of the eigenvectors of C, and where the vectors in W are a sub-set of those in V $p \times L$ $j = 1 \ldots p$
$k = 1 \ldots L$
$\mathbf\left\{T\right\} = \\left\{ T\left[i, k\right] \\right\}$ matrix consisting of n row vectors, where each vector is the projection of the corresponding data vector from matrix X onto the basis vectors contained in the columns of matrix W. $n \times L$ $i = 1 \ldots n$
$k = 1 \ldots L$

## Properties and limitations of PCA

As noted above, the results of PCA depend on the scaling of the variables.

The applicability of PCA is limited by certain assumptions made in its derivation.

### PCA and information theory

The claim that the PCA used for dimensionality reduction preserves most of the information of the data is misleading. Indeed, without any assumption on the signal model, PCA cannot help to reduce the amount of information lost during dimensionality reduction, where information was measured using Shannon entropy.

Under the assumption that

$\mathbf\left\{x\right\}=\mathbf\left\{s\right\}+\mathbf\left\{n\right\}$

i.e., that the data vector $\mathbf\left\{x\right\}$ is the sum of the desired information-bearing signal $\mathbf\left\{s\right\}$ and a noise signal $\mathbf\left\{n\right\}$ one can show that PCA can be optimal for dimensionality reduction also from an information-theoretic point-of-view.

In particular, Linsker showed that if $\mathbf\left\{s\right\}$ is Gaussian and $\mathbf\left\{n\right\}$ is Gaussian noise with a covariance matrix proportional to the identity matrix, the PCA maximizes the mutual information $I\left(\mathbf\left\{y\right\};\mathbf\left\{s\right\}\right)$ between the desired information $\mathbf\left\{s\right\}$ and the dimensionality-reduced output $\mathbf\left\{y\right\}=\mathbf\left\{W\right\}_L^T\mathbf\left\{x\right\}$.

If the noise is still Gaussian and has a covariance matrix proportional to the identity matrix (i.e., the components of the vector $\mathbf\left\{n\right\}$ are iid), but the information-bearing signal $\mathbf\left\{s\right\}$ is non-Gaussian (which is a common scenario), PCA at least minimizes an upper bound on the information loss, which is defined as

$I\left(\mathbf\left\{x\right\};\mathbf\left\{s\right\}\right)-I\left(\mathbf\left\{y\right\};\mathbf\left\{s\right\}\right).$

The optimality of PCA is also preserved if the noise $\mathbf\left\{n\right\}$ is iid and at least more Gaussian (in terms of the Kullback–Leibler divergence) than the information-bearing signal $\mathbf\left\{s\right\}$. In general, even if the above signal model holds, PCA loses its information-theoretic optimality as soon as the noise $\mathbf\left\{n\right\}$ becomes dependent.

## Computing PCA using the covariance method

The following is a detailed description of PCA using the covariance method (see also ].

The goal is to transform a given data set X of dimension p to an alternative data set Y of smaller dimension L. Equivalently, we are seeking to find the matrix Y, where Y is the Karhunen–Loève transform (KLT) of matrix X:

$\mathbf\left\{Y\right\} = \mathbb\left\{KLT\right\} \\left\{ \mathbf\left\{X\right\} \\right\}$

### Organize the data set

Suppose you have data comprising a set of observations of p variables, and you want to reduce the data so that each observation can be described with only L variables, L < p. Suppose further, that the data are arranged as a set of n data vectors $\mathbf\left\{x\right\}_1 \ldots \mathbf\left\{x\right\}_n$ with each $\mathbf\left\{x\right\}_i$ representing a single grouped observation of the p variables.

• Write $\mathbf\left\{x\right\}_1 \ldots \mathbf\left\{x\right\}_n$ as row vectors, each of which has p columns.
• Place the row vectors into a single matrix X of dimensions n × p.

### Calculate the empirical mean

• Find the empirical mean along each dimension j = 1, ..., p.
• Place the calculated mean values into an empirical mean vector u of dimensions p × 1.
$u\left[j\right] = \left\{1 \over N\right\} \sum_\left\{i=1\right\}^n X\left[i,j\right]$

### Calculate the deviations from the mean

Mean subtraction is an integral part of the solution towards finding a principal component basis that minimizes the mean square error of approximating the data. Hence we proceed by centering the data as follows:

• Subtract the empirical mean vector u from each row of the data matrix X.
• Store mean-subtracted data in the n × p matrix B.
$\mathbf\left\{B\right\} = \mathbf\left\{X\right\} - \mathbf\left\{h\right\}\mathbf\left\{u\right\}^\left\{T\right\}$
where h is an n × 1 column vector of all 1s:
$h\left[i\right] = 1 \, \qquad \qquad \text\left\{for \right\} i = 1, \ldots, n$

### Find the covariance matrix

$\mathbf\left\{C\right\} = \left\{ 1 \over \left\{n-1\right\} \right\} \mathbf\left\{B\right\}^\left\{*\right\} \cdot \mathbf\left\{B\right\}$
where
$* \$ is the conjugate transpose operator. Note that if B consists entirely of real numbers, which is the case in many applications, the "conjugate transpose" is the same as the regular transpose.
• Please note that outer products apply to vectors. For tensor cases we should apply tensor products, but the covariance matrix in PCA is a sum of outer products between its sample vectors; indeed, it could be represented as B*.B. See the covariance matrix sections on the discussion page for more information.
• The reasoning behind using N-1 instead of N to calculate the covariance is Bessel's correction

### Find the eigenvectors and eigenvalues of the covariance matrix

$\mathbf\left\{V\right\}^\left\{-1\right\} \mathbf\left\{C\right\} \mathbf\left\{V\right\} = \mathbf\left\{D\right\}$
where D is the diagonal matrix of eigenvalues of C. This step will typically involve the use of a computer-based algorithm for computing eigenvectors and eigenvalues. These algorithms are readily available as sub-components of most matrix algebra systems, such as R, MATLAB, Mathematica, SciPy, IDL (Interactive Data Language), or GNU Octave as well as OpenCV.
• Matrix D will take the form of an M × M diagonal matrix, where
$D\left[k,l\right] = \lambda_k \qquad \text\left\{for \right\} k = l = j$
is the jth eigenvalue of the covariance matrix C, and
$D\left[k,l\right] = 0 \qquad \text\left\{for \right\} k \ne l.$
• Matrix V, also of dimension p × p, contains p column vectors, each of length p, which represent the p eigenvectors of the covariance matrix C.
• The eigenvalues and eigenvectors are ordered and paired. The jth eigenvalue corresponds to the jth eigenvector.

### Rearrange the eigenvectors and eigenvalues

• Sort the columns of the eigenvector matrix V and eigenvalue matrix D in order of decreasing eigenvalue.
• Make sure to maintain the correct pairings between the columns in each matrix.

### Compute the cumulative energy content for each eigenvector

• The eigenvalues represent the distribution of the source data's energy among each of the eigenvectors, where the eigenvectors form a basis for the data. The cumulative energy content g for the jth eigenvector is the sum of the energy content across all of the eigenvalues from 1 through j:
$g\left[m\right] = \sum_\left\{k=1\right\}^j D\left[k,k\right] \qquad \mathrm\left\{for\right\} \qquad j = 1,\dots,p$

### Select a subset of the eigenvectors as basis vectors

• Save the first L columns of V as the p × L matrix W:
$W\left[k,l\right] = V\left[k,l\right] \qquad \mathrm\left\{for\right\} \qquad k = 1,\dots,p \qquad l = 1,\dots,L$
where
$1 \leq L \leq p.$
• Use the vector g as a guide in choosing an appropriate value for L. The goal is to choose a value of L as small as possible while achieving a reasonably high value of g on a percentage basis. For example, you may want to choose L so that the cumulative energy g is above a certain threshold, like 90 percent. In this case, choose the smallest value of L such that
$\frac\left\{g\left[L\right]\right\}\left\{g\left[p\right]\right\} \ge 0.9\,$

### Convert the source data to z-scores (optional)

• Create an p × 1 empirical standard deviation vector s from the square root of each element along the main diagonal of the diagonalized covariance matrix C. (Note, that scaling operations do not commute with the KLT thus we must scale by the variances of the already-decorrelated vector, which is the diagonal of C) :
$\mathbf\left\{s\right\} = \\left\{ s\left[j\right] \\right\} = \\left\{ \sqrt\left\{C\left[j,j\right]\right\} \\right\} \qquad \text\left\{for \right\} j = 1, \ldots, p$
• Calculate the n × p z-score matrix:
$\mathbf\left\{Z\right\} = \left\{ \mathbf\left\{B\right\} \over \mathbf\left\{h\right\} \cdot \mathbf\left\{s\right\}^\left\{T\right\} \right\}$ (divide element-by-element)
• Note: While this step is useful for various applications as it normalizes the data set with respect to its variance, it is not integral part of PCA/KLT

### Project the z-scores of the data onto the new basis

• The projected vectors are the columns of the matrix
$\mathbf\left\{T\right\} = \mathbf\left\{Z\right\} \cdot \mathbf\left\{W\right\} = \mathbb\left\{KLT\right\} \\left\{ \mathbf\left\{X\right\} \\right\}.$

## Derivation of PCA using the covariance method

Let X be a d-dimensional random vector expressed as column vector. Without loss of generality, assume X has zero mean.

We want to find $\left(\ast\right)\,$ a $d \times d$ orthonormal transformation matrix P so that PX has a diagonal covariant matrix (i.e. PX is a random vector with all its distinct components pairwise uncorrelated).

A quick computation assuming $P$ were unitary yields:



\begin{array}[t]{rcl} \operatorname{var}(PX) &= &\mathbb{E}[PX~(PX)^{\dagger}]\\ &= &\mathbb{E}[PX~X^{\dagger}P^{\dagger}]\\ &= &P~\mathbb{E}[XX^{\dagger}]P^{\dagger}\\ &= &P~\operatorname{var}(X)P^{-1}\\ \end{array}

Hence $\left(\ast\right)\,$ holds if and only if $\operatorname\left\{var\right\}\left(X\right)$ were diagonalisable by $P$.

This is very constructive, as var(X) is guaranteed to be a non-negative definite matrix and thus is guaranteed to be diagonalisable by some unitary matrix.

### Iterative computation

In practical implementations especially with high dimensional data (large p), the covariance method is rarely used because it is not efficient. One way to compute the first principal component efficiently is shown in the following pseudo-code, for a data matrix X with zero mean, without ever computing its covariance matrix

$\mathbf\left\{r\right\} =$ a random vector of length p
do c times:
$\mathbf\left\{s\right\} = 0$ (a vector of length p)
for each row $\mathbf\left\{x\right\} \in \mathbf\left\{X\right\}$
$\mathbf\left\{s\right\} = \mathbf\left\{s\right\} + \left(\mathbf\left\{x\right\} \cdot \mathbf\left\{r\right\}\right)\mathbf\left\{x\right\}$
$\mathbf\left\{r\right\} = \frac\left\{\mathbf\left\{s\right\}\right\}\left\{|\mathbf\left\{s\right\}|\right\}$
return $\mathbf\left\{r\right\}$


This algorithm is simply an efficient way of calculating XTX r, normalizing, and placing the result back in r (power iteration). It avoids the np2 operations of calculating the covariance matrix. r will typically get close to the first principal component of X within a small number of iterations, c. (The magnitude of s will be larger after each iteration. Convergence can be detected when it increases by an amount too small for the precision of the machine.)

Subsequent principal components can be computed by subtracting component r from X (see Gram–Schmidt) and then repeating this algorithm to find the next principal component. However this simple approach is not numerically stable if more than a small number of principal components are required, because imprecisions in the calculations will additively affect the estimates of subsequent principal components. More advanced methods build on this basic idea, as with the closely related Lanczos algorithm.

One way to compute the eigenvalue that corresponds with each principal component is to measure the difference in mean-squared-distance between the rows and the centroid, before and after subtracting out the principal component. The eigenvalue that corresponds with the component that was removed is equal to this difference.

### The NIPALS method

For very high-dimensional datasets, such as those generated in the *omics sciences (e.g., genomics, metabolomics) it is usually only necessary to compute the first few PCs. The non-linear iterative partial least squares (NIPALS) algorithm calculates t1 and w1T from X. The outer product, t1w1T can then be subtracted from X leaving the residual matrix E1. This can be then used to calculate subsequent PCs. This results in a dramatic reduction in computational time since calculation of the covariance matrix is avoided.

However, for large data matrices, or matrices that have a high degree of column collinearity, NIPALS suffers from loss of orthogonality due to machine precision limitations accumulated in each iteration step. A Gram–Schmidt (GS) re-orthogonalization algorithm is applied to both the scores and the loadings at each iteration step to eliminate this loss of orthogonality.

### Online/sequential estimation

In an "online" or "streaming" situation with data arriving piece by piece rather than being stored in a single batch, it is useful to make an estimate of the PCA projection that can be updated sequentially. This can be done efficiently, but requires different algorithms.

## Relation between PCA and K-means clustering

It has been shown recently (2001,2004) that the relaxed solution of K-means clustering, specified by the cluster indicators, is given by the PCA principal components, and the PCA subspace spanned by the principal directions is identical to the cluster centroid subspace specified by the between-class scatter matrix. Thus PCA automatically projects to the subspace where the global solution of K-means clustering lies, and thus facilitates K-means clustering to find near-optimal solutions.

## Correspondence analysis

Correspondence analysis (CA) was developed by Jean-Paul Benzécri and is conceptually similar to PCA, but scales the data (which should be non-negative) so that rows and columns are treated equivalently. It is traditionally applied to contingency tables. CA decomposes the chi-squared statistic associated to this table into orthogonal factors. Because CA is a descriptive technique, it can be applied to tables for which the chi-squared statistic is appropriate or not. Several variants of CA are available including detrended correspondence analysis and canonical correspondence analysis. One special extension is multiple correspondence analysis, which may be seen as the counterpart of principal component analysis for categorical data.

## Generalizations

### Nonlinear generalizations

Most of the modern methods for nonlinear dimensionality reduction find their theoretical and algorithmic roots in PCA or K-means. Pearson's original idea was to take a straight line (or plane) which will be "the best fit" to a set of data points. Principal curves and manifolds give the natural geometric framework for PCA generalization and extend the geometric interpretation of PCA by explicitly constructing an embedded manifold for data approximation, and by encoding using standard geometric projection onto the manifold, as it is illustrated by Fig. See also the elastic map algorithm and principal geodesic analysis. Another popular generalization is kernel PCA, which corresponds to PCA performed in a reproducing kernel Hilbert space associated with a positive definite kernel.

### Multilinear generalizations

In multilinear subspace learning, PCA is generalized to multilinear PCA (MPCA) that extracts features directly from tensor representations. MPCA is solved by performing PCA in each mode of the tensor iteratively. MPCA has been applied to face recognition, gait recognition, etc. MPCA is further extended to uncorrelated MPCA, non-negative MPCA and robust MPCA.

### Higher order

N-way principal component analysis may be performed with models such as Tucker decomposition, PARAFAC, multiple factor analysis, co-inertia analysis, STATIS, and DISTATIS.

### Robustness – weighted PCA

While PCA finds the mathematically optimal method (as in minimizing the squared error), it is sensitive to outliers in the data that produce large errors PCA tries to avoid. It therefore is common practice to remove outliers before computing PCA. However, in some contexts, outliers can be difficult to identify. For example in data mining algorithms like correlation clustering, the assignment of points to clusters and outliers is not known beforehand. A recently proposed generalization of PCA based on a weighted PCA increases robustness by assigning different weights to data objects based on their estimated relevancy.

## Software/source code

• Mathematica implements principal component analysis with the PrincipalComponents command using both covariance and correlation methods.
• In the NAG Library, principal components analysis is implemented via the g03aa routine (available in both the Fortran and the C versions of the Library).
• In the MATLAB Statistics Toolbox, the functions princomp and pca (R2012b) give the principal components, while the function pcares gives the residuals and reconstructed matrix for a low-rank PCA approximation. An example MATLAB implementation of PCA is available.
• in GNU Octave, a free software computational environment mostly compatible with MATLAB, the function princomp gives the principal component.
• in the free statistical package R, the functions princomp and prcomp can be used for principal component analysis; prcomp uses singular value decomposition which generally gives better numerical accuracy. Recently there has been an explosion in implementations of principal component analysis in various R packages. Some packages that implement PCA in R, include, but are not limited to: ade4, vegan, ExPosition, and FactoMineR
• in SAS, PROC FACTOR offers principal components analysis.
• In XLMiner, the Principal Components tab can be used for principal component analysis.
• In Stata, the pca command provides principal components analysis.
• Cornell Spectrum Imager – An open-source toolset built on ImageJ. Enables quick easy PCA analysis for 3D datacubes.
• imDEV – Free Excel addin to calculate principal components using R package
• "ViSta: The Visual Statistics System" – a free software that provides principal components analysis, simple and multiple correspondence analysis.
• "Spectramap" – software to create a biplot using principal components analysis, correspondence analysis or spectral map analysis.
• FinMath – a .NET numerical library containing an implementation of PCA.
• The Unscrambler is a multivariate analysis software enabling Principal Component Analysis (PCA) with PCA Projection.
• OpenCV
• NMath, a proprietary numerical library containing PCA for the .NET Framework.
• In IDL, the principal components can be calculated using the function pcomp.
• Weka computes principal components.
• Software for analyzing multivariate data with instant response using PCA
• Orange (software) supports PCA through its Linear Projection widget.
• A version of PCA adapted for population genetics analysis can be found in the suite EIGENSOFT.
• PCA can also be performed by the statistical software Partek Genomics Suite.
• The libpca C++ library offers PCA and corresponding transformations