How does PCA work?

Authors
How does PCA work?

PCA (Principal Component Analysis) takes data with many columns and shrinks it to fewer columns, while keeping as much of the useful information as possible.

In this blog, we will learn about PCA, which stands for Principal Component Analysis. We will also see why we need PCA, what dimension and variance mean, what Principal Components are, how PCA works step by step, how many components we must keep, and where it works well and where it falls short.

We will cover the following:

  • What is PCA?
  • Why do we need PCA?
  • What does "dimension" mean?
  • The central idea behind PCA
  • What is variance?
  • What is a Principal Component?
  • How does PCA work, step by step
  • A numeric walk-through
  • How many components should we keep?
  • Seeing it in code
  • Advantages of PCA
  • Limitations of PCA
  • Where PCA is used

I am Amit Shekhar, Founder @ Outcome School, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

I teach AI and Machine Learning at Outcome School.

Let's get started.

What is PCA?

PCA is a method that takes data with many columns and shrinks it down to fewer columns, while keeping as much useful information as possible.

Here, Principal means most important, and a Component is a new column that we create from the old columns. So, PCA finds the most important new columns inside our data.

Let's say we have a spreadsheet with 100 columns. Many of those columns are repeating the same information in different ways. PCA looks at all of them and replaces them with just a few new columns that capture most of the information.

We can picture this shrinking like below:

   Original table                        Smaller table
   (100 columns)                         (2 columns)

   col1 col2 col3 ... col100             new1 new2
   ---- ---- ---- --- ------    PCA      ---- ----
    .    .    .   ...   .       --->      .    .
    .    .    .   ...   .                 .    .
    .    .    .   ...   .                 .    .

Here, we can see that PCA takes a wide table with many columns and gives us a narrow table with only a few new columns, while keeping almost the same information.

We have a detailed blog on Supervised vs Unsupervised Learning that explains where PCA fits as a dimensionality reduction technique in unsupervised learning.

Why do we need PCA?

The best way to learn this is by taking an example.

Suppose we collect data about people for a health study. For each person, we record many things: height in centimeters, height in inches, weight in kilograms, weight in pounds, age, daily steps, and etc.

Now, look closely. Height in centimeters and height in inches are basically the same information written twice. The same is true for weight in kilograms and weight in pounds. So, some of our columns are repeating each other.

When columns carry overlapping information like this, we say they are correlated. Correlated means they move together. Here, when one goes up, the other also goes up.

This creates a few problems.

Problem 1: Too many columns make the data hard to understand and slow to process. We call this the problem of high dimensionality. A dimension is a column, and we will explain this properly in the next section.

Problem 2: We cannot draw a picture of data with 100 columns. Humans can only see in two or three dimensions. So we cannot visualize the data to understand it.

Problem 3: Many Machine Learning models get confused or slow when there are too many columns, especially when many of them repeat the same information.

So, here comes PCA to the rescue.

PCA looks at all our columns, notices which ones overlap, and combines them into a few new columns that hold the real information without the repetition. This is why we need PCA.

What does "dimension" mean?

Before we go deeper, we must understand the word dimension, because PCA is often called a dimensionality reduction technique.

A dimension is one feature, which means one column, in our data.

Let's make this concrete.

If we only record the height of each person, we have one column. So we have one dimension. We can place each person on a single line.

If we record height and weight, we have two columns. So we have two dimensions. We can place each person on a flat graph, like a sheet of paper, with height on one axis and weight on the other.

If we add age, we have three columns, which means three dimensions. We can imagine each person as a point floating inside a room.

We can picture this growth like below:

1 dimension (a line):          .----.----.----.----.

2 dimensions (a sheet):        ^ weight
                               |   .     .
                               |      .       .
                               |   .      .
                               +-----------------> height

3 dimensions (a room):         a point floating inside a box
                               with length, width, and height

Here, we can see that as we add more columns, we add more dimensions. With 100 columns, we have 100 dimensions. We cannot draw that, and it becomes very hard to work with.

So, dimensionality reduction means reducing the number of columns. PCA is one of the techniques that does this.

To learn Supervised and Unsupervised Learning and the rest of the Machine Learning Fundamentals from the ground up, check out our AI and Machine Learning Program at Outcome School.

The central idea behind PCA

Now, let's understand the central idea of PCA before any math.

PCA does not just delete columns. It creates new columns by mixing the old ones, and these new columns hold the same information with less repetition.

