Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Principal Component Analysis, Part 2

From mathematical foundations to practical implementation


Principal Component Analysis (PCA) is a fundamental dimensionality reduction technique that identifies an optimal rr-dimensional subspace capturing the maximum variance in the data. Its mathematical foundation rests on finding orthogonal directions — called principal components — that sequentially maximize the projected variance.

Given a centered data matrix X\mathbf{X}, we seek unit vectors u\mathbf{u} that maximize the variance of projected data Xu\mathbf{X}\mathbf{u}:

max⁡∥u∥=1Var(Xu)\max_{\|\mathbf{u}\|=1} \text{Var}(\mathbf{X}\mathbf{u})

This optimization leads to the key eigenvalue problem:

Cu=λu\mathbf{C}\mathbf{u} = \lambda\mathbf{u}

where C\mathbf{C} is a covariance matrix.

In the following sections, we will systematically derive the solution to this problem and demonstrate its geometric interpretation.


Source
<Figure size 1200x800 with 1 Axes>

Linear Algebra Foundations

Data Matrix Representation

A data matrix X\mathbf{X} with nn rows (samples) and dd columns (features) can be written as:

X=[x11x12⋯x1dx21x22⋯x2d⋮⋮⋱⋮xn1xn2⋯xnd]\mathbf{X} = \begin{bmatrix} x_{11} & x_{12} & \cdots & x_{1d}\\ x_{21} & x_{22} & \cdots & x_{2d}\\ \vdots & \vdots & \ddots & \vdots\\ x_{n1} & x_{n2} & \cdots & x_{nd} \end{bmatrix}

Each row xi=(xi1,xi2,…,xid)T\mathbf{x}_i = (x_{i1}, x_{i2}, \ldots, x_{id})^T represents one sample in dd-dimensional space.

Source

Vector Operations

Dot Product
aTb=∑i=1maibi\mathbf{a}^T\mathbf{b} = \sum_{i=1}^m a_i b_i
Vector Length (Norm)
∥a∥=aTa=∑i=1mai2\|\mathbf{a}\| = \sqrt{\mathbf{a}^T\mathbf{a}} = \sqrt{\sum_{i=1}^m a_i^2}
Unit Vector
u=a∥a∥\mathbf{u} = \frac{\mathbf{a}}{\|\mathbf{a}\|}
Distance between Vectors
∥a−b∥=∑i=1m(ai−bi)2\|\mathbf{a} - \mathbf{b}\| = \sqrt{\sum_{i=1}^m (a_i-b_i)^2}
Angle between Vectors
cos⁡θ=aTb∥a∥∥b∥\cos \theta = \frac{\mathbf{a}^T\mathbf{b}}{\|\mathbf{a}\|\|\mathbf{b}\|}
Dot product: 11
Norm of a: 5.00
Norm of b: 2.24
Angle between vectors: 10.30 degrees

Vector Projections (Derivation & Geometric Intuition)

Derivation of Projection Formula

We begin with fundamental vector operations to derive the projection formula naturally:

  1. Dot Product and Angle Relationship:
    From our previous definitions, we know:

    aTb=∥a∥∥b∥cos⁡θ\mathbf{a}^T \mathbf{b} = \|\mathbf{a}\| \|\mathbf{b}\| \cos \theta

    This measures alignment between vectors.

  2. Scalar Projection (Length of Shadow):
    The length of b\mathbf{b}'s shadow along a\mathbf{a} is:

    Scalar projection=∥b∥cos⁡θ=aTb∥a∥\text{Scalar projection} = \|\mathbf{b}\| \cos \theta = \frac{\mathbf{a}^T \mathbf{b}}{\|\mathbf{a}\|}

    For unit vectors, this simplifies to aTb\mathbf{a}^T \mathbf{b}.

  3. Vector Projection:
    To get the vector form, we multiply the scalar projection by a\mathbf{a}'s unit vector:

    b∥=(aTb∥a∥)(a∥a∥)=aTb∥a∥2a\mathbf{b}_{\parallel} = \left( \frac{\mathbf{a}^T \mathbf{b}}{\|\mathbf{a}\|} \right) \left( \frac{\mathbf{a}}{\|\mathbf{a}\|} \right) = \frac{\mathbf{a}^T \mathbf{b}}{\|\mathbf{a}\|^2} \mathbf{a}
Final Projection Formula
b∥=(aTb∥a∥2)a\mathbf{b}_{\parallel} = \left( \frac{\mathbf{a}^T \mathbf{b}}{\|\mathbf{a}\|^2} \right) \mathbf{a}

