Lecture 14: Dimensionality Reduction
A comprehensive guide to dimensionality reduction techniques, focusing on Principal Component Analysis (PCA), data compression, visualization, mathematical formulation, algorithm implementation, reconstruction, and practical guidance.
Motivation 1: Data Compression
Dimensionality reduction is a second major class of unsupervised learning problems.
Why Dimensionality Reduction?
- Compression: Reduces the space required to store data on disk or in memory.
- Speedup: Accelerates machine learning algorithms by reducing the number of input features.
What is Dimensionality Reduction?
When building datasets, you may collect a large number of features—sometimes more than necessary. Dimensionality reduction allows us to simplify datasets in a rational and structured way.
Example 1: Redundant Features ()
Consider a dataset containing redundant features, such as measuring the same attribute in two different units (e.g., length in centimeters vs. length in inches ).

- In real-world data, examples may not lie on a perfect straight line due to measurement noise or round-off errors.
- Data redundancy often occurs when different teams collect data independently without centralized control.
- We can project these 2D points onto a single 1D line to reduce the dataset from 2D to 1D ().
Example 2: Pilot Aptitude
In a survey of helicopter pilots:
These features are highly correlated and can be merged into a single summary feature such as "pilot aptitude."
Representing Compressed Data
When projecting 2D data onto a line, we record the position of each sample along that single line ():

- Original representation: (a 2D feature vector with and dimensions).
- Compressed representation: (a single 1D scalar value).
- This cuts storage requirements in half with acceptable lossy compression.
Example 3: Compression
Consider a 3D dataset:

All data points may approximately lie within a 2D plane (e.g., sitting inside a shallow box/tray):

Because the points fall within a shallow depth range, we can drop the perpendicular depth dimension and project the points onto two new axes ( and ) lying on the plane:

This reduces a 3D feature vector to a 2D feature vector (). In large-scale machine learning applications, PCA is often used for massive reductions such as .
Motivation 2: Visualization
It is extremely difficult to visualize data in high dimensions (e.g., 50D). Dimensionality reduction allows us to compress features to 2D or 3D for intuitive visualization and exploration.
Why Visualization Matters
- Understanding data structure helps guide algorithm design.
- Makes it easier to communicate patterns, clusters, and trends to others.
Example: Global Country Statistics
Suppose we collect a dataset containing 50 statistics for various countries:

Plotting 50 dimensions directly is impossible. Using dimensionality reduction, we convert each 50-dimensional feature vector into a 2-dimensional vector :

We can then plot the dataset on a 2D graph ( vs. ).
Interpreting Summary Features
Unsupervised learning algorithms do not automatically assign semantic labels to the new dimensions and . We inspect the axes to infer their meaning:
- (Horizontal Axis): May correspond to overall country size / total economic output.
- (Vertical Axis): May correspond to per-person well-being or individual economic prosperity.
Feature scaling is crucial prior to dimensionality reduction so all attributes contribute proportionally.
Principal Component Analysis (PCA): Problem Formulation
The most widely used algorithm for dimensionality reduction is Principal Component Analysis (PCA).
Goal of PCA
For reduction, we seek a line onto which the data can be projected:

PCA finds a lower-dimensional surface (a line in 2D) that minimizes the projection error (the sum of squared shortest distances from each point to the surface):

Note: Always perform mean normalization and feature scaling on data before running PCA.
Formal Description
- : Find a vector that defines the projection line minimizing the squared projection error:

The direction vector can be positive or negative (i.e., and define the exact same line).
- General Case (): Find vectors onto which to project the data so as to minimize the projection error.
- The projected points lie on the linear subspace spanned by .
- For , PCA finds two vectors and that define a 2D plane:

PCA vs. Linear Regression
PCA is not linear regression! Despite visual similarities, they minimize entirely different quantities:
- Linear Regression: Minimizes the vertical distance between each point and the fitted line (predicting target from features ).
- PCA: Minimizes the shortest orthogonal (perpendicular) distance between each point and the projection line/surface. All features are treated symmetrically with no separate target label .
PCA Algorithm
1. Data Preprocessing
Given an unlabeled dataset where :
- Mean Normalization:
- Compute feature means:
- Replace each with so that every feature has mean .
- Feature Scaling (if features have different scales):
- Rescale features: , where is the range () or standard deviation.
2. Algorithm Overview ()

