CadetX
CX Learn | Complete Machine Learning Guide
Scikit-Learn · Python
CadetX logo CadetX CX Learn
ML-101 · Module 12 Intermediate about 35 minutes 10 Lessons Prereq: Modules 1, 2, 5 and 9

Principal Component Analysis (PCA)

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:

ProblemWhat happens
Slow trainingMore features means more calculations, more memory and longer waits
The curse of dimensionalityAs you learned in Module 6, with many features all points start to look equally far apart, which hurts distance-based models
OverfittingMore features gives a model more ways to memorise noise (Module 5)
Impossible to seeWe 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.

Points spread out in a diagonal cloud. The first principal component points along the long diagonal, where the data varies most. The second principal component is at right angles to it, where there is little variation.PC1PC2PC1: 93% of the variationThe direction where the datais most spread out.PC2: 7% of the variationAt right angles to PC1.Very little spread here.Keep only PC1: 2 featuresbecome 1, and most of theinformation is kept.
Figure 1. Two features that rise together, like height and arm span. PC1 runs along the diagonal and captures 93% of the variation. PC2, at right angles, captures only 7%. We could keep just PC1 and lose very little.

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

Variation kept by this one line

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.

Cumulative variation explained by principal components of the digits data. It rises quickly: 10 components keep 73 percent, and 30 components keep 95 percent, out of 64 features.0%25%50%75%100%110203040506430 components = 95%Bars: each component on its ownLine: running totalNumber of components (out of 64)
Figure 2. Explained variance for the 64-pixel digits. Each blue bar is one component on its own; the amber line is the running total. Just 10 components keep 73% of the variation, and 30 keep 95%. The last 20 or so add almost nothing.
Your goalHow to choose
Speed up a model, keep accuracyKeep enough components for about 90 to 95% of the variation
Visualise the dataKeep 2 (or 3) components, so you can draw them
Find the best number for a modelTreat 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

StepWhat to doWhy
1. ScalePut 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. Fitpca.fit(X_train)PCA learns the directions from the training data only, to avoid leakage
3. ChoosePick how many components to keepUsing the explained variance chart or cross-validation
4. Transformpca.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.

700 handwritten digits squeezed from 64 features to 2 principal components. Digits of the same kind form their own coloured clouds, such as zeros on one side and fours on another, though some digits overlap.34991933168809259654999824197314825084772871704361169514363691832308443018855016171383046985919419440582851956541371697995915810654825412513688522915065848950305401040467774997102468476273736489047278283830941525696944406675527821304250337393490035013037300183360010682554081598041380134438967562018522226572539172122467284259347102734901912519254984320302146164297026292938912146598084766236634907466597128746198746711308646510119589646507641463068077914155608348238255518086306832091584365045705225834068367907072283399791386511387981795273648405690305632698959806454932014066524387416387965724151162994669989751130205480961045396820780387825105351056046513666884349458574430013850113036722800956360digit1digit2digit3digit4digit5digit6digit7digit8digit9digitPC1 →PC2 →
Figure 3. 700 handwritten digits, each squeezed from 64 pixel features to just 2 components and drawn as its own number. PCA never saw the labels, yet many digits form their own clouds: 0s at the bottom, 3s on the left, and 4s and 6s on the right. Others, like 1, 5, 8 and 9, overlap in the middle.

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.

Three handwritten digits rebuilt from 2, 5, 10 and 30 principal components, next to the original. With 2 components they are blurry blobs; with 10 they are recognisable; with 30 they look almost identical to the originals.2 comp.5 comp.10 comp.30 comp.Original
Figure 4. Three digits rebuilt from 2, 5, 10 and 30 components, next to the originals. With 2 components they're blurry blobs. By 10 they're recognisable. At 30, they're almost identical to the originals, using fewer than half the numbers.

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?

digits_pca.py
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}")
Output
 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

StrengthsWeaknesses
Speeds up training on data with many featuresComponents are hard to explain: "PC3" is a mix of many features
Removes redundancy and noise, which can reduce overfittingOnly finds straight-line directions; it can't follow curved patterns
Makes high-dimensional data visible in 2D or 3DAlways loses some information
Fast, simple and well understoodMust scale features first
No labels needed (unsupervised)Ignores labels, so it may drop directions that matter for your task
AreaHow PCA is used
FinanceSummarising how dozens of interest rates or share prices move together into a few main "factors"
Genetics and healthcareReducing thousands of gene measurements to a handful of components for study and visualisation
ImagesCompressing images and finding the main features of faces
Surveys and social researchCombining many related questions into a few underlying themes
Machine learning pipelinesShrinking features before KNN, SVMs or clustering to make them faster and more accurate
Data explorationA 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

  1. 01
    Introduction to Machine LearningWhat ML is and how it works
  2. 02
    Preparing Data for Machine LearningFeatures, encoding, scaling, train/test split
  3. 03
    Linear RegressionPredicting numbers
  4. 04
    Logistic RegressionPredicting yes or no
  5. 05
    Evaluating ModelsAccuracy, precision, recall, overfitting, cross-validation
  6. 06
    K-Nearest NeighboursLearning from similar examples
  7. 07
    Decision TreesFlowcharts that learn
  8. 08
    Random Forest and Gradient BoostingMany models working together
  9. 09
    Support Vector MachinesFinding the best boundary
  10. 10
    Naive BayesProbability-based classification
  11. 11
    Clustering with K-MeansFinding groups without labels
  12. 12
    Dimensionality Reduction with PCAYou are here
  13. 13
    Capstone ProjectBuild and present a full ML project