Let's say we have two columns: height in centimeters and height in inches. Both say the same thing. Instead of keeping both, PCA can create one new column that captures "how tall the person is", and throw away the leftover, which carries almost no extra information.

So, PCA finds new directions in the data along which the information is richest, and it lines up new columns along those directions.

The best way to picture this is with a scatter of points. Suppose we have two columns, and when we plot the points, they spread out mostly along one diagonal direction, like below:

   ^ column 2
   |                  .
   |               .  .
   |            .  .
   |         .  .
   |      .  .
   |   .  .
   +-----------------------> column 1

Here, we can see that the points are not spread evenly. They stretch a lot along the diagonal and only a little across it. That diagonal direction is where most of the information lives. PCA finds exactly this direction and makes it the new main column.

So, PCA looks for the directions where the data spreads out the most, and keeps those.

What is variance?

To understand "where the data spreads out the most", we need one word: variance.

Variance is a measure of how spread out the numbers are.

If the numbers are all close together, the variance is low. If the numbers are far apart, the variance is high.

Let's say we measure the age of people in two rooms.

  • Room A: ages are 30, 31, 29, 30, 30. These are very close together. Low variance.
  • Room B: ages are 5, 80, 25, 60, 15. These are far apart. High variance.

Now, why does PCA care about variance? Because spread means information.

Let's say a column has the same value for every person, for example everyone's "country" is the same. That column has zero variance and tells us nothing useful to separate one person from another. But a column where people differ a lot, like income, has high variance and helps us tell people apart.

So, PCA follows one rule: the directions with the most variance carry the most information, so we keep those. The directions with the least variance carry the least information, so we can drop them.

Planning your move into AI?

No matter which tech domain you work in today, with your effort, you can transition to these roles:

  • AI Engineer
  • Forward Deployed Engineer
  • AI Agent Engineer
  • Harness Engineer
  • Voice AI Engineer
  • AI Architect
  • LLM Engineer
  • LLM Inference Engineer
  • Gen AI Engineer
  • MLOps Engineer
  • ML Engineer
  • Deep Learning Engineer

Our AI and Machine Learning Program at Outcome School takes you there.

What is a Principal Component?

Now, we can define the most important term.

A Principal Component is a new column that PCA creates, pointing in a direction where the data spreads out the most.

PCA creates these new columns one by one, in order of importance.

  • The first Principal Component points in the direction of the highest variance. It captures the most information.
  • The second Principal Component points in the direction of the next highest variance, but with one rule: it must be at a right angle to the first one. Being at a right angle means it captures brand new information, not a repeat of the first.
  • The third Principal Component captures the next highest variance, again at a right angle to the earlier ones, and so on.

We can picture the first two Principal Components on our scatter of points like below:

   ^ column 2
   |       PC2         PC1
   |        \           /
   |         \       . / .
   |          \     . / .
   |           \   . / .
   |            \ . / .
   |             \ / .
   |              X
   |           . / \
   |          . / . \
   |         . / .   \
   |        . / .     \
   |       . / .       \
   |        /           \
   +------------------------------> column 1

Here, we can see that PC1 runs along the direction where the points spread the most. PC2 runs across it, at a right angle, capturing whatever spread is left over. Each new component picks up fresh information that the earlier ones missed.

So, the Principal Components are the new columns, ranked from most important to least important. If we keep only the first few, we keep most of the information while throwing away the rest.

How does PCA work, step by step

Now, let's understand how PCA actually does its work. It follows a clear set of steps.

Step 1: Standardize the data.

Different columns can be on very different scales. For example, age goes from 0 to 100, while income goes from 0 to 100000. If we do not fix this, the column with bigger numbers will unfairly dominate.

So, we standardize the data, which means we rescale every column so that they are all on a common scale. After this step, no single column wins just because its numbers happen to be larger.

We can picture standardizing like below:

   Before standardize                After standardize

   age    income                     age      income
   ---    ------                     -----    -----
    25    50000          -->         -1.07    -0.98
    40    90000                       1.34     1.37
    30    60000                      -0.27    -0.39

Here, we can see that before standardizing, income has huge numbers and age has small numbers, so income would unfairly dominate. After standardizing, both columns sit on the same scale, so PCA treats them equally.

Step 2: Measure how the columns move together.

Next, PCA studies how each pair of columns relates. It checks which columns move together and which move apart. This relationship is captured in a table called the covariance matrix.

