Steps of Principal Component Analysis (PCA)
Principal Component Analysis (PCA) reduces dimensionality by projecting centered (and typically standardized) data onto orthogonal directions of maximum variance. The core steps are centering and scaling features, computing the covariance matrix, finding its eigenvectors and eigenvalues (or SVD), selecting the top k components by explained variance, and projecting the data onto that subspace.
Study Card: Steps of Principal Component Analysis (PCA)
Direct Answer
Principal Component Analysis (PCA) transforms correlated features into a smaller set of uncorrelated orthogonal components capturing maximum variance. The 5 steps are:
- Mean-Center (and Standardize) Data: Subtract each feature’s mean (). When features have different units or scales, divide by each feature’s standard deviation (-score standardization) so large-scale features do not dominate.
- Compute Covariance Matrix: For centered matrix , compute .
- Perform Eigendecomposition (or SVD): Solve for orthonormal eigenvectors and eigenvalues sorted descending ().
- Select Top Components: Form projection matrix choosing by cumulative explained variance ratio or scree plot.
- Project Data: Compute low-dimensional coordinates .
Practical applications include dimensionality reduction, noise filtering, multicollinearity removal, and 2D/3D exploratory visualization.
Key Terms
- Mean-Centering & Standardization: Centering is mandatory for covariance computation; scaling to unit variance prevents features with larger numerical ranges from skewing principal directions.
- Covariance Matrix (): Symmetric positive semi-definite matrix capturing pairwise linear covariances between features.
- Eigendecomposition: Factorizing into orthogonal principal directions (eigenvectors) and directional variances (eigenvalues).
- Eigenvalues (): Variance of the data along principal component .
- Eigenvectors (): Unit orthogonal basis vectors defining the principal component axes.
Example
Consider customer records with age, annual_income, and purchase_frequency:
- Standardize all three features so
annual_incomein tens of thousands does not overwhelmageandfrequency. - Compute the covariance (correlation) matrix of the standardized features.
- Eigendecompose to obtain 3 eigenvalues and eigenvectors.
- Select the top eigenvectors if they explain e.g. 90% of total variance.
- Project the standardized matrix onto those 2 eigenvectors to produce compact features.
Code Implementation
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
# Sample Data
np.random.seed(42)
data = {
'feature1': np.random.rand(100) * 10,
'feature2': 3 * np.random.rand(100) + 2,
'feature3': 0.5 * np.random.rand(100) - 1,
}
df = pd.DataFrame(data)
# Step 1: Standardize (center to zero mean and scale to unit variance)
X_scaled = StandardScaler().fit_transform(df)
# Step 2: Calculate the covariance matrix
covariance_matrix = np.cov(X_scaled, rowvar=False)
# Step 3 & 4: Eigendecomposition (eigh for symmetric matrices) sorted descending
eigvals, eigvecs = np.linalg.eigh(covariance_matrix)
order = np.argsort(eigvals)[::-1]
eigvals = eigvals[order]
eigvecs = eigvecs[:, order]
n_components = 2
W_k = eigvecs[:, :n_components]
# Step 5: Project data onto top k eigenvectors (and cross-check with scikit-learn PCA)
X_pca_manual = X_scaled @ W_k
pca = PCA(n_components=n_components)
X_pca = pca.fit_transform(X_scaled)
print("Manual Explained Variance Ratio: ", np.round(eigvals[:n_components] / eigvals.sum(), 6))
print("Sklearn Explained Variance Ratio:", np.round(pca.explained_variance_ratio_, 6))
# Scree plot for Explained Variance Ratio
plt.figure(figsize=(8, 5))
plt.bar(range(1, n_components + 1), pca.explained_variance_ratio_)
plt.xlabel('Principal Components')
plt.xticks(np.arange(1, n_components + 1))
plt.ylabel('Explained Variance Ratio')
plt.title('Scree Plot for PCA')
plt.show()
# Visualize projected data
plt.figure(figsize=(8, 6))
plt.scatter(X_pca[:, 0], X_pca[:, 1])
plt.xlabel('Principal Component 1')
plt.ylabel('Principal Component 2')
plt.title('PCA Projection of Data')
plt.show()
Related Concepts
- Eigenvalues and Eigenvectors: Eigenvectors give orthogonal axes of maximal variance; eigenvalues measure variance captured along each axis.
- Covariance vs. Correlation Matrix: Running PCA on standardized data equals eigendecomposing the Pearson correlation matrix, which is preferred whenever features carry incompatible units.
- Singular Value Decomposition (SVD): Practical implementations (
sklearn.decomposition.PCA) compute truncated SVD of directly in , avoiding forming (which squares condition numbers) and scaling efficiently when . - Comparison with t-SNE & LDA: PCA is linear and unsupervised; t-SNE is non-linear for visualization; LDA is linear and supervised (maximizing class separability).
- Scree Plot & Cumulative Variance: Used to choose (e.g., retaining 95% cumulative variance). Remember to fit
StandardScalerandPCAon training data only before transforming test sets.