Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

PCA and Covariance Matrix Eigendecomposition

Introduction

In our previous lessons, we've built a strong geometric foundation in linear algebra, culminating in understanding projections and decompositions like SVD. We saw how these tools allow us to find optimal approximations and transform data into more revealing coordinate systems. Today, we'll explore a powerful application of these ideas: Principal Component Analysis (PCA).

This lesson serves as a capstone for our linear algebra module and a bridge to machine learning. PCA is a cornerstone of classical data analysis, used to simplify complex, high-dimensional datasets. For your goal of mastering both classical and modern AI, understanding PCA is crucial, as it represents the linear, geometric ancestor to non-linear dimensionality reduction techniques like the autoencoders we will encounter in deep learning.

Our objective is to understand PCA's core purpose—finding the most meaningful directions in a dataset—and to establish its fundamental identity: PCA is achieved by performing an eigendecomposition on the data's covariance matrix.

The Goal of PCA: Finding a Better Basis

Imagine you are working with a dataset from a physics simulation or a 3D scanner. You might have hundreds or even thousands of measurements for each data point. It's likely that many of these measurements are correlated or redundant. For instance, two nearby sensors might record very similar temperature values. The goal of dimensionality reduction is to find a more compact representation of this data, capturing the "essence" while discarding redundancy and noise.

PCA provides a formal, non-parametric way to do this. It aims to find a new coordinate system, a new basis, for the data. The key idea is that this new basis should be chosen so that the axes point in the directions of maximum variance in the data.

To get an intuitive feel for this, let's watch a short video that explains the motivation behind PCA.

Principal Component Analysis (PCA)

The video "Principal Component Analysis" from the Visually Explained channel provides an excellent high-level overview.

Watch the first minute of the video, from the start to the end of the introduction. Pay attention to the idea of combining existing factors to create new, more informative ones called "principal components."

As the video suggests, PCA constructs new axes (principal components) by combining the original ones. These new axes are ranked by importance, where importance is measured by variance. The first principal component is the direction in which the data is most spread out. The second principal component is the direction of most variance in the data orthogonal to the first, and so on. This creates a new, hierarchical, and data-driven basis.

Quantifying Relationships: The Covariance Matrix

To formalize the idea of finding directions of maximal variance, we first need a tool to quantify the relationships between all the different features (dimensions) in our dataset. This tool is the covariance matrix.

Let's assume we have a dataset represented by a matrix , where each row is a data sample and each column is a different feature. Before we proceed, we must perform a crucial preprocessing step: mean-centering. For each feature column, we calculate its mean and subtract it from every entry in that column. This ensures our dataset is centered around the origin.

The covariance between two features measures how they vary together.

  • A large positive covariance means that when one feature's value is high, the other's tends to be high as well.
  • A large negative covariance means they are inversely related.
  • A covariance near zero suggests they are uncorrelated.

The covariance matrix, which we'll denote as , is a square, symmetric matrix where:

  • The entry on the diagonal is the variance of the -th feature.
  • The off-diagonal entry is the covariance between the -th and -th features.

If our data matrix is already mean-centered, its sample covariance matrix is defined as:

Our goal in PCA is to find a new basis where the features are uncorrelated.

Question: If we transform our data into a new representation where all features are uncorrelated, what would the covariance matrix of this new data look like?

Answer If all features are uncorrelated, then all the off-diagonal elements of the covariance matrix, which represent the covariances between different features, must be zero. Therefore, the covariance matrix would be a **diagonal matrix**.

This insight is the key. The entire problem of PCA reduces to finding a rotation (an orthogonal transformation) that diagonalizes the covariance matrix.

For a more thorough walkthrough of the concepts of variance, redundancy, and the construction of the covariance matrix, the following reading is highly recommended.

A TUTORIAL ON PRINCIPAL COMPONENT ANALYSIS

This tutorial by Jon Shlens provides a fantastic intuition-first derivation of PCA.

Please read Section 4, "Variance and the Goal." Focus on the segments from the beginning of the section through the introduction of the covariance matrix. This will solidify why the covariance matrix is the right tool for this job and why our goal is to diagonalize it.

The Solution: Eigendecomposition of the Covariance Matrix

We have now framed our problem: find an orthogonal transformation matrix that transforms our data into new data such that the covariance matrix of , , is diagonal.

Let our transformation be a rotation defined by an orthogonal matrix . The transformed data is . Let's see what the new covariance matrix becomes:

