6. Unsupervised Learning: Dimensionality Reduction
PCA Mathematical Intuition and Variance Projection
In machine learning, datasets often contain dozens or hundreds of features. This high dimensionality introduces the 'curse of dimensionality', where the volume of space increases exponentially, making the data sparse and causing models to overfit. Principal Component Analysis (PCA) is a powerful unsupervised linear technique designed to address this problem by reducing the dimensions of a dataset while preserving as much variance (information) as possible.
To understand the mathematical intuition of PCA, imagine a 2D cloud of data points. PCA seeks to find a new coordinate system. The first principal component (PC1) is a line that passes through the direction of maximum variance in the data. By projecting data points onto this line, we retain the highest amount of information. The second principal component (PC2) must be orthogonal (at a 90-degree angle) to PC1, capturing the highest remaining variance.
The mathematical steps to perform PCA are as follows: First, we standardize the features so they have a mean of 0 and variance of 1. Second, we compute the Covariance Matrix, which measures how each pair of variables changes together. Third, we compute the Eigenvectors and Eigenvalues of this covariance matrix. Eigenvectors represent the directions of the new axes (the principal components), while their corresponding Eigenvalues represent the amount of variance carried by each component. Finally, we sort the eigenvectors by their eigenvalues in descending order and project our original data onto these eigenvectors.
import numpy as np # 1. Create a simulated 2D dataset where X and Y are highly correlated np.random.seed(42) x = np.random.normal(0, 1, 100) y = 2 * x + np.random.normal(0, 0.5, 100) X = np.column_stack((x, y)) # 2. Standardize the data (zero mean, unit variance) X_std = (X - np.mean(X, axis=0)) / np.std(X, axis=0) # 3. Compute the Covariance Matrix cov_matrix = np.cov(X_std.T) # 4. Calculate Eigenvalues and Eigenvectors eigenvalues, eigenvectors = np.linalg.eig(cov_matrix) # 5. Sort eigenvalues and eigenvectors in descending order idx = eigenvalues.argsort()[::-1] eigenvalues = eigenvalues[idx] eigenvectors = eigenvectors[:, idx] # 6. Project data onto the first principal component projection_matrix = eigenvectors[:, 0] X_projected = X_std.dot(projection_matrix) print('Eigenvalues (Variance explained):', eigenvalues) print('Top Eigenvector (PC1 Direction):', projection_matrix) print('Projected Data Shape:', X_projected.shape)
Tuning n_components and Interpreting explained_variance_ratio_
In practice, you do not need to implement PCA from scratch using raw matrix algebra. Scikit-learn provides a highly optimized implementation in sklearn.decomposition.PCA. When utilizing this class, the most critical hyperparameter to tune is n_components, which controls how many principal components you want to retain.
How do you determine the optimal number of components? We look at the explained_variance_ratio_ attribute. This attribute returns an array where each element represents the proportion of the dataset's total variance that lies along each principal component. By summing these values cumulatively, we can determine the minimum number of components required to retain a target percentage of information (e.g., 90% or 95%).
Scikit-learn also offers an elegant shortcut: if you pass a float between 0.0 and 1.0 to the n_components parameter during instantiation, PCA will automatically select the minimum number of components needed to preserve that specific fraction of the variance.
import numpy as np from sklearn.decomposition import PCA from sklearn.datasets import make_classification # Generate a high-dimensional synthetic dataset (20 features) X, y = make_classification(n_samples=150, n_features=20, n_informative=5, random_state=42) # Instantiate PCA without reducing dimensions initially pca_full = PCA() pca_full.fit(X) # Print explained variance ratio per component explained_var = pca_full.explained_variance_ratio_ cumulative_var = np.cumsum(explained_var) print('Explained Variance Ratio per Component:\n', np.round(explained_var[:5], 4)) print('Cumulative Variance Explained:\n', np.round(cumulative_var[:5], 4)) # Instantiate PCA to retain exactly 90% of the total variance pca_90 = PCA(n_components=0.90) X_reduced = pca_90.fit_transform(X) print(f'\nOriginal number of features: {X.shape[1]}') print(f'Reduced number of features (retaining 90% variance): {X_reduced.shape[1]}')
Visualizing 2D Projections of High-Dimensional Datasets
One of the most practical everyday use-cases for dimensionality reduction is data visualization. Human perception is limited to 2D or 3D environments, making it impossible to directly plot a dataset with dozens of features to check for patterns, outliers, or clusters.
By applying PCA and setting n_components=2, we can compress any multi-dimensional dataset down into a standard 2-dimensional coordinate space. While we inevitably lose some information during this lossy compression, we preserve the directions of maximum variance.
Once the dataset is reduced to two features (Principal Component 1 and Principal Component 2), we can plot the coordinates using a scatter plot. Color-coding the points with target class labels (even though PCA is unsupervised and does not use these labels during fitting) helps us visually diagnose whether classes are linearly separable in the reduced space.
import matplotlib.pyplot as plt import pandas as pd from sklearn.datasets import load_iris from sklearn.decomposition import PCA # Load the 4-dimensional Iris dataset iris = load_iris() X = iris.data y = iris.target target_names = iris.target_names # Project down to 2 dimensions using PCA pca = PCA(n_components=2) X_r = pca.fit_transform(X) # Create a visualization plot plt.figure(figsize=(8, 6)) colors = ['navy', 'turquoise', 'darkorange'] lw = 2 for color, i, target_name in zip(colors, [0, 1, 2], target_names): plt.scatter(X_r[y == i, 0], X_r[y == i, 1], color=color, alpha=.8, lw=lw, label=target_name) plt.legend(loc='best', shadow=False, scatterpoints=1) plt.title('PCA 2D Projection of the 4D Iris Dataset') plt.xlabel(f'PC1 ({pca.explained_variance_ratio_[0]:.2%} variance)') plt.ylabel(f'PC2 ({pca.explained_variance_ratio_[1]:.2%} variance)') plt.grid(True, linestyle='--', alpha=0.5) plt.show()
Non-Linear Reduction: t-SNE and Perplexity Parameters
PCA is a linear dimensionality reduction method. It projects data points on straight axes, which works beautifully if your data lies on a flat plane. However, if your data exists on a highly curved manifold (like a Swiss Roll or concentric circles), linear PCA fails to capture the underlying structure.
t-Distributed Stochastic Neighbor Embedding (t-SNE) is a state-of-the-art non-linear dimensionality reduction technique designed to capture local structure. It maps high-dimensional points to 2D or 3D coordinates such that similar points in high-dimensional space remain close together, and dissimilar points are placed far apart.
Here is a comparison between the two methods:
| Feature | PCA | t-SNE |
|---|---|---|
| Algorithm Type | Linear projection | Non-linear probabilistic manifold |
| Goal | Maximize global variance preservation | Preserve local neighborhood similarity |
| Out-of-sample projection | Yes (has a transform method) | No (requires re-running the optimization) |
The most critical parameter in t-SNE is perplexity. Perplexity can be thought of as a target number of nearest neighbors that each point considers when determining local structures. Standard values range from 5 to 50. Low perplexity isolates local patterns to a high degree (making clusters look tight but scattered), while high perplexity emphasizes global relationships.
from sklearn.manifold import TSNE from sklearn.datasets import make_circles import matplotlib.pyplot as plt # Generate a non-linear concentric circles dataset X, y = make_circles(n_samples=300, noise=0.05, factor=0.5, random_state=0) # Apply t-SNE with a specific perplexity tsne = TSNE(n_components=2, perplexity=30.0, random_state=42, n_iter=1000) X_tsne = tsne.fit_transform(X) # Plot the t-SNE mapping plt.figure(figsize=(8, 6)) plt.scatter(X_tsne[y == 0, 0], X_tsne[y == 0, 1], color='red', label='Outer Circle') plt.scatter(X_tsne[y == 1, 0], X_tsne[y == 1, 1], color='blue', label='Inner Circle') plt.title('t-SNE Projection of Non-Linear Circles') plt.legend() plt.grid(True, linestyle='--', alpha=0.5) plt.show()
Knowledge Check
Ready to test your understanding of 6. Unsupervised Learning: Dimensionality Reduction?