Real datasets can have hundreds or thousands of features. Many of them overlap and repeat the same information. Principal Component Analysis (PCA) squeezes lots of features into a few new ones while keeping most of the information, making data faster to model and possible to see.
- Level: Intermediate
- Time: about 35 minutes
- Needs: Modules 1, 2, 5 and 9
By the end of this module you will be able to
- Explain why having too many features causes problems
- Describe what a principal component is, in plain English
- Read an explained variance chart and choose how many components to keep
- Use PCA to visualise data with many features on a 2D chart
- Explain what information is lost when data is compressed
- Use PCA inside a pipeline in scikit-learn
- Know PCA's limits, and when to use alternatives
12.1Why reduce the number of features?
Each feature in a dataset is called a dimension. A table with 3 columns is 3-dimensional; the handwritten digits from Module 9 are 64-dimensional (one per pixel). Some real datasets have many thousands.
Lots of dimensions cause four problems:
| Problem | What happens |
|---|---|
| Slow training | More features means more calculations, more memory and longer waits |
| The curse of dimensionality | As you learned in Module 6, with many features all points start to look equally far apart, which hurts distance-based models |
| Overfitting | More features gives a model more ways to memorise noise (Module 5) |
| Impossible to see | We can draw 2 or 3 dimensions on a chart, but not 64 |
The good news is that many features are redundant. A house's size in square metres and its number of rooms rise together. A person's height and arm span are almost the same measurement. In an image, neighbouring pixels are usually similar. If features repeat each other, we can combine them without losing much.
Dimensionality reduction in one sentence
Dimensionality reduction turns many features into fewer new ones, keeping as much of the useful information as possible.
12.2The big idea behind PCA
Taking the best photograph
Imagine photographing a long bus. A photo taken from the front shows a small rectangle; you can't tell it's a bus. A photo from the side shows its full length, windows and wheels. Both are 2D pictures of a 3D object, but the side view keeps far more information, because it looks along the direction where the bus is most spread out. PCA finds the "best angle" to view your data from.
PCA looks for the direction in which the data is most spread out. That direction becomes the first new feature, called the first principal component (PC1). Then it finds the next most spread-out direction, at right angles to the first (PC2), and so on.
Why does "most spread out" matter? Because variation is information. If every house in a dataset had exactly 3 bedrooms, the "bedrooms" column would tell a model nothing. The directions where the data varies most are the ones that separate one example from another.
Each principal component is a mix of the original features. For example, PC1 above might be roughly "0.8 × height + 0.6 × arm span": a combined "body size" feature.
12.3Finding the first principal component
Let's find PC1 by hand. Rotate the line below. Each point is "projected" (squashed) onto the line, like a shadow. PCA wants the line where those shadows are as spread out as possible, so they keep as much of the original variation as they can.
Try it: rotate the line to capture the most variation
When the line runs along the long diagonal of the cloud, the shadows spread out the most, keeping about 93% of the variation. That's PC1. Rotate it 90 degrees and you get PC2, which keeps the remaining 7%.
12.4How many components should you keep?
PCA creates as many components as there were original features, but ordered from most to least useful. The first few usually carry most of the information. The share each one keeps is called its explained variance.
| Your goal | How to choose |
|---|---|
| Speed up a model, keep accuracy | Keep enough components for about 90 to 95% of the variation |
| Visualise the data | Keep 2 (or 3) components, so you can draw them |
| Find the best number for a model | Treat the number of components as a hyperparameter and tune it with cross-validation |
In scikit-learn, you can even ask for a share directly: PCA(n_components=0.95) keeps as many components as needed for 95% of the variation.
12.5Using PCA, step by step
| Step | What to do | Why |
|---|---|---|
| 1. Scale | Put all features on a similar scale (Module 2) | PCA looks for spread. Without scaling, a feature measured in thousands would look "more spread out" just because of its units |
| 2. Fit | pca.fit(X_train) | PCA learns the directions from the training data only, to avoid leakage |
| 3. Choose | Pick how many components to keep | Using the explained variance chart or cross-validation |
| 4. Transform | pca.transform(X) | Turns each row's original features into its new component values |
As always, the easiest and safest way is to put the scaler, PCA and the model together in a Pipeline, which handles steps 1, 2 and 4 automatically, even during cross-validation.
PCA is unsupervised
PCA only looks at the features, never the labels. It keeps the directions with the most variation, which are usually useful, but not always the ones that best separate your classes. Always check your model's accuracy after applying PCA.
12.6Seeing data with many features
One of the most popular uses of PCA is to draw high-dimensional data. We can't picture 64 dimensions, but we can squeeze the digits down to 2 components and plot them.
This kind of chart is a great first step with any new dataset. It shows whether the classes naturally separate, which groups are likely to get confused (here, digits such as 1, 5, 8 and 9, which overlap in the middle), and whether there are any strange outliers.
Only 28% of the information, but still useful
These 2 components keep only 28% of the variation, so the picture is a rough sketch, not the full story. For visualisation only, tools called t-SNE and UMAP often separate groups more clearly, because they can bend and curve. PCA is faster, simpler and, unlike them, can also be used to prepare data for models.
12.7PCA as compression: what gets lost?
PCA can also go backwards: take the few components and rebuild an approximate version of the original data. The rebuilt version shows exactly what was kept, and what was thrown away.
What's thrown away first is the fine detail and noise: tiny variations that are different in every image. What's kept is the main shape. That's why PCA can sometimes even improve a model: it removes noise that the model might otherwise overfit.
12.8PCA in Python
Let's return to the digits and the SVM from Module 9. How much information do the components keep, and what happens to accuracy when we shrink 64 features down to 30, 10 or even 2?
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import MinMaxScaler
from sklearn.svm import SVC
# 1. The handwritten digits from Module 9: 64 pixel features each
X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y)
# 2. How much information does each component keep?
pca = PCA().fit(MinMaxScaler().fit_transform(X_train))
cumulative = np.cumsum(pca.explained_variance_ratio_)
for n in [1, 2, 5, 10, 20, 30]:
words = "components keep" if n > 1 else "component keeps"
print(f"{n:2} {words} {cumulative[n-1]:.0%} of the variation")
print("Components needed for 95%:", np.argmax(cumulative >= 0.95) + 1)
# 3. Does shrinking 64 features hurt accuracy?
print()
for n in [None, 30, 10, 2]:
steps = [("scale", MinMaxScaler())]
if n:
steps.append(("pca", PCA(n_components=n, random_state=42)))
steps.append(("svm", SVC(C=10)))
model = Pipeline(steps)
model.fit(X_train, y_train)
label = f"{n} components" if n else "All 64 features"
print(f"{label:16} accuracy={model.score(X_test, y_test):.3f}")
1 component keeps 15% of the variation 2 components keep 28% of the variation 5 components keep 54% of the variation 10 components keep 73% of the variation 20 components keep 89% of the variation 30 components keep 95% of the variation Components needed for 95%: 30 All 64 features accuracy=0.991 30 components accuracy=0.991 10 components accuracy=0.982 2 components accuracy=0.653
What the output tells us
- The information is concentrated. The first component alone keeps 15%. Ten keep 73%, and 30 keep 95%, so more than half of the 64 original features are mostly redundant.
- 30 components give exactly the same accuracy (99.1%) as all 64 features, with less than half the data. On big datasets, that means much faster training.
- 10 components lose very little (98.2%), with just a sixth of the features.
- 2 components drop to 65.3%. Good enough for a chart (Figure 3), but far too little information for a reliable model. It's still much better than guessing, which would be 10%.
Reading the components
After fitting, pca.components_ shows how much each original feature contributes to each component, and pca.explained_variance_ratio_ shows how much variation each one keeps. Looking at the biggest contributions can help you give a component a meaningful name, such as "overall size" or "price level".
12.9Strengths, weaknesses and real-world uses
| Strengths | Weaknesses |
|---|---|
| Speeds up training on data with many features | Components are hard to explain: "PC3" is a mix of many features |
| Removes redundancy and noise, which can reduce overfitting | Only finds straight-line directions; it can't follow curved patterns |
| Makes high-dimensional data visible in 2D or 3D | Always loses some information |
| Fast, simple and well understood | Must scale features first |
| No labels needed (unsupervised) | Ignores labels, so it may drop directions that matter for your task |
| Area | How PCA is used |
|---|---|
| Finance | Summarising how dozens of interest rates or share prices move together into a few main "factors" |
| Genetics and healthcare | Reducing thousands of gene measurements to a handful of components for study and visualisation |
| Images | Compressing images and finding the main features of faces |
| Surveys and social research | Combining many related questions into a few underlying themes |
| Machine learning pipelines | Shrinking features before KNN, SVMs or clustering to make them faster and more accurate |
| Data exploration | A quick 2D picture of any new dataset |
SummaryKey takeaways
- Too many features makes models slower, more likely to overfit and impossible to see.
- Many features are redundant, so they can be combined with little loss.
- PCA finds new directions, principal components, ordered by how much of the data's variation they keep.
- Each component is a mix of the original features, and each is at right angles to the ones before.
- Use the explained variance chart to choose how many to keep: about 95% for modelling, 2 or 3 for charts.
- Always scale first and fit PCA on the training data only, ideally in a
Pipeline. - PCA throws away fine detail and noise first, keeping the main shape.
- Components can be hard to explain, and PCA only finds straight-line patterns.
Check your understanding
Your machine learning roadmap
- 01Introduction to Machine LearningWhat ML is and how it works
- 02Preparing Data for Machine LearningFeatures, encoding, scaling, train/test split
- 03Linear RegressionPredicting numbers
- 04Logistic RegressionPredicting yes or no
- 05Evaluating ModelsAccuracy, precision, recall, overfitting, cross-validation
- 06K-Nearest NeighboursLearning from similar examples
- 07Decision TreesFlowcharts that learn
- 08Random Forest and Gradient BoostingMany models working together
- 09Support Vector MachinesFinding the best boundary
- 10Naive BayesProbability-based classification
- 11Clustering with K-MeansFinding groups without labels
- 12Dimensionality Reduction with PCAYou are here
- 13Capstone ProjectBuild and present a full ML project
Next module
Capstone Project