Hello! Welcome to the first lesson of our module on Unsupervised Learning.
In our previous module, we focused on supervised learning, concluding with how to interpret feature importance in tree-based models. We saw that understanding which features drive a model's predictions is crucial. Sometimes, this analysis reveals that many features are redundant or that the sheer number of features makes the model complex and hard to visualize. This provides a perfect transition to our topic today.
This lesson addresses the learning outcome: Apply Principal Component Analysis (PCA) to reduce data dimensionality. We will explore one of the most fundamental techniques in unsupervised learning. By the end of this lesson, you'll understand the motivation behind dimensionality reduction and be able to apply PCA to transform a high-dimensional dataset into a lower-dimensional one, paving the way for more efficient modeling and visualization.
We'll cover:
- The "Why": Understanding the problems caused by too many features, often called the "Curse of Dimensionality."
- The Core Idea: Grasping the intuition behind PCA – finding new axes that capture the most information.
- The "How": Walking through the step-by-step process of PCA, from standardizing data to projecting it onto new components.
- The Application: Implementing PCA using Python's
scikit-learnlibrary.
1. Why Do We Need Fewer Dimensions? The Curse of Dimensionality
In machine learning, it's natural to think that "more data is better," and this often extends to "more features are better." However, having a very large number of features (i.e., high-dimensional data) can introduce significant problems.
Principal Component Analysis — Applied Machine ...
To understand these problems, let's read about the 'Curse of Dimensionality'. The article 'Principal Component Analysis' by Michael Pyrcz offers an excellent, detailed explanation.
Please read the section 'Motivation for Principal Component Analysis' and the sub-section 'Curse of Dimensionality'. Focus on grasping why having many features makes it harder to visualize data, requires more samples, and can lead to model instability.
As the article explains, a high number of dimensions leads to several issues:
- Visualization is Impossible: We can intuitively understand data in 2D or 3D, but we cannot visualize it in 10, 50, or 100 dimensions.
- Data Becomes "Sparse": As you add more dimensions, the amount of data needed to maintain the same density of coverage grows exponentially. Your data points become very far apart from each other, making it difficult for algorithms to find local patterns.
- Increased Risk of Overfitting: With more features, a model has more opportunities to learn noise and spurious correlations from the training data, hurting its ability to generalize to new data.
- Multicollinearity: It becomes more likely that some features are correlated with others, which can make certain models (like linear regression) unstable.
Dimensionality reduction techniques, like PCA, aim to solve these problems by creating a compact, lower-dimensional representation of the data while preserving as much of the original information as possible.
2. The Core Idea of PCA: Finding New, More Informative Axes
Imagine you have a 2D dataset where the two features are highly correlated, like a city's population and its average cost of living. The data points would form an elongated cloud on a scatter plot.

