Machine Learning from Scratch – Day 15: Understanding Principal Component Analysis (PCA)
Understanding Principal Component Analysis (PCA)
Series: Machine Learning From Scratch (18 articles)
- …
- 15Machine Learning from Scratch – Day 15: Understanding Principal Component Analysis (PCA) This article
Machine Learning from Scratch – Day 15: Understanding Principal Component Analysis (PCA)
Introduction
In our previous article, we explored Hierarchical Clustering, an unsupervised learning algorithm that groups similar data points into a hierarchy of clusters.
Today, we are going to learn about another important machine learning technique: Principal Component Analysis (PCA).
Imagine working with a dataset containing 100 features.
Some features might contain similar information, some might be highly correlated, and others might contribute very little to the patterns we want to study.
Processing all these features can increase computational complexity and make visualization difficult.
Is there a way to reduce the number of features while preserving as much useful information as possible?
Yes! This is where PCA becomes useful.
PCA is a dimensionality reduction technique that transforms a dataset into a smaller set of new features called principal components.
Let's understand how it works.
1. What is Principal Component Analysis?
Principal Component Analysis (PCA) is an unsupervised dimensionality reduction technique used to reduce the number of features in a dataset.
It transforms the original features into a new set of variables called principal components.
These components:
- Are linear combinations of the original features.
- Are uncorrelated with one another in the transformed training data.
- Are ordered by the amount of variance they capture.
The first principal component captures the maximum possible variance.
The second captures the maximum remaining variance while being orthogonal to the first, and the process continues.
In simple terms, PCA helps represent high-dimensional data using fewer dimensions while retaining as much variation in the data as possible.
2. Why Do We Need Dimensionality Reduction?
Before understanding PCA, let's look at why dimensionality reduction matters.
Consider a dataset containing information about customers:
- Age
- Income
- Spending score
- Purchase frequency
- Number of transactions
- Average order value
- Customer lifetime value
As the number of features increases, analyzing and visualizing the dataset becomes more challenging.
Some features may also contain overlapping information.
Dimensionality reduction helps address these challenges.
Benefits of dimensionality reduction
1. Reduced Computational Complexity
Fewer features can reduce the time and resources required by some machine learning algorithms.
2. Easier Visualization
High-dimensional data can be transformed into two or three dimensions for visualization.
3. Reduced Redundancy
PCA can combine correlated information into a smaller set of components.
4. Noise Reduction
Removing components with very low variance can sometimes reduce noise, although low variance does not automatically mean a feature is unimportant.
5. Simplified Data Representation
A smaller number of components can make complex datasets easier to explore.
3. Understanding Principal Components
Principal components are new directions in the feature space along which the data has the greatest variance.
Let's understand this using a simple example.
Imagine a dataset containing two features:
- Height
- Weight
These two features may be correlated because people who are taller often tend to weigh more.
PCA can combine information from both features into a new direction called the first principal component.
The second principal component captures the remaining variance in a direction perpendicular to the first.
For a dataset with two features:
- PC1 captures the maximum variance.
- PC2 captures the maximum remaining variance, subject to being orthogonal to PC1.
If PC1 captures most of the variation, we may be able to represent the dataset using only PC1 with some loss of information.
4. How Does PCA Work?
PCA follows a mathematical process to identify the most important directions in a dataset.
Let's understand the major steps.
Step 1: Standardize the Data
PCA is sensitive to feature scales.
For example, consider a dataset containing:
- Age: 18–60
- Annual income: ₹2,00,000–₹20,00,000
Income has a much larger numerical scale than age.
Without scaling, income may dominate the variance calculation.
Therefore, standardization is commonly performed before PCA.
A popular technique is StandardScaler.
The standardization formula is:
Z = (X - μ) / σ
Where:
- X is the original feature value.
- μ is the feature mean.
- σ is the feature standard deviation.
Step 2: Calculate the Covariance Matrix
The covariance matrix helps us understand how different features vary together.
It shows:
- Positive covariance: Two features tend to increase together.
- Negative covariance: One feature tends to increase when the other decreases.
- Near-zero covariance: Little linear co-variation is observed.
Step 3: Calculate Eigenvalues and Eigenvectors
This is the mathematical foundation of PCA.
Eigenvectors represent the directions of the principal components.
Eigenvalues represent the amount of variance captured along those directions.
The components are ordered from the highest eigenvalue to the lowest.
Step 4: Select Principal Components
Choose the number of principal components based on how much variance we want to retain.
For example:
- PC1: 60% variance
- PC2: 25% variance
- PC3: 10% variance
- PC4: 5% variance
If we retain the first two components, we preserve:
60% + 25% = 85%
of the total variance.
Step 5: Transform the Data
Finally, project the original standardized data onto the selected principal components.
The result is a dataset with fewer dimensions.
5. Understanding Explained Variance
One of the most important concepts in PCA is Explained Variance.
It tells us how much of the total variance in the original dataset is captured by each principal component.
The explained variance ratio is calculated as:
Explained Variance Ratio = Eigenvalue of a Component / Sum of All Eigenvalues
For example:
Component | Explained variance |
|---|---|
PC1 | 60% |
PC2 | 25% |
PC3 | 10% |
PC4 | 5% |
The cumulative explained variance is:
- First component: 60%
- First two components: 85%
- First three components: 95%
- All four components: 100%
This helps us decide how many components to retain.
A common approach is to retain enough components to explain approximately 90–95% of the variance.
However, this is only a guideline. The appropriate threshold depends on the problem and the performance requirements of the downstream model.
6. PCA vs Feature Selection
An important distinction is that PCA is not the same as feature selection.
Feature Selection | PCA |
|---|---|
Selects existing features | Creates new features |
Keeps original feature meanings | Components combine original features |
Removes selected features | Projects data into a new feature space |
Can preserve interpretability | Components may be difficult to interpret |
For example, feature selection might retain age and income while removing other columns.
PCA might create a component that combines age, income, and spending score.
PCA is therefore a feature extraction technique rather than a feature selection technique.
7. Implementing PCA Using Python
Now let's implement PCA using Scikit-learn.
We will use the Iris dataset, which contains four numerical features.
Our objective is to reduce these four dimensions to two principal components.
Step 1: Import libraries
import matplotlib.pyplot as pltfrom sklearn.datasets import load_irisfrom sklearn.preprocessing import StandardScalerfrom sklearn.decomposition import PCAStep 2: Load the dataset
iris = load_iris()
X = iris.datay = iris.targetThe dataset contains:
- Sepal length
- Sepal width
- Petal length
- Petal width
It also contains three flower species.
Step 3: Standardize the data
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)Standardization ensures that features with different scales do not dominate PCA.
Step 4: Apply PCA
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)Here:
-
n_components=2means we want to retain two principal components.
-
fit_transform()learns the components and transforms the dataset.
Our original dataset had four features.
After PCA, it has only two components.
Step 5: Check explained variance
print("Explained Variance Ratio:")print(pca.explained_variance_ratio_)
print("Total Explained Variance:")print(pca.explained_variance_ratio_.sum())This tells us how much of the original variance is represented by the two selected components.
Step 6: Visualize the transformed data
plt.figure(figsize=(8, 6))
plt.scatter( X_pca[:, 0], X_pca[:, 1], c=y)
plt.xlabel("Principal Component 1")plt.ylabel("Principal Component 2")
plt.title("PCA - Iris Dataset")
plt.show()The scatter plot displays the Iris samples using two principal components.
Different colors represent different flower species.
Notice that we used the labels only for coloring the visualization. PCA itself did not use them to learn the components.
8. Advantages and Disadvantages of PCA
Advantages | Disadvantages |
|---|---|
Reduces the number of features | Components can be difficult to interpret |
Can reduce computational requirements | Some information is lost |
Helps visualize high-dimensional data | Sensitive to feature scaling |
Removes linear correlations between components | Captures linear relationships |
Can help reduce noise | Important low-variance information may be discarded |
9. Real-World Applications of PCA
PCA is used in many machine learning and data science applications.
1. Image Compression
PCA can represent image data using fewer dimensions, potentially reducing storage requirements.
2. Face Recognition
PCA has historically been used in face recognition techniques such as Eigenfaces.
3. Data Visualization
High-dimensional datasets can be projected into two or three dimensions for visualization.
4. Genomics
PCA helps analyze high-dimensional genetic datasets and identify major patterns of variation.
5. Financial Data Analysis
PCA can summarize correlated financial variables into a smaller set of components.
6. Machine Learning Preprocessing
PCA can reduce feature dimensionality before applying other machine learning algorithms.
10. Important Things to Remember
Before using PCA in a real-world project, keep these points in mind:
- PCA is an unsupervised technique.
- Feature scaling is generally important.
- Principal components are linear combinations of original features.
- Components are ordered by explained variance.
- PCA does not guarantee better model accuracy.
- PCA can reduce interpretability because original feature meanings are transformed.
- When evaluating a predictive model, fit PCA only on training data and use the learned transformation on validation and test data. This prevents data leakage.
11. Key Takeaways
Let's summarize what we learned today:
- PCA stands for Principal Component Analysis.
- It is used for dimensionality reduction.
- It transforms original features into principal components.
- Eigenvectors determine component directions.
- Eigenvalues indicate the variance captured by components.
- Explained variance helps determine how many components to retain.
- PCA is useful for visualization, compression, and preprocessing.
PCA teaches us that sometimes we don't need every original feature to understand the major patterns in a dataset.
By transforming data into a smaller number of meaningful directions, we can simplify complex machine learning problems.
Coming Next – Day 16: Understanding Gradient Boosting
In our next article, we will explore Gradient Boosting, an ensemble learning technique that builds models sequentially, with each new model attempting to correct errors made by the previous ensemble.
We will understand how boosting works, the role of residuals, and how to implement Gradient Boosting using Python.
Series: Machine Learning From Scratch (18 articles)
- …
- 15Machine Learning from Scratch – Day 15: Understanding Principal Component Analysis (PCA) This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article