For each pair of columns, the covariance matrix tells us "when this column goes up, does that column also go up?" It is how PCA discovers the overlap between columns.

Step 3: Find the special directions.

From the covariance matrix, PCA finds the special directions in the data. These directions have proper names from mathematics: the directions are called eigenvectors, and the amount of variance along each direction is called an eigenvalue.

We do not need the heavy math here. We just need to understand this:

  • An eigenvector is one of the new directions, which becomes a Principal Component.
  • An eigenvalue is a number that tells us how much variance, which means how much information, lies along that direction.

A large eigenvalue means that direction holds a lot of information. A small eigenvalue means that direction holds very little.

Step 4: Rank the directions and keep the best ones.

PCA sorts all the directions from the highest eigenvalue to the lowest. The direction with the highest eigenvalue becomes the first Principal Component, the next becomes the second, and so on.

Then we decide how many to keep. We keep the top few components that hold most of the information, and we drop the rest.

Step 5: Rewrite the data using only the kept components.

Finally, PCA rewrites our original data using only the components we kept. The result is a new, smaller table with fewer columns, but it still carries most of the original information.

We can picture the whole pipeline like below:

Original data (many columns)
        ↓
Standardize each column
        ↓
Covariance matrix (how columns move together)
        ↓
Find directions (eigenvectors and eigenvalues)
        ↓
Rank directions (highest eigenvalue first)
        ↓
Keep the top components
        ↓
Smaller data (few columns)

Here, we can see the full journey. We start with many columns, study how they relate, find the best directions, rank them, keep the top few, and end with a smaller table. This is how PCA works.

A quick note for you

No matter which tech domain you work in, get familiar with these topics:

  • LLM
  • RAG
  • MCP
  • Agent
  • Fine-tuning
  • Quantization

We put it all together in one video:

AI Engineering Explained: LLM, RAG, MCP, Agent, Fine-Tuning, and Quantization

No need to stop reading - bookmark it and watch later when you get time. Future you will thank you.

Now, let's get back to the topic.

A numeric walk-through

Now, let's make this concrete with a small example. Suppose we have data for 5 students, with two columns: hours studied and marks scored.

StudentHours studiedMarks scored
1130
2240
3350
4460
5570

Here, we can notice something straight away. Every time hours studied goes up by 1, marks scored goes up by 10. The two columns move together perfectly. They are strongly correlated.

So, both columns are really telling the same story: "this student is putting in effort". We do not need two columns to capture this. One column is enough.

This is exactly what PCA discovers. When PCA looks at this data, it finds that the points all lie along a single straight line, like below:

   ^ marks
   |                       .
   |                   .
   |               .
   |           .
   |       .
   +-----------------------> hours

Here, we can see that all 5 points sit on one diagonal line. The data spreads a lot along that line, and not at all across it.

So, PCA creates the first Principal Component pointing along that line. This single new column captures all the spread. The second component, which runs across the line, captures nothing, so we can drop it.

The result is that we replaced two columns with one column, and we lost no information. We went from 2 dimensions to 1 dimension. In real data, the points are never on a perfect line, so we lose a little information.

How many components should we keep?

Now, the next big question is: how many Principal Components must we keep?

If we keep too few, we lose important information. If we keep too many, we did not really simplify the data. So we need a balanced choice.

The common way to decide is to look at the explained variance.

Explained variance tells us what percentage of the total information each component captures.

Let's say we run PCA and get these numbers:

Component 1:  captures 72% of the information
Component 2:  captures 18% of the information
Component 3:  captures  6% of the information
Component 4:  captures  3% of the information
Component 5:  captures  1% of the information

Here, we can see that the first two components together capture 72 + 18 = 90% of the information. The remaining three components together hold only 10%.

So, if keeping 90% of the information is good enough for our use case, we keep just the first two components and drop the other three. We reduced five columns down to two, and we kept most of the story.

A popular way to view this is the scree plot, which is a chart of how much each component captures, from highest to lowest:

  variance
  captured
    ^
    |  #
    |  #
    |  #
    |  #
    |  #
    |  #  #
    |  #  #  #  #  #
    +--------------------> component number
       1  2  3  4  5

Here, we can see that the bars drop off quickly. The first few bars are tall, and then the height falls sharply. We usually keep the components before the drop-off flattens out, depending on our use case.

Stay updated: Subscribe to our newsletter to get our latest AI and Machine Learning blogs straight to your inbox.

