edSlash Labs  /  Machine Learning Lab  /  Unsupervised Learning  /  PCA
Algorithm 04 · Unsupervised learning · Dimensionality reduction

Principal Component Analysis (PCA)

Learn how PCA reduces the number of features in a dataset. It finds new directions that capture the largest patterns in the data, so we can keep useful information with fewer dimensions.

Beginner friendly

The big idea

Keep the most important directions. Reduce the number of features.

Many features → Fewer componentsPCA creates new features called principal components.

Imagine a cloud of points on a graph. PCA finds the direction in which the points spread out the most. That direction is the first principal component (PC1). The next component captures as much of the remaining variation as possible and is at a right angle to PC1.

PCA is often used to simplify data, reduce noise, speed up models, and make high-dimensional data easier to visualise.

Key ideas

What PCA is looking for.

Variance

How much a feature or direction spreads out. PCA tries to keep directions with high variance.

Principal components

New directions made by combining the original features.

Explained variance

The share of the data's variation captured by each component.

Important: PCA is not a feature selection method. It creates new features from combinations of the old ones. It does not use target labels, so it is an unsupervised technique.

1. How does PCA work?

It rotates the view of the data to find its strongest directions.

The main steps

Prepare the data

Put features on comparable scales when needed. Usually, subtract each feature's mean. Standardise features if their scales differ.

Find how features vary together

Calculate the covariance matrix (or use singular value decomposition, SVD).

Find principal directions

Find eigenvectors and eigenvalues. Eigenvectors give the directions; eigenvalues tell how much variance lies along them.

Rank the components

Sort components from the largest eigenvalue to the smallest.

Project the data

Keep the first few components and express each row using those new coordinates.

A simple picture

Think of a long, tilted cloud of points. The points spread out most along its long direction. PCA turns the axes to line up with that direction. If most of the spread is along one direction, we may describe the data with just one component instead of two.

Do not confuse: PCA changes the coordinate system. It does not simply remove the original columns with the smallest values.

2. Live PCA playground

Change the data shape and number of components. Watch the principal directions and projected data update.

Interactive experiment

Before and after PCA

Left: original feature space. Right: coordinates after projection.

Original data + PC axes
Reduced representation
Data pointsPC1 directionPC2 direction / projection

The demo uses two input features, so the maximum number of components is two. Real PCA can reduce hundreds of features to a smaller number.

Standardising gives both features unit variance before PCA.

PC1 variance—
PC2 variance—
Variance kept—
Components kept1 / 2
PCA is ready. The first component points in the direction with the most variance.
Try keeping one component, then switch to two. Increase the data spread setting to make the main direction more obvious.

3. The mathematics behind PCA

You only need a few ideas to understand what the algorithm is doing.

Covariance matrix

Covariance describes how two features change together. For two features, the covariance matrix looks like this:

Σ = [ σ₁²   cov(1,2)
cov(1,2)   σ₂² ]

The diagonal values are the variances of each feature. The other values show how the features move together.

Eigenvectors and eigenvalues

Σv = λv

An eigenvector (v) gives a principal direction. Its eigenvalue (λ) tells how much variance is captured along that direction. PCA sorts the eigenvalues from largest to smallest.

The first principal component has the largest eigenvalue. The second is perpendicular to the first and captures the next largest amount of variance.

Projecting the data

Z = Xcentred Wk

X is the prepared data. Wk contains the first k principal directions. Z is the new, smaller representation of the data. Each row in Z is the original row expressed using the selected components.

4. Worked example: reducing two features to one

Imagine two measurements that often increase together.

Small example dataset

Suppose we record study hours and test practice scores for five learners.

LearnerStudy hoursPractice score
A12
B23
C35
D46
E58

What PCA does

Notice the relationship

Higher study hours generally go with higher practice scores. The two columns contain similar information.

Find the main direction

PCA finds a direction that follows the shared pattern in both measurements.

Make one new feature

