CSE-41XX
CS-4125 ML

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 (2D1D2\text{D} \to 1\text{D})

Consider a dataset containing redundant features, such as measuring the same attribute in two different units (e.g., length in centimeters x1x_1 vs. length in inches x2x_2).

Plot of 2D data with redundant features showing reduction to 1D

  • 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 (2D1D2\text{D} \to 1\text{D}).

Example 2: Pilot Aptitude

In a survey of helicopter pilots:

  • x1=pilot skillx_1 = \text{pilot skill}
  • x2=pilot enjoymentx_2 = \text{pilot enjoyment}

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 (zz):

Data points projected onto a 1D line with position z

  • Original representation: x(1)R2x^{(1)} \in \mathbb{R}^2 (a 2D feature vector with x1x_1 and x2x_2 dimensions).
  • Compressed representation: z(1)R1z^{(1)} \in \mathbb{R}^1 (a single 1D scalar value).
  • This cuts storage requirements in half with acceptable lossy compression.

Example 3: 3D2D3\text{D} \to 2\text{D} Compression

Consider a 3D dataset:

3D scatter plot of data points before reduction

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

3D data points lying on a 2D planar 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 (z1z_1 and z2z_2) lying on the plane:

2D projection plane showing axes z1 and z2

This reduces a 3D feature vector to a 2D feature vector (3D2D3\text{D} \to 2\text{D}). In large-scale machine learning applications, PCA is often used for massive reductions such as 1000D100D1000\text{D} \to 100\text{D}.


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:

Table of country statistics with high-dimensional features

  • x1=GDPx_1 = \text{GDP}
  • x2=Literacy ratex_2 = \text{Literacy rate}
  • \ldots
  • x6=Mean household incomex_6 = \text{Mean household income}
  • ,x50\ldots, x_{50}

Plotting 50 dimensions directly is impossible. Using dimensionality reduction, we convert each 50-dimensional feature vector x(i)R50x^{(i)} \in \mathbb{R}^{50} into a 2-dimensional vector z(i)R2z^{(i)} \in \mathbb{R}^2:

Country features reduced to 2D summary features z1 and z2 for plotting

We can then plot the dataset on a 2D graph (z1z_1 vs. z2z_2).

Interpreting Summary Features

Unsupervised learning algorithms do not automatically assign semantic labels to the new dimensions z1z_1 and z2z_2. We inspect the axes to infer their meaning:

  • z1z_1 (Horizontal Axis): May correspond to overall country size / total economic output.
  • z2z_2 (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 2D1D2\text{D} \to 1\text{D} reduction, we seek a line onto which the data can be projected:

2D scatter plot of data points for PCA formulation

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):

2D plot showing projection errors onto a line

Note: Always perform mean normalization and feature scaling on data before running PCA.

Formal Description

  • 2D1D2\text{D} \to 1\text{D}: Find a vector u(1)Rnu^{(1)} \in \mathbb{R}^n that defines the projection line minimizing the squared projection error:

Projection vector u1 defining the line of projection

The direction vector u(1)u^{(1)} can be positive or negative (i.e., u(1)u^{(1)} and u(1)-u^{(1)} define the exact same line).

  • General Case (nDkDn\text{D} \to k\text{D}): Find kk vectors u(1),u(2),,u(k)Rnu^{(1)}, u^{(2)}, \ldots, u^{(k)} \in \mathbb{R}^n onto which to project the data so as to minimize the projection error.
    • The projected points lie on the linear subspace spanned by {u(1),u(2),,u(k)}\{u^{(1)}, u^{(2)}, \ldots, u^{(k)}\}.
    • For 3D2D3\text{D} \to 2\text{D}, PCA finds two vectors u(1)u^{(1)} and u(2)u^{(2)} that define a 2D plane:

3D data points projected onto a 2D plane defined by u1 and u2

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 yy from features xx).
  • 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 yy.

PCA Algorithm

