PCA and ICA (Unsupervised Learning)¶
Learning Objectives¶
By the end of this lecture, you should be able to:
- Understand the mathematical foundations of PCA through eigenvectors and covariance
- Implement PCA from scratch and interpret the principal components
- Choose the appropriate number of components for dimensionality reduction
- Recognize when PCA is appropriate and understand its limitations
- Apply PCA to real-world datasets
Motivation: Why Do We Need PCA?¶
Real-world problem: Consider analyzing gene expression data with 20,000 genes measured across only 100 patients.
Challenges:
- Most dimensions are redundant—genes often work in coordinated groups
- Visualization is impossible in 20,000 dimensions
- Models overfit with more features than samples
- Computation becomes intractable
PCA helps us:
- Find the "true" underlying patterns in high-dimensional data
- Reduce dimensionality while preserving the most important information
- Enable visualization and interpretation
- Improve model performance by removing noise
Recap: Linear Algebra Basics¶
Matrix multiplication is not commutative: $$\left[\begin{array}{cc} 0 & 1 \\ 0 & 0 \end{array}\right] \left[\begin{array}{cc} 0 & 0 \\ 1 & 0 \end{array}\right] = \left[\begin{array}{cc} 1 & 0 \\ 0 & 0 \end{array}\right]$$ $$\neq$$ $$\left[\begin{array}{cc} 0 & 0 \\ 1 & 0 \end{array}\right] \left[\begin{array}{cc} 0 & 1 \\ 0 & 0 \end{array}\right] = \left[\begin{array}{cc} 0 & 0 \\ 0 & 1 \end{array}\right]$$
Inner product between vectors ${\bf x}, {\bf y} \in \mathbb{R}^p$ (as column vectors): $$\langle {\bf x},{\bf y} \rangle = {\bf x}^T {\bf y} = \sum_{i=1}^p x_i y_i$$
Important consequences:
- $\langle {\bf x},{\bf x} \rangle \geq 0$ (always non-negative)
- $\Vert {\bf x} \Vert^2 = \langle {\bf x},{\bf x} \rangle$ (norm squared)
- $\langle {\bf x},{\bf y} \rangle = 0$ if and only if ${\bf x} \perp {\bf y}$ (orthogonal vectors have zero inner product)
- $\langle {\bf x},{\bf y} \rangle = \Vert {\bf x} \Vert \Vert {\bf y} \Vert \cos \theta$, where $\theta$ is the angle between vectors
Geometric interpretation of (4): The projection of ${\bf x}$ onto the direction of ${\bf y}$ is: $$\text{proj}_{\bf y}({\bf x}) = \frac{\langle {\bf x}, {\bf y} \rangle}{\Vert {\bf y} \Vert^2} {\bf y}$$
- If ${\bf y}$ is already normalized ($\Vert {\bf y} \Vert = 1$), this simplifies to $\langle {\bf x}, {\bf y} \rangle \cdot {\bf y}$.
- Notation:
- We will denote ${\bf A}_{i,\cdot}$ as the $i$-th row of matrix ${\bf A}$
- We will denote ${\bf A}_{\cdot,j}$ as the $j$-th column of matrix ${\bf A}$
Orthogonal vectors¶
Consider row vectors ${\bf u}_1,\ldots,{\bf u}_k \in \mathbb{R}^k$
- Vector ${\bf u}_i$ is normalized if $\langle {\bf u}_i, {\bf u}_i \rangle = 1$, also defined as $\Vert {\bf u}_i \Vert = 1$.
- Vectors ${\bf u}_i$ and ${\bf u}_j$ are ortogonal if $\langle {\bf u}_i, {\bf u}_j \rangle = 0$ also defined as ${\bf u}_i \perp {\bf u}_j$.
- Vectors ${\bf u}_i$ and ${\bf u}_j$ are orthonormal if they are both orthogonal and normalized.
- If ${\bf U}$ is a matrix $${\bf U} = \left[ \begin{array}{c} {\bf u}_1 \\ \vdots \\ {\bf u}_k \end{array} \right]$$ then ${\bf U}{\bf U}^T = I$, where $I$ is the identity matrix.
Key property: If ${\bf U} = [{\bf u}_1 \mid {\bf u}_2 \mid \cdots \mid {\bf u}_k]$ is a $p \times k$ matrix whose columns are orthonormal vectors, then: $${\bf U}^T{\bf U} = I_k$$ where $I_k$ is the $k \times k$ identity matrix.
Quick check: Why is ${\bf U}^T{\bf U} = I$ important?
- It means we can easily compute coefficients for representing any vector in this basis
- The inverse (or pseudo-inverse) is simply the transpose: ${\bf U}^{-1} = {\bf U}^T$ (when $k=p$)
- Computations are numerically stable
Orthogonal projections¶
For any ${\bf a} \in \mathbb{R}^k$, $${\bf a} = \sum_{i=1}^k ({\bf a} {\bf u}_i^T) {\bf u}_i$$
This means that ${\bf U}$ is a basis for $\mathbb{R}^k$ (see figure for an example on $\mathbb{R}^2$).
Yes.
Example: Let ${\bf U} = [{\bf u}_1^T; {\bf u}_2^T]$ be an orthonormal basis for $\mathbb{R}^2$. Define:
- ${\bf v}_1 = 2 {\bf u}_1 + {\bf u}_2$
- ${\bf v}_2 = {\bf u}_1 + 2 {\bf u}_2$
The vectors ${\bf v}_1$ and ${\bf v}_2$ are not orthogonal: $$\langle {\bf v}_1, {\bf v}_2 \rangle = 4$$
Exercise: Verify that ${\bf v}_1$ and ${\bf v}_2$ span $\mathbb{R}^2$ by showing they're linearly independent. (Hint: Show that $c_1 {\bf v}_1 + c_2 {\bf v}_2 = 0$ only when $c_1 = c_2 = 0$)
However, ${\bf V} = [{\bf v}_1^T; {\bf v}_2^T]$ still forms a basis for $\mathbb{R}^2$, just not an orthonormal one.
- Working with orthonormal bases is computationally easier.
- But sometimes non-orthogonal bases are more useful.
Eigenvalues and Eigenvectors¶
Let ${\bf A} \in \mathbb{R}^{n \times n}$ be an $n \times n$ matrix and ${\bf v} \in \mathbb{R}^{n}$ be a column vector.
Definition: ${\bf v}$ is called an eigenvector of ${\bf A}$ if: $${\bf A} {\bf v} = \lambda {\bf v}$$ where ${\bf v} \neq \mathbf{0}$ (non-trivial) and $\lambda \in \mathbb{R}$ is called the corresponding eigenvalue.
We generally normalize eigenvectors so that $\Vert {\bf v} \Vert = 1$.
Geometric interpretation: Eigenvectors are special directions that don't change direction under the transformation ${\bf A}$—they only get scaled by the factor $\lambda$. Regular vectors get both rotated and scaled.
Note: For simplicity, we will assume all eigenvalues are real to simplify our exposition. This is guaranteed when ${\bf A}$ is symmetric (like covariance matrices).
Properties of eigenvectors:¶
Special case—Symmetric matrices:
When ${\bf A}$ is symmetric (${\bf A} = {\bf A}^T$):
- All eigenvalues are real
- Eigenvectors corresponding to different eigenvalues are orthogonal
- We can choose ${\bf V}$ to be orthonormal, so ${\bf V}^{-1} = {\bf V}^T$
- This is exactly the case for covariance matrices in PCA as we will see later
Consider:
${\bf A}$ is diagonalizable square matrix (nondefective). Then ${\bf A}$ has $n$ linearly independent eigenvectors ${\bf v}_1,\ldots,{\bf v}_n$.
- Dianognalizable means $A$ can be transformed into a diagonal matrix $D$; i.e., $A = P D P^{-1}$ for some invertible matrix $P$.
Let ${\bf v}_i = \begin{bmatrix} v_{i1} & v_{i2} & \cdots & v_{in} \end{bmatrix}$ be the $i$-th eigenvector and let $${\bf V} = \begin{bmatrix} {\bf v}_1 \\ {\bf v}_2 \\ \vdots \\ {\bf v}_n \end{bmatrix} = \begin{bmatrix} v_{11} & v_{12} & \cdots & v_{1n} \\ v_{21} & v_{22} & \cdots & v_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ v_{n1} & v_{n2} & \cdots & v_{nn} \end{bmatrix}$$ be a matrix where each row vector is an eigenvector, ${\bf V} \in \mathbb{R}^{n \times n}$.
Then ${\bf V} A = \Lambda {\bf V}$, that is: $$\begin{bmatrix} {\bf v}_1 \\ {\bf v}_2 \\ \vdots \\ {\bf v}_n \end{bmatrix} \begin{bmatrix} a_{11} & a_{12} & \cdots & a_{1n} \\ a_{21} & a_{22} & \cdots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{n1} & a_{n2} & \cdots & a_{nn} \end{bmatrix} = \begin{bmatrix} \lambda_1 & 0 & \cdots & 0 \\ 0 & \lambda_2 & \cdots & 0 \\ \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \cdots & \lambda_n \end{bmatrix} \begin{bmatrix} {\bf v}_1 \\ {\bf v}_2 \\ \vdots \\ {\bf v}_n \end{bmatrix},$$ where $$ \Lambda = \left[ \begin{array}{cccc} ~{\bf \lambda}_1 & 0 & \cdots & 0 \\ 0 & \lambda_2 & \cdots & 0 \\ \vdots & \vdots & \cdots & \vdots \\ 0 & 0 & \cdots & \lambda_n \end{array} \right]$$
The above implies $A = {\bf V}^{-1} \Lambda {\bf V} $.
Matrix powers are now easy to compute: $${\bf A}^t = {\bf V}^{-1} \Lambda {\bf V} {\bf A}^{t-1} = {\bf V}^{-1} \Lambda {\bf V} {\bf V}^{-1} \Lambda {\bf V} {\bf A}^{t-2} = {\bf V}^{-1} \Lambda^2 {\bf V} {\bf A}^{t-2} = \cdots = {\bf V}^{-1} \Lambda^t {\bf V}.$$
Matrix inversion is also easy to compute $${\bf A}^{-1} = {\bf V}^{-1} \Lambda^{-1} {\bf V}.$$
The real challenge remains finding ${\bf V}$ and inverting it (${\bf V}^{-1}$).
Positive and Nonnegative Matrices and Vectors¶
We say a matrix or vector is
- positive (or elementwise positive) if all its entries are positive. We will denote ${\bf A} > 0$
- nonnegative (or elementwise nonnegative) if all its entries are nonnegative. We will denote ${\bf A} \geq 0$
A matrix is called regular if for some $k \geq 1$, $ {\bf A}^k > 0$.
(Detour) Covariance¶
- We start defining covariance:
- Measures how two random variables $X$ and $Y$ vary together
- Let ${\bf x}$ be a vector with $n$ elements, where $x_i$ is an independent sample of $p(X)$
- Let ${\bf y}$ be a vector with $n$ elements, where $y_i$ is an independent sample of $p(Y)$
- Let $\bar{\bf x}$ be the empirical average values of ${\bf x}$
- Let $\bar{\bf y}$ be the empirical average values of ${\bf y}$
$$\text{COV}({\bf x},{\bf y}) = \frac{1}{n-1} \sum_{i=1}^n ({\bf x}_i - \bar{\bf x})({\bf y}_i - \bar{\bf y})$$
- Positive if large values of X are linearly associated with large values of Y
- Negative if large values of X are linearly associated with small values of Y
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
# Create Data:
x = np.random.uniform(0,10,(25,))
y = x + np.random.standard_normal((25,))
z = np.column_stack((x,y))
# Scatter Plot
plt.scatter(x,y)
<matplotlib.collections.PathCollection at 0x106327010>
# Compute covariance (as a matrix, variance shows in the diagonal, off-diagonal is the covariance):
np.cov(x,y)
array([[12.40271739, 12.05952134],
[12.05952134, 13.01134297]])
(Detour) Correlation Coefficient¶
- Covariance depends on ranges of X and Y
- Correlation standardizes covariance by dividing through standard deviations
- Let $\hat{\sigma}_{\bf x}$ be the empirical standard deviation of $X$
- Let $\hat{\sigma}_{\bf y}$ be the empirical standard deviation of $Y$
$$\rho({\bf x},{\bf y}) = \frac{\text{COV}({\bf x},{\bf y})}{\hat{\sigma}_{\bf x} \hat{\sigma}_{\bf y}}$$
# Compute correlation (as a matrix, diagonal are ones, off-diagonal is the correlation):
np.corrcoef(x,y)
array([[1. , 0.94931553],
[0.94931553, 1. ]])
Recap: Correlation Matrix¶
- $p \times p$ symmetric matrix of correlations for p random variables
- What values are on the diagonal?
Covariance Matrix ($\Sigma$)¶
The covariance matrix is like the correlation matrix but contains covariances instead of correlations.
Computing the Covariance Matrix¶
Input: Data matrix ${\bf D} \in \mathbb{R}^{n \times p}$ with $n$ samples and $p$ features
- Rows are data points (samples, e.g., individual flowers)
- Columns are features/attributes (e.g., sepal length, sepal width, petal length, petal width)
Step 1: Center the data (make each column have mean 0): $${\bf X}_{i,\cdot} = {\bf D}_{i,\cdot} - \bar{\bf D}$$ where $\bar{\bf D} = \frac{1}{n}\sum_{i=1}^n {\bf D}_{i,\cdot}$ is the mean of each column.
Step 2: Compute the $p \times p$ covariance matrix: $$\Sigma = \frac{1}{n-1} {\bf X}^T {\bf X}$$
- Note: Often we will also scale the data per dimension, therefore using the correlagtion matrix: $X_\text{standardized} = (X - \text{mean}(X)) / \text{std}(X)$ and then $$\Sigma = \frac{1}{n-1} {\bf X}_\text{standardized}^T {\bf X}_\text{standardized}$$.
Interpretation: Each element $$\Sigma_{i,j} = \widehat{\text{Cov}}({\bf X}_{\cdot,i},{\bf X}_{\cdot,j})$$ is the sample covariance between the $i$-th and $j$-th features.
- If standardized, then $$\Sigma_{i,j} = \widehat{\text{Cor}}({\bf X}_{\cdot,i},{\bf X}_{\cdot,j}).$$
Key properties of $\Sigma$:
- Symmetric: $\Sigma = \Sigma^T$
- Positive semidefinite: ${\bf z}^T \Sigma {\bf z} \geq 0$ for all ${\bf z}$
- Diagonal elements are variances: $\Sigma_{i,i} = \widehat{\text{Var}}({\bf X}_{\cdot,i})$
- Off-diagonal elements are covariances
Why center the data? If we don't center, we get $\frac{1}{n-1}{\bf D}^T {\bf D}$, which mixes means and covariances. Centering ensures we only capture covariance structure.
Low Dimensional Projections¶
Goal: We want to identify and describe the "real dimensions" that underlie high-dimensional data.
Benefits:
- Simplification: Reduces the number of variables in modeling
- Visualization: Can plot data in 2D or 3D
- Reduces redundancy: Can identify variables with similar behavior
- Interpretability: Can identify sets of variables with similar behavior
- Noise reduction: Minor dimensions often contain noise
- Computational efficiency: Fewer dimensions = faster algorithms
The idea: Project data from its original high-dimensional space into a lower-dimensional space that captures most of the variation.
Dimensionality reduction methods¶
- Principal component analysis (PCA)
- Linear transformation, minimizes unexplained variance
- Independent Component Analysis (ICA)
- Projects into low-dimensional subspace by finding components that are statistically independent and non-Gaussian
- Manifold methods (t-SNE, UMAP)
- Data point distances only defined between points considered close
- We will see these when we talk about clustering
Principal Component Analysis (PCA)¶
- Developed independently by Karl Pearson (1901) and Harold Hotelling (1933)
- Based on the eigenvector decomposition of the covariance matrix
- One of the most widely used dimensionality reduction techniques
Key Insight: The eigenvectors of the covariance matrix point in directions of maximum (residual) variance in the data.
Principal Component Analysis (PCA)¶
Goal: Find a linear projection that maximizes the variance of the projected data
- Given a $p$-dimensional vector ${\bf x} \in \mathbb{R}^p$, find an orthonormal basis (matrix) ${\bf V} \in \mathbb{R}^{p \times k}$ and a vector ${\bf z} \in \mathbb{R}^k$, $k \leq p$, such that $$ {\bf x} = {\bf V}{\bf z} $$ and ${\bf z}$ has uncorrelated components ${\bf z}_i$.
Model space: set of $k$ orthonormal basis vectors ${\bf V}$
- All basis vectors have norm of 1
- Any pair of basis vectors have dot-product of 0
Finding ${\bf V}$¶
- Compute eigenvectors & eigenvalues of the covariance matrix $\Sigma$:
$$
{\bf V} \Sigma = \Lambda {\bf V}
$$
- Eigenvectors ${\bf V}$ are the principal component vectors, where each is a $k \times 1$ column vector
- Since any two eigenvectors ${\bf v}_i$ and ${\bf v}_j$ are orthogonal, they have 0 covariance, i.e., $\langle {\bf v}_i, {\bf v}_j \rangle = {\bf v}_i^T {\bf v}_j = 0$, $\forall i,j \in \{1,\ldots,k\}, i\neq j$.
E.g., for orthogonal vectors ${\bf v}_1$ and ${\bf v}_2$
- The first eigenvector ${\bf v}_1$ maximizes variance of projected data
- The second eigenvector ${\bf v}_2$ maximizes variance among directions orthogonal to ${\bf v}_1$
- And so on...
scikit-learn:
class sklearn.decomposition.PCA(n_components=None, *, copy=True, whiten=False, svd_solver='auto', tol=0.0, iterated_power='auto', n_oversamples=10, power_iteration_normalizer='auto', random_state=None)[source]
Principal component analysis (PCA).
Linear dimensionality reduction using Singular Value Decomposition of the data to project it to a lower dimensional space. The input data is centered **but not scaled** for each feature before applying the SVD.
Quiz¶
Consider a dataset with customer attributes for bank loan applications, including variables measured on very different scales:
- Income: measured in dollars (e.g., $\$30,000$ to $\$200,000$)
- Age: measured in years (e.g., 25 to 65)
- Credit score: measured in points (e.g., 300 to 850)
Suppose we perform PCA using scikit-learn PCA library, which uses the covariance matrix by centering the data (but not scaling): $$\Sigma = \frac{1}{n-1} \mathbf{X}^T \mathbf{X}$$
rather than the correlation matrix (equivalently, the covariance matrix of standardized data): $$\Sigma = \frac{1}{n-1} \mathbf{X}_\text{standardized}^T \mathbf{X}_\text{standardized}$$
What is the consequence of this choice?
(A) Nothing changes—covariance is scale-invariant by definition, so standardization is unnecessary
(B) The covariance matrix cannot be computed because the features have different units
(C) The eigenvectors will have incorrect signs (positive becomes negative and vice versa)
(D) The first principal component will be dominated by high-variance features like income, potentially obscuring patterns in lower-variance features like age
(E) The covariance matrix will not be symmetric, violating requirements for eigendecomposition
Eigenvalues and Variance (very important)¶
Key relationship: The variance captured by the $i$-th principal component is exactly $\lambda_i$ (the $i$-th largest eigenvalue).
Total variance is preserved: $$\sum_{j=1}^p \hat{\sigma}_j^2 = \sum_{j=1}^p \lambda_j$$
where $\hat{\sigma}_j^2$ is the variance of the $j$-th original feature.
Variance explained by first $k$ components: $$\text{Explained variance ratio} = \frac{\sum_{i=1}^k \lambda_i}{\sum_{j=1}^p \lambda_j}$$
This tells us what fraction of the total variance we capture with the first $k$ components.
Mathematical property: Because $\Sigma$ is positive semidefinite: $${\bf V}^T \Sigma {\bf V} = \Lambda$$
and since $\Sigma$ is symmetric, ${\bf V}$ is orthonormal: ${\bf V}^T {\bf V} = I$.
Computational complexity: $O(np^2 + p^3)$
- $O(np^2)$ to compute $\Sigma = \frac{1}{n-1}{\bf X}^T {\bf X}$
- $O(p^3)$ to compute eigendecomposition
Applying PCA for Dimensionality Reduction¶
Projection Formula¶
Given a new $p$-dimensional vector ${\bf x}' \in \mathbb{R}^p$, we:
Center it: ${\bf x}' \leftarrow {\bf x}' - \bar{\bf x}$ (using the mean from training data)
Project onto first $k$ principal components: $$z_i = {\bf x}'^T {\bf v}_i, \quad i \in \{1,\ldots,k\}$$
Result: Vector ${\bf z} = (z_1, z_2, \ldots, z_k) \in \mathbb{R}^k$
In matrix form: ${\bf z} = {\bf V}_k^T {\bf x}'$
Choosing $k$: How Many Components?¶
This is an important question. There are several approaches:
1. Explained variance threshold: Choose $k$ such that we explain at least (e.g.) 95% of variance: $$\frac{\sum_{i=1}^k \lambda_i}{\sum_{j=1}^p \lambda_j} \geq 0.95$$
2. Scree plot / Elbow method: Plot eigenvalues and look for an "elbow" where eigenvalues drop off sharply (see example below).
3. Kaiser criterion: Keep components with $\lambda_i > 1$ (when features are standardized).
- Rationale: Each standardized feature has variance 1, so we only keep components that explain more variance than a single original feature.
4. Cross-validation: Choose $k$ that maximizes performance on a downstream task.
GPU & CPU Implementation of the PCA Algorithm¶
## First, let's look at the dataset
# Load iris dataset
from sklearn import datasets
iris = datasets.load_iris()
# Copy original data
D = iris.data
# Center the data
X = D - np.mean(D,axis=0)
# Normalize the data
X = X/np.std(X,axis=0)
# Plot feature values of original IRIS data
fig = plt.figure(1, figsize=(9, 6))
ax = fig.add_subplot(111)
bp = ax.boxplot(iris.data)
plt.ylabel('Feature value',size=16)
plt.title('Iris original data',size=18)
labels = ['Sepal length', 'Sepal width', 'Petal length', 'Petal width']
x_pos = [i for i in range(1,len(labels)+1)]
plt.xticks(x_pos, labels, rotation=45,size=16)
#fig.savefig('fig1.png', bbox_inches='tight')
([<matplotlib.axis.XTick at 0x131f30ed0>, <matplotlib.axis.XTick at 0x111e66a50>, <matplotlib.axis.XTick at 0x132120350>, <matplotlib.axis.XTick at 0x131f5da50>], [Text(1, 0, 'Sepal length'), Text(2, 0, 'Sepal width'), Text(3, 0, 'Petal length'), Text(4, 0, 'Petal width')])
# Plot feature values of centered + normalized IRIS data
fig = plt.figure(1, figsize=(9, 6))
ax = fig.add_subplot(111)
bp = ax.boxplot(X)
plt.ylabel('Feature value',size=16)
plt.title('Normalized Iris data',size=18)
labels = ['Sepal length', 'Sepal width', 'Petal length', 'Petal width']
x_pos = [i for i in range(1,len(labels)+1)]
plt.xticks(x_pos, labels, rotation=45,size=16)
#fig.savefig('fig1.png', bbox_inches='tight')
([<matplotlib.axis.XTick at 0x132161d50>, <matplotlib.axis.XTick at 0x13215eb10>, <matplotlib.axis.XTick at 0x13214ff90>, <matplotlib.axis.XTick at 0x1321d1f90>], [Text(1, 0, 'Sepal length'), Text(2, 0, 'Sepal width'), Text(3, 0, 'Petal length'), Text(4, 0, 'Petal width')])
## PCA Implementation using PyTorch for GPU & CPU
# Based on implementation by https://medium.com/@ravikalia/pca-done-from-scratch-with-python-2b5eb2790bfc
# (c) Bruno Ribeiro
# Implemented cuda version and improved overall performance
import torch
def PCA_torch(X,k, device, center=True, scale=False):
# Gets the size of X
n,p = X.size()
# Sends X to the appropriate memory (CPU or GPU) for our computations
# Note that it makes a copy of X
X_new = X.to(device=device,dtype=torch.float32)
print(f'X is in GPU = {X_new.is_cuda}')
if center:
# Mean of each column
mean = X_new.mean(axis=0,keepdim=True)
# Subtract each row in X by the column mean
X_new = X_new - mean
# Computes covariance matrix.
covariance = 1/(n-1) * (X_new.T @ X_new)
if scale:
# If we beed ti scale
scaling = torch.sqrt(1/torch.diag(covariance))
covariance = torch.diag(scaling).view(p,p) @ covariance
eigenvalues, eigenvectors = torch.linalg.eig(covariance)
# Cast complex vectors as real (these eigenvalues & eigenvectors have no imaginary component)
eigenvalues = eigenvalues.real
eigenvectors = eigenvectors.real
components = (eigenvectors[:, :k]).T
explained_variance = eigenvalues[:k]
return {'k':k, 'components':components.cpu(),'explained_variance':explained_variance.cpu()}
Applying PCA¶
Let's apply PCA to reduce the dimensionality of the Iris dataset:
- The Iris dataset represents flowers with 4 attributes: sepal length, sepal width, petal length and petal width.
- The Principal Component Analysis (PCA) applied to this data identifies the combination of attributes (principal components, or directions in the feature space) that account for the most variance in the data.
- The dataset contains 3 kind of flowers (Setosa,Versicolor,Virginica) but we will not use the type of flower in our analysis (we will assume it is hidden from us)
- Here we will plot the different samples on the 2 first principal components.
%matplotlib inline
import matplotlib.pyplot as plt
import torch
iris = datasets.load_iris()
iris_data = torch.from_numpy(iris.data)
n, p = iris_data.size()
# Returns 2 components
k = 4
print(f'p={p}, k={k}')
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
PCA_output = PCA_torch(iris_data, k, device)
# Percentage of variance explained for each components
print(f'Explained variance ratio (first two components): {PCA_output["explained_variance"]}\n\n')
print(f'PCA basis={PCA_output["components"]}')
p=4, k=4
X is in GPU = False
Explained variance ratio (first two components): tensor([4.2282, 0.2427, 0.0782, 0.0238])
PCA basis=tensor([[-0.3614, 0.0845, -0.8567, -0.3583],
[-0.6566, -0.7302, 0.1734, 0.0755],
[-0.5820, 0.5979, 0.0762, 0.5458],
[ 0.3155, -0.3197, -0.4798, 0.7537]])
Let's now project the flowers (originally in 4 dimensions: sepal length, sepal width, petal length and petal width) into two dimension using PCA:
%matplotlib inline
plt.figure()
colors = ['navy', 'turquoise', 'darkorange']
lw = 2
y = iris.target
target_names = iris.target_names
for color, i, target_name in zip(colors, [0, 1, 2], target_names):
# Projects all data for a given color into the two new bases
x_1 = iris_data[y==i,:].float() @ PCA_output["components"][0]
x_2 = iris_data[y==i,:].float() @ PCA_output["components"][1]
# Draw output points
plt.scatter(x_1, x_2, color=color, alpha=.8, lw=lw, label=target_name)
plt.legend(loc='best', shadow=False, scatterpoints=1)
plt.title('PCA of IRIS dataset')
Text(0.5, 1.0, 'PCA of IRIS dataset')
How much do these two dimensions explain the variance in the data?
x = range(0,PCA_output['explained_variance'].shape[0])
y = PCA_output['explained_variance'] #The amount of variance explained by each of the selected components.
plt.bar(x, y)
#plt.xlabel('x axis label')
plt.ylabel('variance',size=16)
plt.title('PCA',size=18)
labels = ['Component 1', 'Component 2', 'Component 3', 'Component 4']
x_pos = [float(i)-0.3 for i in x]
plt.xticks(x_pos, labels, rotation=45,size=16)
([<matplotlib.axis.XTick at 0x14248d410>, <matplotlib.axis.XTick at 0x142494290>, <matplotlib.axis.XTick at 0x14248c490>, <matplotlib.axis.XTick at 0x1424d7510>], [Text(-0.3, 0, 'Component 1'), Text(0.7, 0, 'Component 2'), Text(1.7, 0, 'Component 3'), Text(2.7, 0, 'Component 4')])
(Extra) Independent Component Analysis (ICA)¶
Independent Component Analysis (ICA)
The Blind Source Separation Problem¶
Given a $p$-dimensional vector ${\bf x} \in \mathbb{R}^p$, find:
- A mixing matrix ${\bf H} \in \mathbb{R}^{p\times k}$
- A vector of sources ${\bf s} \in \mathbb{R}^k$
Such that: $${\bf x} = {\bf H} {\bf s}$$
where the components of ${\bf s}$ are:
- Statistically independent (not just uncorrelated)
- Non-Gaussian (this is what allows us to separate them)
ICA vs. PCA¶
| PCA | ICA |
|---|---|
| Finds uncorrelated components | Finds independent components |
| Maximizes variance | Maximizes non-Gaussianity |
| Components are orthogonal | Components need not be orthogonal |
| Based on 2nd-order statistics (covariance) | Uses higher-order statistics (kurtosis, negentropy) |
| Unique solution (up to rotation) | Unique solution (under non-Gaussianity assumption) |
The "Cocktail Party Problem"¶
Scenario: Multiple people talking simultaneously in a room, multiple microphones recording.
Observed: Mixtures $\mathbf{x}_i(t)$ at each microphone $i=1,\ldots,m$ (each is a linear combination of all voices)
$$\begin{bmatrix} x_1(t) \\ x_2(t) \\ \vdots \\ x_m(t) \end{bmatrix} = \begin{bmatrix} h_{11} & h_{12} & \cdots & h_{1n} \\ h_{21} & h_{22} & \cdots & h_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ h_{m1} & h_{m2} & \cdots & h_{mn} \end{bmatrix} \begin{bmatrix} s_1(t) \\ s_2(t) \\ \vdots \\ s_n(t) \end{bmatrix}$$
where:
- ${\bf x}(t) \in \mathbb{R}^m$: observed mixtures at $m$ microphones
- ${\bf H} \in \mathbb{R}^{m \times n}$: unknown mixing matrix (captures room acoustics, positions, etc.)
- ${\bf s}(t) \in \mathbb{R}^n$: independent source signals from $n$ speakers
Goal: Recover the original sources $\mathbf{s}_i(t)$ (individual voices)
Assumption: The source signals are statistically independent (different people speak independently)
ICA can separate these mixed signals without knowing:
- The mixing process (how sound travels and mixes)
- The number or positions of speakers
- Any training examples of separated sources
This is called "blind" source separation because we don't know the mixing process.
ICA Goal: Estimate $\hat{\bf H}^{-1}$ such that:
$$\begin{bmatrix} \hat{s}_1(t) \\ \hat{s}_2(t) \\ \vdots \\ \hat{s}_n(t) \end{bmatrix} = \begin{bmatrix} \hat{h}^{-1}_{11} & \hat{h}^{-1}_{12} & \cdots & \hat{h}^{-1}_{1m} \\ \hat{h}^{-1}_{21} & \hat{h}^{-1}_{22} & \cdots & \hat{h}^{-1}_{2m} \\ \vdots & \vdots & \ddots & \vdots \\ \hat{h}^{-1}_{n1} & \hat{h}^{-1}_{n2} & \cdots & \hat{h}^{-1}_{nm} \end{bmatrix} \begin{bmatrix} x_1(t) \\ x_2(t) \\ \vdots \\ x_m(t) \end{bmatrix}$$
where $\hat{\bf s}(t) = \hat{\bf H}^{-1} {\bf x}(t)$ recovers the original sources (up to permutation and scaling).
ICA Steps
Preprocessing:
- Center the data
- Whiten the data (decorrelate and normalize variance)
Optimization:
- Maximize non-Gaussianity of projected data
- Common measures: kurtosis or negentropy
- Iterative algorithms: FastICA, Infomax, JADE
Output:
- Predicted inverse mixing matrix $\hat{\mathbf{H}}^{-1}$
- Independent components $\mathbf{s}$
Note: ICA is more computationally intensive than PCA and requires more careful tuning.