Each learner gets a PC1 score. We can use that one score instead of both original columns, while accepting some information loss.

The example is for understanding the idea. A real PCA result depends on how the data is centred or scaled and on the values in the full dataset.

5. Explained variance: how many components should we keep?

Keep enough components to preserve the amount of information you need.

Illustrative explained variance

Imagine PCA finds these shares of variance in a dataset:

PC160%
PC225%
PC310%
PC45%

Together, PC1 and PC2 explain 85% of the variance in this example.

Common ways to choose k

Cumulative explained variance

Choose enough components to reach a target, such as 90% or 95%, if that suits the task.

Scree plot

Plot each component's variance. Look for the point where the curve starts to flatten.

Test the result

Check how much useful performance or information is lost after reducing the dimensions.

The percentages above are an example, not a result from the playground. Explained variance measures spread in the data; it does not guarantee that every useful pattern for a prediction task is kept.

6. PCA in Python

Scikit-learn provides PCA, including the projection and explained variance scores.

Dimensionality reduction with scikit-learn

Copy this example into a Python notebook.

# Install the libraries if needed:
# pip install numpy scikit-learn

import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

# Example data: four measurements for six records
X = np.array([
    [2.5, 2.4, 1.2, 1.0],
    [0.5, 0.7, 0.4, 0.3],
    [2.2, 2.9, 1.1, 1.4],
    [1.9, 2.2, 0.9, 0.8],
    [3.1, 3.0, 1.5, 1.3],
    [2.3, 2.7, 1.0, 1.2]
])

# Standardise features before PCA when scales differ
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# Reduce four features to two components
pca = PCA(n_components=2)
X_reduced = pca.fit_transform(X_scaled)

print("Reduced data:")
print(X_reduced)

# Share of variance captured by each component
print("Explained variance ratio:")
print(pca.explained_variance_ratio_)

# Total share captured by the selected components
print("Total variance kept:")
print(pca.explained_variance_ratio_.sum())

Use the same fitted scaler and PCA object when transforming new records. Fit them on the training data only when preparing a machine-learning pipeline.

Good practice: fit scaling and PCA on the training set, then use those fitted steps on validation and test data. This helps prevent information from leaking into model training.

Useful Python terms

StandardScaler centres and scales features. PCA(n_components=2) keeps two components. fit_transform() learns the directions and projects the data. explained_variance_ratio_ reports the share captured by each component.

7. Where is PCA used in real life?

PCA is useful when a dataset has many features or strong relationships between them.

Data visualisation

Reduce many features to two or three components so patterns can be plotted.

Image compression

Represent image data with fewer values while keeping much of its variation.

Noise reduction

Remove low-variance directions that may contain small or noisy changes.

Preprocessing

Create a smaller set of inputs before using another machine-learning model.

Strengths and limitations

Know what PCA can—and cannot—do.

Strengths

  • Can reduce many features to fewer components.
  • Can remove repeated information from correlated features.
  • Can make complex data easier to plot.
  • Can reduce storage and model training time.

Limitations

  • Components can be hard to explain.
  • It mainly captures linear patterns.
  • Results can change with feature scaling.
  • Some information is lost when components are removed.
  • High variance does not always mean high usefulness for prediction.

PCA vs feature selection

QuestionPCAFeature selection
What does it keep?New combinations of original features.A chosen set of original features.
Are the original columns retained?They are combined into components.Selected columns stay as they are.
Does it use the target label?No, standard PCA is unsupervised.Some methods use labels; others do not.
Main goalCapture variance with fewer dimensions.Keep useful original inputs.

8. Knowledge check

Answer one question at a time. Your score and explanations will appear after the final question.

0 of 10 answered

Mini challenge

In the playground, make the points follow one strong direction. Keep only PC1. Then change the data so it spreads more evenly. Does PC1 still explain as much of the variance?

Explain in your own words why PCA can reduce the number of features but still keep much of the information.