Key Insights:

  1. Dot Product Interpretation:

    • The numerator aTb\mathbf{a}^T \mathbf{b} measures alignment

    • The denominator ∥a∥2\|\mathbf{a}\|^2 normalizes for vector length

  2. Special Case - Unit Vector: When ∥a∥=1\|\mathbf{a}\|=1:

    b∥=(aTb)a\mathbf{b}_{\parallel} = (\mathbf{a}^T \mathbf{b}) \mathbf{a}
  3. Geometric Meaning:

    • b∥\mathbf{b}_{\parallel} is b\mathbf{b}'s shadow on a\mathbf{a}

    • The residual b⊥=b−b∥\mathbf{b}_{\perp} = \mathbf{b} - \mathbf{b}_{\parallel} is orthogonal to a\mathbf{a}

Example

Let a=[10]\mathbf{a} = \begin{bmatrix} 1 \\ 0 \end{bmatrix} and b=[32]\mathbf{b} = \begin{bmatrix} 3 \\ 2 \end{bmatrix}.

  • Step 1: Compute aTb=1×3+0×2=3\mathbf{a}^T \mathbf{b} = 1 \times 3 + 0 \times 2 = 3.

  • Step 2: Compute ∥a∥2=12+02=1\|\mathbf{a}\|^2 = 1^2 + 0^2 = 1.

  • Step 3: Projection b∥=3[10]=[30]\mathbf{b}_{\parallel} = 3\begin{bmatrix} 1 \\ 0 \end{bmatrix} = \begin{bmatrix} 3 \\ 0 \end{bmatrix}.

  • Perpendicular Component: b⊥=[32]−[30]=[02]\mathbf{b}_{\perp} = \begin{bmatrix} 3 \\ 2 \end{bmatrix} - \begin{bmatrix} 3 \\ 0 \end{bmatrix} = \begin{bmatrix} 0 \\ 2 \end{bmatrix}.

Interpretation:
Since a\mathbf{a} points along the x-axis, b∥\mathbf{b}_{\parallel} retains only the x-component of b\mathbf{b}, and b⊥\mathbf{b}_{\perp} captures the remaining y-component, which is orthogonal to a\mathbf{a}.


Connection to PCA:
This projection concept is the geometric heart of PCA. In the next section we extend it to multiple dimensions, leading to the PCA solution via eigenvalue decomposition.


Original vector b: [3 2]
Projection onto a: [3. 0.]
Perpendicular component: [0. 2.]
Verification (should equal b): [3. 2.]
Source
<Figure size 1000x500 with 1 Axes>
Vector a: [1 0], magnitude: 1.00
Vector b: [3 2], magnitude: 3.61
b_parallel: [3. 0.], magnitude: 3.00
b_perpendicular: [0. 2.], magnitude: 2.00

Basis Transformation

Change of Basis

Any vector x\mathbf{x} can be expressed in terms of a new orthonormal basis {u1,u2,…,ud}\{\mathbf{u}_1, \mathbf{u}_2, \ldots, \mathbf{u}_d\}:

x=a1u1+a2u2+⋯+adud=Ua\mathbf{x} = a_1\mathbf{u}_1 + a_2\mathbf{u}_2 + \cdots + a_d\mathbf{u}_d = \mathbf{U}\mathbf{a}

where U=[u1∣u2∣⋯∣ud]\mathbf{U} = [\mathbf{u}_1 \mid \mathbf{u}_2 \mid \cdots \mid \mathbf{u}_d] has the new basis vectors as its columns, and a\mathbf{a} holds the coordinates of x\mathbf{x} in the new basis:

a=UTx\mathbf{a} = \mathbf{U}^T\mathbf{x}

This works because orthonormality gives UTU=I\mathbf{U}^T\mathbf{U} = \mathbf{I}, so the coordinate in direction ui\mathbf{u}_i is simply the dot product ai=uiTxa_i = \mathbf{u}_i^T \mathbf{x}.

Original vector x: [0.5 1.  2. ]
In standard basis: 0.5i + 1.0j + 2.0k
[[ 0.70710678 -0.70710678  0.        ]
 [ 0.70710678  0.70710678  0.        ]
 [ 0.          0.          1.        ]]
Source
<Figure size 1500x500 with 2 Axes>

Rotation Matrix Mathematical Foundation

2D Rotation Fundamentals