1. Data Preprocessing

Given an unlabeled dataset {x(1),x(2),,x(m)}\{x^{(1)}, x^{(2)}, \ldots, x^{(m)}\} where x(i)Rnx^{(i)} \in \mathbb{R}^n:

  1. Mean Normalization:
    • Compute feature means: μj=1mi=1mxj(i)\mu_j = \frac{1}{m} \sum_{i=1}^{m} x_j^{(i)}
    • Replace each xj(i)x_j^{(i)} with xj(i)μjx_j^{(i)} - \mu_j so that every feature has mean 00.
  2. Feature Scaling (if features have different scales):
    • Rescale features: xj(i)xj(i)μjsjx_j^{(i)} \leftarrow \frac{x_j^{(i)} - \mu_j}{s_j}, where sjs_j is the range (maxmin\text{max} - \text{min}) or standard deviation.

2. Algorithm Overview (2D1D2\text{D} \to 1\text{D})

2D to 1D PCA projection diagram

We need to calculate two sets of variables:

  1. uu vectors: The vectors defining the projection plane/subspace.
  2. zz vectors: The lower-dimensional feature representations.

3. Step-by-Step Algorithm (nDkDn\text{D} \to k\text{D})

Step 1: Compute Covariance Matrix Σ\Sigma

Covariance matrix Sigma mathematical formula

Σ=1mi=1m(x(i))(x(i))T\Sigma = \frac{1}{m} \sum_{i=1}^{m} (x^{(i)})(x^{(i)})^T

  • Σ\Sigma (uppercase Greek letter Sigma) is an n×nn \times n matrix (not to be confused with summation notation).
  • x(i)x^{(i)} is an n×1n \times 1 column vector.

Step 2: Compute Eigenvectors of Σ\Sigma

In Octave / MATLAB, compute Singular Value Decomposition (SVD):

Octave code computing SVD of covariance matrix

[U, S, V] = svd(sigma);
  • svd is numerically more stable than eig (eigenvalue decomposition).
  • UU is an n×nn \times n matrix whose columns are the eigenvectors u(1),u(2),,u(n)u^{(1)}, u^{(2)}, \ldots, u^{(n)}.
  • To reduce from nDn\text{D} to kDk\text{D}, take the first kk columns of UU:

Matrix U showing selection of top k columns for Ureduce

Ureduce=[u(1)u(2)u(k)]Rn×kU_{\text{reduce}} = \begin{bmatrix} | & | & & | \\ u^{(1)} & u^{(2)} & \dots & u^{(k)} \\ | & | & & | \end{bmatrix} \in \mathbb{R}^{n \times k}

Step 3: Project Data onto Lower Dimension

Calculate zRkz \in \mathbb{R}^k for each example xRnx \in \mathbb{R}^n:

z=UreduceTxz = U_{\text{reduce}}^T x

  • Dimension check: UreduceTU_{\text{reduce}}^T is k×nk \times n and xx is n×1n \times 1, producing zRk×1z \in \mathbb{R}^{k \times 1}.

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 zRkz \in \mathbb{R}^k back into an approximation of original high-dimensional space xRnx \in \mathbb{R}^n?

Reconstruction Formula

Given z=UreduceTxz = U_{\text{reduce}}^T x, the reconstructed feature vector xapproxx_{\text{approx}} is:

xapprox=Ureducezx_{\text{approx}} = U_{\text{reduce}} z

Original 2D data points projected to 1D z coordinates

Dimensionality Verification

  • UreduceRn×kU_{\text{reduce}} \in \mathbb{R}^{n \times k}
  • zRk×1z \in \mathbb{R}^{k \times 1}
  • xapprox=UreducezRn×1x_{\text{approx}} = U_{\text{reduce}} z \in \mathbb{R}^{n \times 1}

Reconstructed points xapprox lying on the projection line

xapproxx_{\text{approx}} projects the compressed points back into nn-dimensional space. While fine detail off the projection line is lost during compression, xapproxx_{\text{approx}} closely approximates the original data points.


