Principal Component Analysis

Overview

Dimensionality reduction

Problem. Many variables make data hard to read and models risky (multicollinearity, overfitting, broken assumptions).

Question. “How do I keep most of the information with only a few variables?”

\(\Longrightarrow\) Reduce the dimension of the feature space.

Fewer relationships to juggle, and a much smaller risk of overfitting.

PCA

What? A feature-extraction technique: it combines the input variables so you can drop the least important ones while keeping the most valuable parts of all. A bonus: the new variables are mutually independent.

How? It finds the directions, the principal components, in which the data vary most, assuming direction with the largest variance is the most important.

When? You cannot hand-pick variables to drop; you want independent inputs; you can live with less interpretable variables.

Principle

  • PC1 accounts for the largest possible variance: the direction where projections (red dots) spread out most.
  • PC2 is uncorrelated with PC1 and maximizes the remaining variance.
  • And so on.

Mathematical formalism

Context.

\(\mathbf{X}_1, \dots, \mathbf{X}_n\) a sample of \(n\) i.i.d. random vectors in \(\mathbb{R}^p\); \(\mathbb{X}\) the \(n \times p\) data matrix; \(\Sigma\) the covariance of the \(\mathbf{X}_i\)’s.

1st PC.

Search a linear projection \(\mathbf{a} \in \mathbb{R}^p\) of maximal variance: \(\mathbb{X}\mathbf{a}\), with per-coordinate variance \(\mathrm{Var}([\mathbb{X}\mathbf{a}]_i) = \mathbf{a}^\top \Sigma \mathbf{a}\).

  • A constraint is needed, as the maximum does not exist over all of \(\mathbb{R}^p\): impose \(\| \mathbf{a} \| = 1\).
  • Use the sample covariance \(S\) (unbiased for \(\Sigma\)) and solve \(\max_{\| \mathbf{a} \| = 1} \mathbf{a}^\top S \mathbf{a}\).
  • Solution: an eigenvector of \(S\) for the largest eigenvalue; the Lagrangian gives \(S\mathbf{a} = \lambda \mathbf{a}\).

R Packages

Principal component computation

  • prcomp() / princomp() from base stats;
  • PCA() from FactoMineR;
  • dudi.pca() from ade4.

Recommendation

Use FactoMineR::PCA().

Extraction and visualization

The factoextra package.

Case Study

Decathlon data. Athletes’ performance during two events (Decastar, OlympicG); \(41\) athletes described by \(13\) variables.

Objectives

Run a PCA on all athletes to:

  • Study individuals. Are some athletes close (similar results)? Establish profiles, oppose one group to another.
  • Study variables. Summarize the correlation matrix and look for synthetic variables; can one number summarize an athlete’s performance?
  • Link both. Characterize each group of athletes by variables.

PCA Terminology

Individuals. Active ones build the PCA; supplementary ones get coordinates predicted from it.

Variables. Active ones build the PCA; supplementary ones are predicted too, either

  • Continuous (cols 11, 12): rank and points;
  • Qualitative (col 13): the meeting (Olympic Game / Decastar), used to color individuals by group.

Data standardization

Why it matters

PCA maximizes variance, so units bias it: a variable in centimeters swamps one in meters, whatever their intrinsic variability.

\(\Longrightarrow\) We need to scale the variables prior to PCA!

A common solution: standardization

\[ x_{ij} \leftarrow \frac{x_{ij} - \overline{x}_j}{\sqrt{\frac{1}{n-1} \sum_{\ell=1}^n (x_{\ell j} - \overline{x}_j)^2}} \]

\(\Longrightarrow\) PCA() in FactoMineR standardizes automatically.

PCA() Syntax

PCA(
  # a data frame with n rows (individuals) and p columns (numeric variables)
  X = , 
  
  # number of dimensions kept in the results (by default 5)
  ncp = , 
  
  # a vector indicating the indexes of the supplementary individuals
  ind.sup = , 
  
  # a vector indicating the indexes of the quantitative supplementary variables
  quanti.sup = ,
  
  # a vector indicating the indexes of the categorical supplementary variables
  quali.sup = , 
  
  # boolean, if TRUE (default) a graph is displayed
  graph = 
)

Running PCA()

PCA(X = decathlon[, 1:10], graph = FALSE)
**Results for the Principal Component Analysis (PCA)**
The analysis was performed on 41 individuals, described by 10 variables
*The results are available in the following objects:

   name               description                          
1  "$eig"             "eigenvalues"                        
2  "$var"             "results for the variables"          
3  "$var$coord"       "coord. for the variables"           
4  "$var$cor"         "correlations variables - dimensions"
5  "$var$cos2"        "cos2 for the variables"             
6  "$var$contrib"     "contributions of the variables"     
7  "$ind"             "results for the individuals"        
8  "$ind$coord"       "coord. for the individuals"         
9  "$ind$cos2"        "cos2 for the individuals"           
10 "$ind$contrib"     "contributions of the individuals"   
11 "$call"            "summary statistics"                 
12 "$call$centre"     "mean of the variables"              
13 "$call$ecart.type" "standard error of the variables"    
14 "$call$row.w"      "weights for the individuals"        
15 "$call$col.w"      "weights for the variables"          

Visualization and Interpretation

The factoextra package

Whatever engine you used (prcomp(), PCA(), dudi.pca(), epPCA()), factoextra extracts and visualizes the results uniformly.

Useful functions

  • get_eigenvalue(): eigenvalues / variances of the components;
  • fviz_screeplot(): eigenvalues & proportion of explained variance;
  • get_pca_ind() / get_pca_var(): results for individuals / variables;
  • fviz_pca_ind() / fviz_pca_var(): plots for individuals / variables;
  • fviz_pca_biplot(): biplot of both.

