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.
The big idea
Keep the most important directions. Reduce the number of features.
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.
How much a feature or direction spreads out. PCA tries to keep directions with high variance.
New directions made by combining the original features.
The share of the data's variation captured by each component.
1. How does PCA work?
It rotates the view of the data to find its strongest directions.
The main steps
Put features on comparable scales when needed. Usually, subtract each feature's mean. Standardise features if their scales differ.
Calculate the covariance matrix (or use singular value decomposition, SVD).
Find eigenvectors and eigenvalues. Eigenvectors give the directions; eigenvalues tell how much variance lies along them.
Sort components from the largest eigenvalue to the smallest.
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.
2. Live PCA playground
Change the data shape and number of components. Watch the principal directions and projected data update.
Before and after PCA
Left: original feature space. Right: coordinates after 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.
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) σ₂² ]
The diagonal values are the variances of each feature. The other values show how the features move together.
Eigenvectors and eigenvalues
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
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.
| Learner | Study hours | Practice score |
|---|---|---|
| A | 1 | 2 |
| B | 2 | 3 |
| C | 3 | 5 |
| D | 4 | 6 |
| E | 5 | 8 |
What PCA does
Higher study hours generally go with higher practice scores. The two columns contain similar information.
PCA finds a direction that follows the shared pattern in both measurements.
Each learner gets a PC1 score. We can use that one score instead of both original columns, while accepting some information loss.
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:
Together, PC1 and PC2 explain 85% of the variance in this example.
Common ways to choose k
Choose enough components to reach a target, such as 90% or 95%, if that suits the task.
Plot each component's variance. Look for the point where the curve starts to flatten.
Check how much useful performance or information is lost after reducing the dimensions.
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.
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
| Question | PCA | Feature 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 goal | Capture 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.
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?