Sub topic 2
Projecting Data and Reconstructing It
Assume you know basic Python, NumPy, matrix multiplication, means, and variance. PCA works with a feature matrix where rows are samples and columns are features.
Projecting data and reconstructing it
After centering the data, PCA finds component directions in a matrix \(W\). Keeping the first \(k\) directions gives the projection, or scores:
\[ Z = Xc Wk \]
Here, \(Xc\) is centered data, \(Wk\) contains the first \(k\) component vectors, and \(Z\) is the lower-dimensional representation.
You can approximately reconstruct the original data with:
\[ \hat X = ZW_k^T + \mu \]
where \(\mu\) is the feature-mean vector. The reconstruction loses information because discarded components are not restored.
Explained variance and the scree plot
Each component has an eigenvalue that measures the variance it captures. The explained variance ratio for component \(i\) is:
\[ ri = \frac{\lambdai}{\sumj \lambdaj} \]
The cumulative ratio adds these values from the first component onward. A scree plot displays component variance in descending order. A sharp bend, called the elbow, can suggest where additional components provide less benefit.
Choosing how many components to keep
Choose \(k\) by balancing information retention, computation, and simplicity:
- Use a scree plot to look for an elbow.
- Set a target such as 90% or 95% cumulative explained variance.
- Use cross-validation when PCA supports a predictive model.
- Check reconstruction error if accurate recovery matters.
Implementing PCA from scratch with NumPy
The following code centers data, computes the covariance matrix, finds its eigenvectors, projects onto two components, and reconstructs the data.
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 3)) @ np.array([
[3.0, 0.0, 0.0],
[1.0, 1.0, 0.0],
[0.0, 0.0, 0.2],
])
mean = X.mean(axis=0)
X_centered = X - mean
covariance = np.cov(X_centered, rowvar=False)
values, vectors = np.linalg.eigh(covariance)
order = np.argsort(values)[::-1]
values = values[order]
components = vectors[:, order]
k = 2
scores = X_centered @ components[:, :k]
reconstructed = scores @ components[:, :k].T + mean
ratio = values / values.sum()
error = np.mean((X - reconstructed) ** 2)
print("Scores:", scores.shape)
print("Explained variance:", ratio)
print("Reconstruction error:", error)Exercise
Why must the mean be added back after reconstructing centered data?
Show answer
Centering subtracts the original feature means. Adding the mean back returns the reconstruction to the original coordinate system.