Principal Component Analysis (PCA) is one of the most commonly used approaches for dimension reduction and visualization. The idea is to capture major signals of variation in a dataset. A demonstration of the search for a direction is provided at this r-bloggers site:
Rotating a projection direction changes the spread of the projected observations. PCA selects the direction with the largest variance.
Letβs look at a two-dimensional case. We are trying to find a line through the origin such that, if all points are projected onto this line, their coordinates have the largest variance compared with any other direction. We begin with centered observations and return to the centering issue below.
The supplied sample contains 100 observations from a bivariate normal distribution with mean and covariance
It is the original lectureβs realization, generated with set.seed(1) and MASS::mvrnorm(). Both languages use these same observations. We subtract the sample mean from each variable, without dividing by its standard deviation.
Letβs start by finding a direction onto which we can project all the observations. We want this projection to have the largest variation. The direction that goes along the spread of the data is the best choice for this purpose.
Once we have the first direction, we can remove its projection from the original variables and search for a second direction that is orthogonal to , with , and captures the largest remaining variation. In two dimensions, the perpendicular direction is already determined up to its sign.
The standard deviations are about 1.08 and 0.22. Most of the variation is along the first direction. The near-zero inner product above confirms that the directions are perpendicular.
SVD View
Formally, we can generalize this to a centered data matrix . The key tool is the singular value decomposition (SVD):
The columns of are the directions, also called loadings. Thus, is its first column, is its second column, and so on. The diagonal entries of are the singular values.
The coordinates obtained by projecting observations onto these directions are the scores:
The score matrix is , rather than alone. Using sample variance with denominator , the standard deviation on direction is . Its proportion of explained variance is
Both prcomp() in R and PCA() in Python use the convention for reported variances. Multiplying a loading and its scores by describes the same axis, so software can return different signs while producing the same PCA.
Optimization View
An alternative way to understand PCA is by matrix approximation. If we want a rank-one matrix that best approximates in the Frobenius norm, the problem is
The solution is . Keeping more singular components gives the corresponding best approximation of higher rank. Capturing the largest variation and minimizing squared reconstruction error are two views of the same calculation.
Another formulation uses the eigendecomposition of :
The PCA directions are its eigenvectors, and the corresponding eigenvalues are the squared singular values.
Centering Issue
One thing we need to take care of is centering. This is why we subtracted the column means at the beginning. We only centered the data; we did not scale them. Without centering, a leading singular direction can point toward the center of the data cloud rather than follow its variation around that center.
When is centered, the sample covariance matrix is . Hence PCA also performs an eigendecomposition of the sample covariance matrix. The factor changes the eigenvalues but not the directions.
For higher-dimensional data, we usually visualize the first two or three PC coordinates. The scores can be obtained directly from the fitted PCA object or by multiplying the centered data matrix by the loading matrix.
plot(pcafit$x[, 1], pcafit$x[, 2], asp =1,pch =19, cex =0.75, col ="#13294B",xlab ="First PC score", ylab ="Second PC score")abline(h =0, col ="#2F6FB3", lwd =2)abline(v =0, col ="#C84A16", lwd =2)
The same observations expressed in principal-component coordinates.
The two printed calculations agree. Changing coordinates concentrates most of the variation on the first axis. No information is lost when both components are retained. In R, both princomp() and prcomp() perform PCA; we use prcomp() throughout this lecture for its SVD computation and sample-variance convention.
Scaling Issue
For ordinary covariance PCA, we center the variables. Whether to scale each variable to standard deviation one depends on the application. When variables have very different units or numerical scales, such as age and RNA expression, scaling prevents a few variables from dominating the PC loadings solely because of their units.
When all variables are of a similar type, such as pixel intensities in an image, retaining the original scale can be preferable. Variables with larger variation may carry more signal, and scaling may lose that information. The examples below center each variable without scaling it.
Example 1: iris Data
We use the iris data again. All four measurements are considered in this analysis. Both languages read the same course copy. Species labels are used only to color the result, after PCA has been fitted. We first plot the first and second PC coordinates.
Setosa is clearly separated, while the other two species overlap. One may also plot all pairs of PC coordinates to see whether lower components provide useful information.
Lower components usually account for less variation. The eigenvalue plot, also called a scree plot, shows how much variance each component carries. The first iris component accounts for about 92.5% of the total variance, and the first two together account for about 97.8%.
Feature contributions to a PC can be assessed through the magnitude of its loadings. This table shows that Petal.Length has the largest absolute loading on the first PC, about 0.8567.
We can visualize the loadings on the first two PCs. Each point now represents a variable, rather than an observation. This can be helpful when the number of variables is large.
The handwritten ZIP code digits data contain 7,291 training observations and 2,007 test observations. Each image is a grayscale image, converted to a vector of 256 pixel intensities. The first column is the true digit. We use only the 256 pixel columns to fit PCA, and use the digit labels afterward to interpret the plots.
Both languages read the same training data. The test data are also available, although the visualizations here use the training observations. Here is a sample of six images for each digit, with digits 0 through 9 arranged in columns.
Letβs do a simpler task first, using just three digits: 1, 4, and 8. This gives 2,199 observations and 256 variables. We center each pixel across observations without scaling its variance.
zip_pc <-prcomp(zip_sub, center =TRUE, scale. =FALSE)plot(seq_along(zip_pc$sdev), zip_pc$sdev^2, type ="l", col ="#2F6FB3",xlab ="Principal component", ylab ="Variance")
The first few components carry much more variation than later ones. A pairwise plot of the first four PCs helps us inspect which directions separate the three digit labels.
Letβs look at the first two PCs more closely. Even without knowing the true class, the uncolored plot suggests several groups. Some overlap remains, so a visual grouping is not a perfect recovery of the digit labels.
Finally, letβs briefly look at PCA for all ten digits. More components are needed to represent this larger collection of image shapes. As before, the true digit column is excluded from the fit. You can also plot other PC coordinates to look for additional information.
The first two PCs retain large directions of pixel variation, but their score plot still contains considerable overlap among the ten digit labels. PCA is useful for visualization without being designed to separate the known classes.