Using the property , we get:

Recognizing the term in the middle as the original covariance matrix , we have:

We want to be a diagonal matrix, let's call it . So the equation we need to solve is:

If we multiply from the left by , and recall that for an orthogonal matrix , we get:

So we arrive at:

This is precisely the eigenvalue equation for the matrix !

This is the central result of PCA.

  • The columns of the matrix are the eigenvectors of the covariance matrix . These eigenvectors are the principal components—the axes of our new, optimal basis.
  • The diagonal matrix contains the eigenvalues of . Each eigenvalue corresponds to the variance of the data projected onto its associated eigenvector .

The magnitude of the eigenvalues tells us the "importance" of each principal component. The eigenvector with the largest eigenvalue is the first principal component, capturing the direction of maximum variance. The eigenvector with the second-largest eigenvalue is the second principal component, and so on.

The image below provides a perfect visual summary. It shows two different 2D datasets (scatter plots). The principal components are the eigenvectors of the covariance matrix (), shown as the magenta and green vectors. The length of the vectors, representing the variance, corresponds to the eigenvalues ().

Two examples of 2D data distributions. The eigenvectors of the covariance matrix define the principal components (the axes of maximal variance), and the eigenvalues quantify the amount of variance along each of these axes.

To see this derivation presented from a slightly different but equally valid perspective, you can consult the following resource.

ML From Scratch, Part 6: Principal Component Analysis

This article offers a very direct derivation.

Read the section titled "Approach #2". It walks through the exact logic we just discussed, showing that transforming the data by the eigenvector matrix of the covariance matrix results in a new, diagonal covariance matrix.

The PCA Algorithm and Dimensionality Reduction

We can now summarize the entire PCA process as a concrete algorithm:

  1. Given an data matrix , where is the number of samples and is the number of features.
  2. Mean-center the data: For each feature (column), subtract its mean.
  3. Compute the covariance matrix: .
  4. Compute the eigendecomposition of : Find the eigenvalues and corresponding eigenvectors .
  5. Sort the components: Order the eigenvectors according to their corresponding eigenvalues, from largest to smallest. The sorted eigenvectors form the columns of your transformation matrix .
  6. Transform the data: The new data in the principal component basis is given by .

So, how does this lead to dimensionality reduction? We simply decide to keep only the top principal components, where . By projecting our data onto the subspace spanned by these first eigenvectors, we create a -dimensional representation that preserves the maximum possible variance from the original data. The amount of total variance captured by the first components is given by the ratio:

A common practice is to choose such that you retain a desired percentage of the variance, for example, 95% or 99%.

This process of selecting the most important components based on their associated variance is explained well in the following video.

Principal Component Analysis (PCA)

The video "Principal Component Analysis (PCA)" by Steve Brunton provides a clear explanation of how eigenvalues relate to variance explained.

Watch the segment from how eigenvalues quantify variance. This will clarify how you can use the eigenvalues to make a principled decision about how many dimensions to keep.

Conclusion

In this reference lesson, we've connected the abstract concepts of eigendecomposition to the practical task of dimensionality reduction. PCA provides a powerful, principled method for simplifying complex data by finding a new basis that reveals its underlying structure.

Key Takeaways:

  • PCA Goal: To find a new orthogonal basis for a dataset where the axes align with the directions of maximum variance.
  • Core Identity: This goal is accomplished by finding the eigenvectors of the data's covariance matrix.
  • Principal Components: The eigenvectors of the covariance matrix are the principal components, which form the new basis vectors.
  • Variance Explained: The corresponding eigenvalues quantify the variance along each principal component, allowing us to rank them by importance and perform dimensionality reduction by keeping only the most significant ones.

PCA is a purely linear technique; it discovers the best flat subspace (a hyperplane) to project the data onto. This provides a crucial point of contrast for our future studies. When we get to deep learning, we will explore autoencoders, which can be understood as a non-linear generalization of PCA. Instead of finding a flat hyperplane, an autoencoder can learn a complex, curved, low-dimensional manifold that the data lies on, enabling far more powerful compression and representation.

This lesson concludes our module on linear algebra. You now have the geometric and algebraic tools needed to understand how data is represented and manipulated. In our next module, we will turn to Multivariable Calculus. We'll develop the concepts of derivatives and gradients, which are the language of change and optimization, and are essential for training any machine learning model.

Can't find a good explanation? Sign up and we'll make it for you

Sign up