A rotation matrix transforms vectors by rotating them through a specified angle θ while preserving their length. For a 45° rotation in the xy-plane (θ = π/4 radians), the fundamental rotation matrix is:

R(θ)=[cos⁡θ−sin⁡θ0sin⁡θcos⁡θ0001]\mathbf{R}(\theta) = \begin{bmatrix} \cos\theta & -\sin\theta & 0 \\ \sin\theta & \cos\theta & 0 \\ 0 & 0 & 1 \end{bmatrix}

For θ = 45°:

cos⁡(45°)=sin⁡(45°)=12≈0.7071\cos(45°) = \sin(45°) = \frac{1}{\sqrt{2}} \approx 0.7071

Thus, the 45° rotation matrix becomes:

R45°=[12−12012120001]\mathbf{R}_{45°} = \begin{bmatrix} \frac{1}{\sqrt{2}} & -\frac{1}{\sqrt{2}} & 0 \\ \frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}} & 0 \\ 0 & 0 & 1 \end{bmatrix}
Basis Transformation

In the previous code, this rotation matrix defines new basis vectors:

u1 = np.array([1/np.sqrt(2), 1/np.sqrt(2), 0])  # Rotated x-axis
u2 = np.array([-1/np.sqrt(2), 1/np.sqrt(2), 0]) # Rotated y-axis 
u3 = np.array([0, 0, 1])                        # Unchanged z-axis

These form an orthonormal basis:

  1. u1\mathbf{u}_1: Original x-axis rotated 45° counterclockwise

  2. u2\mathbf{u}_2: Original y-axis rotated 45° counterclockwise

  3. u3\mathbf{u}_3: Original z-axis (unchanged)