Instead of describing each point with its original "population" and "cost" values, could we find a new, single axis that runs along the direction of this elongated cloud? This new axis would capture most of the variation in the data. This is the central idea of PCA.
PCA finds a new set of axes, called Principal Components (PCs), that are ordered by how much of the data's variance they capture.
- Principal Component 1 (PC1): The axis that captures the most variance in the dataset. It's the "line of best fit" that passes through the centered data.
- Principal Component 2 (PC2): The axis that is perpendicular (orthogonal) to PC1 and captures the most remaining variance.
- And so on, for as many dimensions as you have.
The following video provides an excellent visual and conceptual explanation of this idea.
StatQuest: Principal Component Analysis (PCA), Step-by-Step
The video 'StatQuest: Principal Component Analysis (PCA), Step-by-Step' beautifully illustrates how PCA finds the first principal component by essentially rotating a line until it 'fits' the data best.
Please watch these two segments: 3:32 - 8:54: Focus on the intuition of centering the data and then rotating a line to find the direction that maximizes the sum of squared distances from the origin to the projected points. This is PC1. 12:46 - 15:06: Watch how PC2 is simply the line perpendicular to PC1 and how the data is then projected onto these new axes to create the final PCA plot.
The key insight is that these new principal components are linear combinations of the original features. For example, in our city data, PC1 might be something like 0.7 * population + 0.7 * cost_of_living, representing an overall "urbanization" score.
3. The PCA Algorithm: Step-by-Step
Now that we have the intuition, let's walk through the steps required to perform PCA. Your background in engineering provides a solid foundation for understanding this process, even without deep expertise in linear algebra.
Step 1: Standardize the Data
PCA is sensitive to the scale of the features. A feature with a large variance (e.g., house prices in dollars) will dominate the PCA process over a feature with a small variance (e.g., number of bedrooms). To prevent this, we must first standardize each feature to have a mean of 0 and a standard deviation of 1.
Principal Component Analysis — Applied Machine ...
The article 'Principal Component Analysis — Applied Machine ...' explains this crucial first step and shows how it's done in Python.
Read the section 'Standardize the Features'. Note the reasoning provided for why standardization is necessary and look at the Python code using StandardScaler from scikit-learn.
Step 2: Compute the Covariance Matrix
Once the data is standardized, we compute the covariance matrix. In Module 2, we learned that covariance measures how two variables change together. The covariance matrix summarizes the pairwise covariance between all features. This matrix effectively describes the shape and orientation of our data cloud.
Step 3: Calculate Eigenvectors and Eigenvalues
This is the core mathematical step of PCA. Don't worry about the complex calculations; it's the what and why that matter here. For the covariance matrix:
- Eigenvectors represent the directions of the new axes (the principal components).
- Eigenvalues represent the magnitude or amount of variance captured by each eigenvector.
The eigenvector with the highest eigenvalue is our PC1. The eigenvector with the second-highest eigenvalue is PC2, and so on.
The following video provides a helpful conceptual bridge from the covariance matrix to eigenvectors and eigenvalues.
Principal Component Analysis (PCA) | Dimensionality Reduction Techniques (2/5)
Let's watch a segment from the 'Principal Component Analysis (PCA)' video by DeepFindr that demystifies these linear algebra concepts.
Please watch from 10:43 to 16:59. Focus on: How the covariance matrix represents the data's variability (10:43 - 12:50). The intuitive explanation of eigenvectors as vectors that don't change direction under a transformation, and eigenvalues as the amount of 'stretch' (12:50 - 15:30). The key connection: Eigenvectors of the covariance matrix are the Principal Components, and the eigenvalues tell us the explained variance (15:30 - 16:59).
In practice, most libraries use a more numerically stable method called Singular Value Decomposition (SVD) to find the principal components, but the final result is the same.
Test your understanding!
You have two features, height (in meters, e.g., 1.8) and weight (in kilograms, e.g., 75.0). Why would it be a problem to run PCA directly on this data without standardization, and which feature would likely dominate PC1?
Show answer
The weight feature has a much larger variance than the height feature simply due to the units of measurement (75.0 vs 1.8). Without standardization, PCA would incorrectly identify weight as the more "important" direction of variation. PC1 would therefore be almost perfectly aligned with the weight axis, and we would lose the information from the relationship between height and weight.
Step 4: Transform the Data
After identifying the principal components, the final step is to project our original, standardized data onto the new axes. We do this by taking the dot product of our data with the matrix of chosen eigenvectors. If we want to reduce our data from 10 dimensions to 2, we would select the first two eigenvectors (PC1 and PC2) and project the data onto them.
The result is a new dataset with the desired number of dimensions, where each new feature is one of the principal components.
4. Applying PCA with scikit-learn
Now for the practical part. scikit-learn makes applying PCA incredibly straightforward. The process encapsulates all the steps we just discussed.
Let's see how to apply PCA to a dataset and reduce its dimensionality.
Principal Component Analysis — Applied Machine ...
Let's return to the 'Principal Component Analysis' tutorial by Michael Pyrcz to see a complete, practical demonstration of applying PCA, interpreting the results, and visualizing the effect of dimensionality reduction.
Please read through the following sections and study the code: 'Principal Component Analysis (PCA)': Shows how to instantiate and fit the PCA object. 'Component Loadings' and 'Proportion of Variance Explained': Explains how to access the pca.components_ and pca.explained_variance_ratio_ attributes, which are the eigenvectors and eigenvalues, respectively. 'Principal Component Scores...': Demonstrates how to use pca.transform() to project the data and pca.inverse_transform() to go back to the original space. 'Demonstration of Dimensional Reduction': This is the most important part. Follow the 6-step visual demonstration of transforming 2D data down to 1D and back again. It perfectly illustrates what 'applying PCA' means.
The key steps in the code are:
- Standardize the data:
x_scaled = StandardScaler().fit_transform(x) - Initialize and fit PCA:
pca = PCA(n_components=2)andpca.fit(x_scaled) - Transform the data:
x_pca = pca.transform(x_scaled)
The resulting x_pca is your new, lower-dimensional dataset.
Conclusion
In this lesson, we introduced the "Curse of Dimensionality" and motivated the need for dimensionality reduction. We then dove deep into the concepts and application of Principal Component Analysis, one of the most widely used techniques for this purpose.
Key Takeaways:
- PCA is an unsupervised learning technique used to reduce the dimensionality of a dataset.
- It works by finding a new set of orthogonal axes, called principal components, that are ordered by the amount of variance they explain.
- The PCA algorithm involves standardizing the data, computing the covariance matrix, and finding its eigenvectors (the PCs) and eigenvalues (the explained variance).
scikit-learnprovides a simplePCAobject that handles these steps, allowing you to easilyfita model andtransformyour data into a lower-dimensional space.
Preview of the Next Lesson:
We've successfully applied PCA to reduce our data's dimensions. But a crucial question remains: how do we decide how many principal components to keep? Is it 2, 5, or 10? In the next lesson, we will learn how to interpret the results of PCA, using tools like the explained variance ratio and scree plots to make an informed decision and find the right balance between dimensionality reduction and information preservation.