Choice of the reduced dimension

Eigenvalues / Variances

Eigenvalues measure the amount of variation retained by each principal component.

eig_val <- get_eigenvalue(res_pca)
html_table(eig_val)

Choosing the appropriate number of PCs

Eigenvalues drive how many PCs to keep.

Guidelines.

  • An eigenvalue \(> 1\) means a PC accounts for more variance than a single standardized variable (a common cutoff when data are standardized);
  • Balance a small number of PCs (good reduction) against total explained variance;
  • Look for interesting patterns in the first few PCs.

Graphical tool.

fviz_screeplot(res_pca, addlabels = TRUE)

Analysis of the variables

Variable Information in PCA

Variable information extraction

var_info <- get_pca_var(res_pca)

Components

  • var_info$coord: coordinates of the variables;
  • var_info$cos2: quality of representation, var.cos2 = var.coord * var.coord;
  • var_info$contrib: contribution to each PC, (var.cos2 * 100) / (sum cos2 of the component).

Usage

  • How well do the PCs represent each variable?
  • Describe each PC by its most contributing variables.

$coord: Correlation variables & components

Property: column norms are 1 (eigenvectors).
Consequence: each coordinate lies in \([-1,1]\).

Contribution of PCs to variables

fviz_pca_var(): Correlation circle

fviz_pca_var(res_pca, col.var = "black")

$cos2: Quality of representation

Positive or negative strong correlations of a PC to a variable mean the PC represents it well.
Squared correlations therefore measure representation quality.

$cos2: Graphical tool 1

corrplot::corrplot(var_info$cos2, is.corr = FALSE)

$cos2: Graphical tool 2

# Total cos2 of variables on Dim.1 and Dim.2
factoextra::fviz_cos2(res_pca, choice = "var", axes = 1:2)

$cos2: Summary

  • High cos2 means the variable is well represented by that PC;
  • Low cos2 means it is poorly represented;
  • Near the circle: very well represented by the first two PCs;
  • Near the center: not well represented.

fviz_pca_var(X = res_pca, col.var = "cos2", gradient.cols = viridis(3), repel = TRUE)

Contribution of variables to PCs

$contrib: Important variables

  • Most important: variables correlating with Dim.1 and Dim.2;
  • Variables correlating with no PC (or only the last ones) can be removed.

$contrib: Graphical tool 1

corrplot::corrplot(var_info$contrib, is.corr = FALSE)

$contrib: Graphical tool 2

# Contributions of variables to PC1
factoextra::fviz_contrib(
  X = res_pca, 
  choice = "var", 
  axes = 1, 
  top = 10
)

# Contributions of variables to PC2
factoextra::fviz_contrib(
  X = res_pca, 
  choice = "var", 
  axes = 2, 
  top = 10
)

$contrib: Summary

factoextra::fviz_pca_var(
  X = res_pca, 
  col.var = "contrib",
  gradient.cols = viridis::viridis(3),
  repel = TRUE
)

Component description

res_pca_var_desc <- FactoMineR::dimdesc(res = res_pca, axes = c(1, 2), proba = 0.05)

Description of PC1

Description of PC2

Analysis of the individuals

The reduced space

Individual information extraction

ind_info <- get_pca_ind(res_pca)

Components

  • ind_info$coord: coordinates of the individuals;
  • ind_info$cos2: quality of representation, ind.cos2 = ind.coord * ind.coord;
  • ind_info$contrib: contribution of individuals, (ind.cos2 * 100) / (sum cos2 of the component).

Usage

  • The reduced space eases pattern spotting, if it represents them well;
  • Similar individuals are grouped together on the plot.

First factorial plane & quality

factoextra::fviz_pca_ind(
  X = res_pca, 
  col.ind = "cos2", 
  gradient.cols = viridis::viridis(3),
  repel = TRUE # Avoid text overlapping (slow if many points)
)

First factorial plane & contribution

# Total contribution on PC1 and PC2
factoextra::fviz_contrib(res_pca, choice = "ind", axes = 1:2)

First factorial plane colored by groups

factoextra::fviz_pca_ind(
  X = res_pca,
  col.ind = decathlon$competition[1:23], # color by groups
  palette = viridis::viridis(3),
  addEllipses = TRUE, # Concentration ellipses
  legend.title = "Competition"
)
  • Shows whether a factorial plane discriminates individuals by a feature;
  • Here Olympics score positively on PC1, Decastar negatively;
  • But the ellipses overlap significantly.

Combined variable and individual analysis

Biplot

fviz_pca_biplot(res_pca, repel = TRUE,
                col.var = "#2E9FDF", col.ind = "#696969")
  • Only useful with few variables & individuals, else unreadable;
  • Individuals and variables are not on the same scale: read directions, not absolute positions;
  • An individual on the same side as a variable has a high value for it; opposite side, a low value.

Interpretation

  • The first two dimensions resume 50% of total inertia (total variance);
  • 100m correlates negatively with long.jump: a short time goes with a big jump;
  • Axis 1 opposes athletes good everywhere (Karpov, Olympic) to those bad everywhere (Bourguignon, Decastar);
  • Axis 2 opposes strong (Discus, Shot.put) to weak athletes;
  • Strength is not much correlated with speed.

\(\Longrightarrow\) Four profiles: fast+strong (Sebrle), slow (Casarsa), fast but weak (Warners), slow and weak (Lorenzo).

Your turn

  • Download the lab file and related data sets from the course website in a folder on your computer.
  • Open the file 12-PCA-Exercises.qmd and perform the PCA analyses for the proposed data sets.

References