Seeing it in code

Now, let's run PCA in Python using the scikit-learn library. We will use the famous Iris dataset, which has 150 flowers and 4 measurements for each flower. Let's see the code as below:

from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

# our original data table: 150 flowers, 4 columns each
X = load_iris().data

# Step 1: standardize the data so every column is on a common scale
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# Step 2: create PCA and ask it to keep 2 components
pca = PCA(n_components=2)
X_reduced = pca.fit_transform(X_scaled)

# Step 3: check how much information each component captured
print(pca.explained_variance_ratio_)

This will print the following:

[0.72962445 0.22850762]

Here, we have done the following:

  • StandardScaler() rescales every column to a common scale, which is the standardize step we discussed earlier.
  • PCA(n_components=2) tells PCA that we want to keep only the top 2 Principal Components.
  • pca.fit_transform(X_scaled) does the real work. It finds the best directions and rewrites our data using only the top 2 components. The result X_reduced is our smaller table.
  • pca.explained_variance_ratio_ prints the fraction of information captured by each component, so we can check whether 2 components were enough. Here, the first component captures about 73% and the second about 23%, so 2 components keep about 96% of the information.

Advantages of PCA

Now, let's understand why PCA is so useful.

  • Fewer columns: PCA reduces many columns into a few, which makes the data smaller and easier to handle.
  • Removes repetition: PCA combines correlated columns that carry the same information, so the repetition is removed.
  • Faster models: With fewer columns, Machine Learning models train faster and use less memory.
  • Easier visualization: By reducing the data to 2 or 3 components, we can draw it on a graph and see patterns.
  • Less noise: The dropped components often hold mostly noise, so removing them can make the data cleaner.

If we want to go deep into Data Analysis and Visualization along with the Machine Learning Fundamentals, we have a complete program on this - check out our AI and Machine Learning Program at Outcome School.

Limitations of PCA

PCA is useful, but we must also know where it falls short.

  • Harder to interpret: The new components are mixtures of the old columns, so they do not have a simple, real-world name like "age" or "income". This makes them harder to explain.
  • Only finds straight-line patterns: PCA looks for directions of spread using straight lines. If the real pattern in the data is curved, PCA can miss it.
  • Sensitive to scale: If we forget to standardize the data first, the columns with bigger numbers will unfairly dominate. So the standardize step is very important.
  • Some information is always lost: When we drop components, we throw away a little information. PCA keeps as much as possible, but it is never a perfect copy.

Where PCA is used

Now, let's see where PCA is used in the real world.

  • Image compression: An image has thousands of pixels, which means thousands of columns. PCA can shrink it into far fewer components while keeping the picture recognizable.
  • Face recognition: PCA is used to turn complex face data into a small set of key features, an idea historically known as "eigenfaces".
  • Finance: PCA helps find the few main factors that drive the movement of many different stocks at once.
  • Genetics: PCA reduces huge tables of gene data into a few components, helping researchers spot patterns across populations.
  • Speeding up Machine Learning: Before training a model, PCA is used to cut down the number of columns, so the model trains faster.
  • Visualization: PCA reduces high-dimensional data to 2 or 3 components so we can plot it and understand it visually.

Now we must have understood what PCA is, how it works, and where it is used.

Frequently Asked Questions

Does PCA just delete columns from the data?

No. PCA does not just delete columns. It creates new columns by mixing the old ones, and these new columns hold the same information with less repetition. Then we keep the top few new columns, which are the Principal Components, and drop the rest.

Why must we standardize the data before PCA?

We must standardize the data because different columns can be on very different scales, like age from 0 to 100 and income from 0 to 100000. If we skip this step, the column with bigger numbers will unfairly dominate. After standardizing, every column sits on a common scale, so PCA treats them equally.

Why is each Principal Component at a right angle to the earlier ones?

Each new Principal Component is at a right angle to the earlier ones so that it captures brand new information, not a repeat of what the earlier components already captured. This is how every component picks up fresh spread in the data that the earlier ones missed.

Can PCA find curved patterns in the data?

No. PCA looks for directions of spread using straight lines, so it only finds straight-line patterns. If the real pattern in the data is curved, PCA can miss it. This is one of the main limitations of PCA, along with components that are harder to interpret.

That's it for now.

Thanks

Amit Shekhar
Founder @ Outcome School

You can connect with me on:

Follow Outcome School on:

Read all of our high-quality blogs here.