We need to calculate two sets of variables:
- vectors: The vectors defining the projection plane/subspace.
- vectors: The lower-dimensional feature representations.
3. Step-by-Step Algorithm ()
Step 1: Compute Covariance Matrix

- (uppercase Greek letter Sigma) is an matrix (not to be confused with summation notation).
- is an column vector.
Step 2: Compute Eigenvectors of
In Octave / MATLAB, compute Singular Value Decomposition (SVD):
![]()
[U, S, V] = svd(sigma);svdis numerically more stable thaneig(eigenvalue decomposition).- is an matrix whose columns are the eigenvectors .
- To reduce from to , take the first columns of :

Step 3: Project Data onto Lower Dimension
Calculate for each example :
- Dimension check: is and is , producing .
Summary of PCA Steps
% 1. Preprocess data (mean normalization & scaling)
% 2. Compute covariance matrix
Sigma = (1/m) * (X' * X);
% 3. Compute eigenvectors
[U, S, V] = svd(Sigma);
% 4. Select top k principal components
Ureduce = U(:, 1:k);
% 5. Compute reduced features Z
Z = X * Ureduce; % (m x k)Reconstruction from Compressed Representation
Since PCA compresses data, can we decompress a low-dimensional vector back into an approximation of original high-dimensional space ?
Reconstruction Formula
Given , the reconstructed feature vector is:

Dimensionality Verification

projects the compressed points back into -dimensional space. While fine detail off the projection line is lost during compression, closely approximates the original data points.
Choosing the Number of Principal Components
How do we select the parameter (number of principal components)?
Mathematical Definitions
-
Average Squared Projection Error:
-
Total Variation in Data:
(Average squared distance of training samples from origin).
Variance Retained Ratio
We select such that the ratio of projection error to total variation is small:

When this condition is satisfied, we say that 99% of the variance is retained. Common choices retain 99% or 95% of total variance.
Efficient Selection of

Instead of iteratively running PCA for different values of , use matrix from a single [U, S, V] = svd(Sigma) call.
is an diagonal matrix (). The variance retained ratio simplifies to:
Test until the smallest satisfying this threshold is found.
Advice for Applying PCA
Speeding Up Supervised Learning Algorithms
Suppose you have a supervised dataset with very high-dimensional inputs (e.g., image pixels ).
Step-by-Step Implementation
- Extract features: Form unlabelled set .
- Run PCA: Map .
- Form new training set: Pair reduced features with labels .
- Train model: Train classifier (e.g., logistic regression, neural network) on .
- Prediction: For a new test sample , apply learned PCA mapping , then feed to trained model.
CRITICAL RULE: PCA parameters () must be learned ONLY on the training set. Once computed, apply these exact parameters to cross-validation and test sets.
PCA typically reduces feature dimensions by with minimal impact on predictive performance.
Applications of PCA
Good Applications
- Compression:
- Reduces disk/RAM storage.
- Speeds up learning algorithms.
- Parameter chosen based on % variance retained (e.g., 99%).
- Visualization:
- Reduces data to or for plotting.
Misuse of PCA: Preventing Overfitting
- Flawed Reasoning: Reducing feature count from to reduces model capacity and might prevent overfitting.
- Why it fails: PCA discards features without looking at class labels . It may throw away information vital for classification.
- Better Alternative: Use regularization (). Regularization keeps all features while penalizing large weights, producing superior results.
PCA Implementation Advice
- Do not apply PCA prematurely: Start by building and evaluating your machine learning system on raw data without PCA.
- Only add PCA if necessary: Implement PCA only if you observe that training is prohibitively slow or memory usage exceeds system constraints.
Lecture 13: Clustering
An introduction to unsupervised learning and clustering, covering the K-means algorithm, optimization objective, random initialization, and techniques for selecting the optimal number of clusters.
Lecture 15: Anomaly Detection
Learn about anomaly detection algorithms, Gaussian distribution modeling, evaluation metrics, feature engineering, and multivariate Gaussian distributions for detecting outliers.