Choosing the Number of Principal Components

How do we select the parameter kk (number of principal components)?

Mathematical Definitions

  1. Average Squared Projection Error: Formula for average squared projection error 1mi=1mx(i)xapprox(i)2\frac{1}{m} \sum_{i=1}^{m} ||x^{(i)} - x_{\text{approx}}^{(i)}||^2

  2. Total Variation in Data: Formula for total variation in data 1mi=1mx(i)2\frac{1}{m} \sum_{i=1}^{m} ||x^{(i)}||^2 (Average squared distance of training samples from origin).

Variance Retained Ratio

We select kk such that the ratio of projection error to total variation is small:

Variance ratio inequality for retaining 99% of variance

1mi=1mx(i)xapprox(i)21mi=1mx(i)20.01\frac{\frac{1}{m} \sum_{i=1}^{m} ||x^{(i)} - x_{\text{approx}}^{(i)}||^2}{\frac{1}{m} \sum_{i=1}^{m} ||x^{(i)}||^2} \le 0.01

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 kk

Algorithm for choosing k using SVD diagonal matrix S

Instead of iteratively running PCA for different values of kk, use matrix SS from a single [U, S, V] = svd(Sigma) call.

SS is an n×nn \times n diagonal matrix (S1,1,S2,2,,Sn,nS_{1,1}, S_{2,2}, \ldots, S_{n,n}). The variance retained ratio simplifies to:

i=1kSiii=1nSii0.99\frac{\sum_{i=1}^{k} S_{ii}}{\sum_{i=1}^{n} S_{ii}} \ge 0.99

Test k=1,2,k = 1, 2, \dots until the smallest kk satisfying this threshold is found.


Advice for Applying PCA

Speeding Up Supervised Learning Algorithms

Suppose you have a supervised dataset (x(1),y(1)),(x(2),y(2)),,(x(m),y(m))(x^{(1)}, y^{(1)}), (x^{(2)}, y^{(2)}), \ldots, (x^{(m)}, y^{(m)}) with very high-dimensional inputs (e.g., 100×100100 \times 100 image pixels     xR10,000\implies x \in \mathbb{R}^{10,000}).

Step-by-Step Implementation

  1. Extract features: Form unlabelled set x(1),x(2),,x(m)Rnx^{(1)}, x^{(2)}, \ldots, x^{(m)} \in \mathbb{R}^n.
  2. Run PCA: Map x(i)z(i)Rkx^{(i)} \to z^{(i)} \in \mathbb{R}^k.
  3. Form new training set: Pair reduced features with labels (z(1),y(1)),,(z(m),y(m))(z^{(1)}, y^{(1)}), \dots, (z^{(m)}, y^{(m)}).
  4. Train model: Train classifier (e.g., logistic regression, neural network) on (z,y)(z, y).
  5. Prediction: For a new test sample xtestx_{\text{test}}, apply learned PCA mapping xtestztestx_{\text{test}} \to z_{\text{test}}, then feed ztestz_{\text{test}} to trained model.

CRITICAL RULE: PCA parameters (μ,s,Ureduce\mu, s, U_{\text{reduce}}) 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 5×10×5\times - 10\times with minimal impact on predictive performance.


Applications of PCA

Good Applications

  1. Compression:
    • Reduces disk/RAM storage.
    • Speeds up learning algorithms.
    • Parameter kk chosen based on % variance retained (e.g., 99%).
  2. Visualization:
    • Reduces data to k=2k = 2 or k=3k = 3 for plotting.

Misuse of PCA: Preventing Overfitting

  • Flawed Reasoning: Reducing feature count from nn to kk reduces model capacity and might prevent overfitting.
  • Why it fails: PCA discards features without looking at class labels yy. It may throw away information vital for classification.
  • Better Alternative: Use regularization (λ\lambda). 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.

On this page