Key Properties
  1. Orthonormality:

    • uiTuj={1if i=j0otherwise\mathbf{u}_i^T\mathbf{u}_j = \begin{cases} 1 & \text{if } i=j \\ 0 & \text{otherwise} \end{cases}

  2. Determinant: det⁡(R)=1\det(\mathbf{R}) = 1 (preserves orientation)

  3. Inverse: R−1=RT\mathbf{R}^{-1} = \mathbf{R}^T (transpose reverses rotation)

Vector Transformation

For any vector x=[x,y,z]T\mathbf{x} = [x,y,z]^T, the rotated version is:

x′=Rx=[x−y2x+y2z]\mathbf{x}' = \mathbf{R}\mathbf{x} = \begin{bmatrix} \frac{x - y}{\sqrt{2}} \\ \frac{x + y}{\sqrt{2}} \\ z \end{bmatrix}

This matches our basis transformation approach where:

x′=xu1+yu2+zu3\mathbf{x}' = x\mathbf{u}_1 + y\mathbf{u}_2 + z\mathbf{u}_3
Why This Works

The columns of R\mathbf{R} are exactly the images of the standard basis vectors under the rotation. When we multiply:

R[100]=u1,R[010]=u2,R[001]=u3\mathbf{R}\begin{bmatrix}1\\0\\0\end{bmatrix} = \mathbf{u}_1, \quad \mathbf{R}\begin{bmatrix}0\\1\\0\end{bmatrix} = \mathbf{u}_2, \quad \mathbf{R}\begin{bmatrix}0\\0\\1\end{bmatrix} = \mathbf{u}_3

So R\mathbf{R} tells us precisely where each axis goes — which is why its columns form the new basis.


In new basis: 1.06u1 + 0.35u2 + 2.00u3

Reconstructed x: [0.5 1.  2. ]
Reconstruction error: 0.0000000000

PCA Mathematical Foundation

Variance Maximization Problem

PCA seeks an orthonormal basis {u1,…,ur}\{\mathbf{u}_1, \dots, \mathbf{u}_r\} that captures maximal variance in the data through sequential optimization:

  1. First Principal Component:
    Find unit vector u1\mathbf{u}_1 maximizing projected variance:

    max⁡∥u1∥=1Var(Xu1)\max_{\|\mathbf{u}_1\|=1} \text{Var}(\mathbf{X}\mathbf{u}_1)
  2. Subsequent Components:
    Each uk\mathbf{u}_k is found by maximizing variance orthogonal to previous components:

    max⁡∥uk∥=1, uk⊥{u1,…,uk−1}Var(Xuk)\max_{\|\mathbf{u}_k\|=1, \, \mathbf{u}_k \perp \{\mathbf{u}_1, \dots, \mathbf{u}_{k-1}\}} \text{Var}(\mathbf{X}\mathbf{u}_k)

In short, the first principal component is the direction of greatest spread in the data. Each subsequent component must be orthogonal to all previous ones, ensuring it captures genuinely new, independent information.

Finding the first principal component

We seek a unit vector u\mathbf{u} that maximizes the variance of the projected data:

max⁡∥u∥=1Var(Xu)=max⁡∥u∥=11n∑i=1n(uTxi−μu)2\max_{\|\mathbf{u}\|=1} \text{Var}(\mathbf{X}\mathbf{u}) = \max_{\|\mathbf{u}\|=1} \frac{1}{n} \sum_{i=1}^n \left( \mathbf{u}^T \mathbf{x}_i - \mu_{\mathbf{u}} \right)^2

where μu=1n∑i=1nuTxi=uTxˉ\mu_{\mathbf{u}} = \frac{1}{n} \sum_{i=1}^n \mathbf{u}^T \mathbf{x}_i = \mathbf{u}^T \bar{\mathbf{x}} is the mean of the projected values (using linearity of the dot product).

Expanding the variance:

  1. Let ai=uTxia_i = \mathbf{u}^T \mathbf{x}_i denote the scalar projection of the ii-th sample.

  2. The variance becomes:

    σu2=1n∑i=1n(ai−μu)2=1n∑i=1n(uTxi−uTxˉ)2=1n∑i=1n[uT(xi−xˉ)]2\sigma^2_{\mathbf{u}} = \frac{1}{n} \sum_{i=1}^n (a_i - \mu_{\mathbf{u}})^2 = \frac{1}{n} \sum_{i=1}^n \left( \mathbf{u}^T \mathbf{x}_i - \mathbf{u}^T \bar{\mathbf{x}} \right)^2 = \frac{1}{n} \sum_{i=1}^n \left[ \mathbf{u}^T (\mathbf{x}_i - \bar{\mathbf{x}}) \right]^2

Let zi=xi−xˉ\mathbf{z}_i = \mathbf{x}_i - \bar{\mathbf{x}} denote the centered data points. Expanding step by step:

  1. Use the identity (ATB)T=BTA(A^TB)^T = B^TA, noting that (uTzi)2=(uTzi)(ziTu)(\mathbf{u}^T \mathbf{z}_i)^2 = (\mathbf{u}^T \mathbf{z}_i)(\mathbf{z}_i^T \mathbf{u}):

σu2=1n∑i=1n(uTzi)2=1n∑i=1n(uTzi)(ziTu)\sigma^2_{\mathbf{u}} = \frac{1}{n} \sum_{i=1}^n (\mathbf{u}^T \mathbf{z}_i)^2 = \frac{1}{n} \sum_{i=1}^n (\mathbf{u}^T \mathbf{z}_i)(\mathbf{z}_i^T \mathbf{u})
  1. Rearrange, grouping ziziT\mathbf{z}_i\mathbf{z}_i^T between uT\mathbf{u}^T and u\mathbf{u}:

=1n∑i=1nuTziziTu= \frac{1}{n} \sum_{i=1}^n \mathbf{u}^T \mathbf{z}_i \mathbf{z}_i^T \mathbf{u}
  1. Pull uT\mathbf{u}^T and u\mathbf{u} outside the sum:

=uT(1n∑i=1nziziT)u= \mathbf{u}^T \left( \frac{1}{n} \sum_{i=1}^n \mathbf{z}_i \mathbf{z}_i^T \right) \mathbf{u}
  1. Recognize the sample covariance matrix C=1n∑i=1nziziT\mathbf{C} = \frac{1}{n} \sum_{i=1}^n \mathbf{z}_i \mathbf{z}_i^T:

=uTCu= \mathbf{u}^T \mathbf{C} \mathbf{u}
  1. Equivalently, using the centered data matrix Z=[z1⋯zn]T∈Rn×d\mathbf{Z} = [\mathbf{z}_1 \cdots \mathbf{z}_n]^T \in \mathbb{R}^{n \times d}:

=1nuTZTZu=1n∥Zu∥2= \frac{1}{n} \mathbf{u}^T \mathbf{Z}^T \mathbf{Z} \mathbf{u} = \frac{1}{n} \|\mathbf{Z}\mathbf{u}\|^2

Hence the variance of the projected data is:

σu2=uTCu\boxed{\sigma^2_{\mathbf{u}} = \mathbf{u}^T \mathbf{C} \mathbf{u}}
Constrained Optimization via Lagrange Multipliers

We maximize the projected variance σu2=uTCu\sigma^2_\mathbf{u} = \mathbf{u}^T \mathbf{C} \mathbf{u} subject to ∥u∥=1\|\mathbf{u}\|=1. Introducing Lagrange multiplier λ\lambda, the Lagrangian is:

max⁡uJ(u)=uTCu−λ(uTu−1)\max_\mathbf{u} J(\mathbf{u}) = \mathbf{u}^T \mathbf{C} \mathbf{u} - \lambda (\mathbf{u}^T\mathbf{u}-1)
Solution

Setting the gradient with respect to u\mathbf{u} to zero:

∂∂u(uTCu−λ(uTu−1))=0\frac{\partial}{\partial \mathbf{u}} \left(\mathbf{u}^T \mathbf{C} \mathbf{u} - \lambda (\mathbf{u}^T\mathbf{u}-1)\right) = \mathbf{0}
2Cu−2λu=02 \mathbf{C} \mathbf{u} - 2 \lambda \mathbf{u} = \mathbf{0}
Cu=λu\mathbf{C} \mathbf{u} = \lambda \mathbf{u}

This is precisely the eigenvalue equation: u\mathbf{u} must be an eigenvector of the covariance matrix C\mathbf{C}, with λ\lambda the corresponding eigenvalue.

Choosing the Right Eigenvalue

Substituting Cu=λu\mathbf{C}\mathbf{u} = \lambda\mathbf{u} back into the variance expression:

σu2=uTCu=uTλu=λuTu=λ\sigma^2_\mathbf{u} = \mathbf{u}^T\mathbf{C}\mathbf{u} = \mathbf{u}^T \lambda \mathbf{u} = \lambda \mathbf{u}^T\mathbf{u} = \lambda

The projected variance equals the eigenvalue λ\lambda. To maximize variance we therefore pick λ1\lambda_1, the largest eigenvalue of C\mathbf{C}. The corresponding eigenvector u1\mathbf{u}_1 defines the direction of maximum variance — the first principal component.

Source
u1 = [-0.83818843 -0.54538075], λ1 = 1.03
Source
<Figure size 800x600 with 1 Axes>

PCA Algorithm

Given a data matrix X∈Rn×d\mathbf{X} \in \mathbb{R}^{n \times d}:

  1. Center the data: Z=X−1⋅μT\mathbf{Z} = \mathbf{X} - \mathbf{1}\cdot\mathbf{\mu}^T

  2. Compute the covariance matrix: C=1nZTZ\mathbf{C} = \frac{1}{n}\mathbf{Z}^T\mathbf{Z}

  3. Compute eigenvalues and eigenvectors of C\mathbf{C}

  4. Sort eigenvalues in descending order

  5. Select the top rr eigenvectors as the principal components

  6. Project the data: Z′=ZUr\mathbf{Z}' = \mathbf{Z}\mathbf{U}_r

PCA Workflow: From Single Sample to Full Matrix

Projection & Reconstruction (Single Data Point)

Step 1: Mean-Centering

  • Given a raw data vector: x=[x1,x2,…,xd]T(original space) \mathbf{x} = [x_1, x_2, \dots, x_d]^T \quad \text{(original space)}

  • Subtract the mean vector: z=x−μ(centered) \mathbf{z} = \mathbf{x} - \mathbf{\mu} \quad \text{(centered)}

    where μ\mathbf{\mu} is the mean of all samples.

Step 2: Projection (Dimensionality Reduction)

  • Project z\mathbf{z} onto the first rr principal components (PCs) u1,…,ur\mathbf{u}_1, \dots, \mathbf{u}_r: ai=uiTza_i = \mathbf{u}_i^T \mathbf{z} (scalar, projection of z\mathbf{z} onto ui\mathbf{u}_i)

  • The reduced representation (in PCA space) is: a=[a1,a2,…,ar]T\mathbf{a} = [a_1, a_2, \dots, a_r]^T

Step 3: Reconstruction (Approximation)

  • Reconstruct the centered data using the PCs: z′=∑i=1raiui=a1u1+a2u2+⋯+arur \mathbf{z}' = \sum_{i=1}^r a_i \mathbf{u}_i = a_1 \mathbf{u}_1 + a_2 \mathbf{u}_2 + \dots + a_r \mathbf{u}_r

  • Add back the mean to return to original space: xrecon=z′+μ \mathbf{x}_{\text{recon}} = \mathbf{z}' + \mathbf{\mu}

Geometric Interpretation

  • The reconstruction z′\mathbf{z}' is the closest approximation of z\mathbf{z} using only rr directions.

  • The error ∥z−z′∥\|\mathbf{z} - \mathbf{z}'\| comes from discarding the remaining PCs.


Generalization to Full Data Matrix

Step 1: Mean-Centering (Matrix Form)

  • Original data matrix:

    X=[x1∣x2∣…∣xn]T(n×d)\mathbf{X} = [\mathbf{x}_1 | \mathbf{x}_2 | \dots | \mathbf{x}_n]^T \quad \text{($n \times d$)}
  • Mean-centered data:

    Z=X−1μT\mathbf{Z} = \mathbf{X} - \mathbf{1} \mathbf{\mu}^T

    where 1\mathbf{1} is a column vector of ones.

Step 2: Projection (PCA Transformation)

  • Project all samples onto the first rr PCs (Ur=[u1∣…∣ur]\mathbf{U}_r = [\mathbf{u}_1 | \dots | \mathbf{u}_r]):

    A=ZUr(n×r matrix of PCA coordinates)\mathbf{A} = \mathbf{Z} \mathbf{U}_r \quad \text{($n \times r$ matrix of PCA coordinates)}
    • Each row of A\mathbf{A} contains the reduced representation of a sample.

Step 3: Reconstruction (Matrix Form)

  • Reconstruct the centered data:

    Z′=AUrT=∑i=1raiuiT\mathbf{Z}' = \mathbf{A} \mathbf{U}_r^T = \sum_{i=1}^r \mathbf{a}_i \mathbf{u}_i^T
    • ai\mathbf{a}_i = ii-th column of A\mathbf{A} (scores for PC ii).

    • Each term aiuiT\mathbf{a}_i \mathbf{u}_i^T is a rank-1 matrix.

  • Return to original space:

    Xrecon=Z′+1μT\mathbf{X}_{\text{recon}} = \mathbf{Z}' + \mathbf{1} \mathbf{\mu}^T

Connection to Python Implementation

Projection (Dimensionality Reduction)

X_transformed = Z @ U_r  # ≡ Z U_r (n × r matrix)

Reconstruction

Z_recon = X_transformed @ U_r.T  # ≡ A U_r^T (n × d)
X_recon = Z_recon + mean        # Add back mean

Key Takeaways

  1. Single Sample →\rightarrow Full Matrix:

    • Start with a single vector to understand projection/reconstruction.

    • Generalize to the full dataset using matrix operations.

  2. Lossy Compression:

    • Keeping only r<dr < d PCs means the reconstruction is approximate.

    • The error depends on the discarded eigenvalues.

  3. PCA as a Rotation:

    • Projection = Rotate data to align with maximum variance directions.

    • Reconstruction = Rotate back, using only the most important directions.

Equivalence of PCA’s Two Optimization Perspectives and Error Analysis (Further Reading)

PCA can be derived from two equivalent perspectives:

  1. Variance Maximization: Find directions that maximize projected variance.

  2. Reconstruction Error Minimization: Find directions that minimize the mean squared reconstruction error.

We’ll prove their equivalence mathematically and analyze the error.


1. Variance Maximization Formulation

Goal: Find unit vector u \mathbf{u} that maximizes the variance of projected data:

max⁡u1n∑j=1n(uTzj)2subject to∥u∥=1.\max_{\mathbf{u}} \frac{1}{n} \sum_{j=1}^n (\mathbf{u}^T \mathbf{z}_j)^2 \quad \text{subject to} \quad \|\mathbf{u}\| = 1.
  • The solution is the eigenvector of ZTZ \mathbf{Z}^T \mathbf{Z} with largest eigenvalue.


2. Reconstruction Error Minimization

Goal: Find u \mathbf{u} that minimizes the MSE between original data zj \mathbf{z}_j and its reconstruction zj′=(uTzj)u \mathbf{z}_j' = (\mathbf{u}^T \mathbf{z}_j)\mathbf{u} :

min⁡u1n∑j=1n∥zj−(uTzj)u∥2subject to∥u∥=1.\min_{\mathbf{u}} \frac{1}{n} \sum_{j=1}^n \|\mathbf{z}_j - (\mathbf{u}^T \mathbf{z}_j)\mathbf{u}\|^2 \quad \text{subject to} \quad \|\mathbf{u}\| = 1.

3. Proof of Equivalence

Expand the reconstruction error:

∥zj−(uTzj)u∥2=∥zj∥2−(uTzj)2.\|\mathbf{z}_j - (\mathbf{u}^T \mathbf{z}_j)\mathbf{u}\|^2 = \|\mathbf{z}_j\|^2 - (\mathbf{u}^T \mathbf{z}_j)^2.

Thus, the MSE becomes:

MSE=1n∑j=1n∥zj∥2−1n∑j=1n(uTzj)2.\text{MSE} = \frac{1}{n} \sum_{j=1}^n \|\mathbf{z}_j\|^2 - \frac{1}{n} \sum_{j=1}^n (\mathbf{u}^T \mathbf{z}_j)^2.

Key Observations:

  1. The term 1n∑∥zj∥2 \frac{1}{n} \sum \|\mathbf{z}_j\|^2 is constant (total variance in data).

  2. Minimizing MSE is equivalent to maximizing 1n∑(uTzj)2 \frac{1}{n} \sum (\mathbf{u}^T \mathbf{z}_j)^2 (projected variance).


4. Error Analysis in PCA

Projection and Residual Components

For a data point zj \mathbf{z}_j (centered) and its reconstruction zj′ \mathbf{z}_j' using r r PCs:

zj=∑i=1r(uiTzj)ui⏟Reconstruction zj′+∑i=r+1d(uiTzj)ui⏟Error ϵj\mathbf{z}_j = \underbrace{\sum_{i=1}^r (\mathbf{u}_i^T \mathbf{z}_j)\mathbf{u}_i}_{\text{Reconstruction } \mathbf{z}_j'} + \underbrace{\sum_{i=r+1}^d (\mathbf{u}_i^T \mathbf{z}_j)\mathbf{u}_i}_{\text{Error } \mathbf{\epsilon}_j}
  • Error vector: ϵj=zj−zj′=∑i=r+1d(uiTzj)ui \mathbf{\epsilon}_j = \mathbf{z}_j - \mathbf{z}_j' = \sum_{i=r+1}^d (\mathbf{u}_i^T \mathbf{z}_j)\mathbf{u}_i .


Mean Squared Error (MSE) Derivation

The total MSE across all samples is:

MSE=1n∑j=1n∥ϵj∥2=1n∑j=1n∥∑i=r+1d(uiTzj)ui∥2.\text{MSE} = \frac{1}{n} \sum_{j=1}^n \|\mathbf{\epsilon}_j\|^2 = \frac{1}{n} \sum_{j=1}^n \left\| \sum_{i=r+1}^d (\mathbf{u}_i^T \mathbf{z}_j)\mathbf{u}_i \right\|^2.
∥ϵj∥2=∑i=r+1d(uiTzj)2∥ui∥2⏟=1=∑i=r+1d(uiTzj)2\|\mathbf{\epsilon}_j\|^2 = \sum_{i=r+1}^d (\mathbf{u}_i^T \mathbf{z}_j)^2 \underbrace{\|\mathbf{u}_i\|^2}_{=1} = \sum_{i=r+1}^d (\mathbf{u}_i^T \mathbf{z}_j)^2
MSE=1n∑j=1n∑i=r+1d(uiTzj)2=∑i=r+1d(1n∑j=1n(uiTzj)2).\text{MSE} = \frac{1}{n} \sum_{j=1}^n \sum_{i=r+1}^d (\mathbf{u}_i^T \mathbf{z}_j)^2 = \sum_{i=r+1}^d \left( \frac{1}{n} \sum_{j=1}^n (\mathbf{u}_i^T \mathbf{z}_j)^2 \right).

By definition, the variance along ui \mathbf{u}_i is:

λi=1n∑j=1n(uiTzj)2.\lambda_i = \frac{1}{n} \sum_{j=1}^n (\mathbf{u}_i^T \mathbf{z}_j)^2.

Thus:

MSE=∑i=r+1dλi.\text{MSE} = \sum_{i=r+1}^d \lambda_i.

5. Conclusion and Summary

  • Dual Formulations: Variance maximization and error minimization are equivalent in PCA.

  • Eigenvalue Interpretation: The MSE equals the sum of discarded eigenvalues because:

    • Each λi \lambda_i represents variance along PC ui \mathbf{u}_i .

    • Discarding PCs r+1 r+1 to d d loses exactly ∑i=r+1dλi \sum_{i=r+1}^d \lambda_i variance.

  • Optimality: PCA’s solution simultaneously maximizes preserved variance and minimizes reconstruction error.

Key Relationships:

ConceptFormulaInterpretation
Projectionzj′=∑i=1r(uiTzj)ui \mathbf{z}_j' = \sum_{i=1}^r (\mathbf{u}_i^T \mathbf{z}_j)\mathbf{u}_i Reconstruction using top r r PCs
Errorϵj=∑i=r+1d(uiTzj)ui \mathbf{\epsilon}_j = \sum_{i=r+1}^d (\mathbf{u}_i^T \mathbf{z}_j)\mathbf{u}_i Residual from discarded PCs
MSEMSE=∑i=r+1dλi \text{MSE} = \sum_{i=r+1}^d \lambda_i Sum of variances of discarded PCs

Examples and Applications

Iris Dataset Example

Source
Original data shape: (150, 4)
Features: ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']

Explained variance ratio:
PC1: 0.925 (92.5%)
PC2: 0.053 (5.3%)
Total: 0.978 (97.8%)
Source
<Figure size 1500x500 with 5 Axes>

Reconstruction Error Analysis

Source
<Figure size 1000x600 with 1 Axes>
Reconstruction errors:
1 components: MSE = 0.085604
2 components: MSE = 0.025341
3 components: MSE = 0.005919
4 components: MSE = 0.000000

High-Dimensional Data Example

Source
Generated data shape: (200, 50)
True intrinsic dimensionality: 3

Explained variance by first 10 components:
PC1: 0.420 (cumulative: 0.420)
PC2: 0.342 (cumulative: 0.763)
PC3: 0.234 (cumulative: 0.997)
PC4: 0.000 (cumulative: 0.997)
PC5: 0.000 (cumulative: 0.997)
PC6: 0.000 (cumulative: 0.997)
PC7: 0.000 (cumulative: 0.997)
PC8: 0.000 (cumulative: 0.998)
PC9: 0.000 (cumulative: 0.998)
PC10: 0.000 (cumulative: 0.998)
Source
<Figure size 1200x500 with 2 Axes>

Number of components needed for 95% variance: 3
This is close to the true intrinsic dimensionality of 3

Comparison with Scikit-learn

Source
Comparison of implementations:
Our explained variance ratio: [0.92461872 0.05306648]
Sklearn explained variance ratio: [0.92461872 0.05306648]

Mean absolute difference in transformed data: 0.0000000000
<Figure size 1200x500 with 2 Axes>

Some of my previous papers are about PCA, including Amintoosi & Farbiz (2022)Fathy et al. (2008)Amintoosi et al. (2007)Amintoosi & Poursadeghi (1394)

Summary

This tutorial covered:

  1. Linear Algebra Foundations: Vector operations, norms, and angles

  2. Vector Projections: Mathematical foundation for dimensionality reduction

  3. Basis Transformation: How to represent data in different coordinate systems

  4. PCA Theory: Variance maximization and eigenvalue decomposition

  5. Implementation: Step-by-step PCA algorithm from scratch

  6. Applications: Real examples with Iris dataset and high-dimensional data

Key Takeaways:

  • PCA finds directions of maximum variance in the data

  • Principal components are eigenvectors of the covariance matrix

  • The eigenvalues represent the amount of variance captured by each component

  • PCA provides optimal linear dimensionality reduction in terms of reconstruction error

  • The number of components can be chosen based on desired explained variance threshold

References
  1. Amintoosi, M., & Farbiz, F. (2022). Eigenbackground Revisited: Can We Model the Background with Eigenvectors? Journal of Mathematical Imaging and Vision, 64(5), 463–477.
  2. Fathy, M., Mozayani, N., & Amintoosi, M. (2008). Outlier Removal for Super-Resolution Problem Using QR-Decomposition. Proceedings of the International Conference on Image Processing, Computer Vision, and Pattern Recognition, 271–277. http://webpages.iust.ac.ir/mamintoosi/papers/IPCV08.pdf
  3. Amintoosi, M., Farbiz, F., & Fathy, M. (2007). A QR Decomposition Based Mixture Model Algorithm for Background Modeling. ICICS2007, Sixth International Conference on Information, Communication and Signal Processing, 1–5.
  4. Amintoosi, M., & Poursadeghi, S. (1394, February). Increasing the Speed of Video Background Subtraction by Incremental QR Decomposition. 8th National Seminar on Linear Algebra and Its Applications.