Skip to content
E
Educatum

Steps of Principal Component Analysis (PCA)

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

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:

  1. Mean-Center (and Standardize) Data: Subtract each feature’s mean (Xc=X−μX_c = X - \mu). When features have different units or scales, divide by each feature’s standard deviation (zz-score standardization) so large-scale features do not dominate.
  2. Compute Covariance Matrix: For centered matrix Xc∈Rn×dX_c \in \mathbb{R}^{n \times d}, compute Σ=1n−1XcTXc\Sigma = \frac{1}{n - 1} X_c^T X_c.
  3. Perform Eigendecomposition (or SVD): Solve Σvj=λjvj\Sigma v_j = \lambda_j v_j for orthonormal eigenvectors vjv_j and eigenvalues λj≥0\lambda_j \ge 0 sorted descending (λ1≥λ2≥⋯≥λd\lambda_1 \ge \lambda_2 \ge \dots \ge \lambda_d).
  4. Select Top kk Components: Form projection matrix Wk=[v1,…,vk]∈Rd×kW_k = [v_1, \dots, v_k] \in \mathbb{R}^{d \times k} choosing kk by cumulative explained variance ratio ∑j=1kλj/∑j=1dλj\sum_{j=1}^k \lambda_j / \sum_{j=1}^d \lambda_j or scree plot.
  5. Project Data: Compute low-dimensional coordinates Z=XcWk∈Rn×kZ = X_c W_k \in \mathbb{R}^{n \times k}.

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 (Σ\Sigma): Symmetric positive semi-definite d×dd \times d matrix capturing pairwise linear covariances between features.
  • Eigendecomposition: Factorizing Σ\Sigma into orthogonal principal directions (eigenvectors) and directional variances (eigenvalues).
  • Eigenvalues (λj\lambda_j): Variance of the data along principal component vjv_j.
  • Eigenvectors (vjv_j): Unit orthogonal basis vectors defining the principal component axes.

Example

Consider customer records with age, annual_income, and purchase_frequency:

  1. Standardize all three features so annual_income in tens of thousands does not overwhelm age and frequency.
  2. Compute the 3×33 \times 3 covariance (correlation) matrix of the standardized features.
  3. Eigendecompose to obtain 3 eigenvalues and eigenvectors.
  4. Select the top k=2k=2 eigenvectors if they explain e.g. 90% of total variance.
  5. Project the n×3n \times 3 standardized matrix onto those 2 eigenvectors to produce compact n×2n \times 2 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()
  • 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 Xc=USVTX_c = U S V^T directly in O(min⁡(n2d,nd2))O(\min(n^2 d, n d^2)), avoiding forming XcTXcX_c^T X_c (which squares condition numbers) and scaling efficiently when d≫nd \gg n.
  • 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 kk (e.g., retaining 95% cumulative variance). Remember to fit StandardScaler and PCA on training data only before transforming test sets.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.