Sub topic 9
Implementing PCA from scratch with NumPy
This chapter turns the PCA derivation into a small, tested NumPy class. It assumes you know basic Python and NumPy, mean and variance, matrix multiplication, and the convention that rows are samples and columns are features. It also assumes you have seen the covariance matrix and the idea of eigenvectors from earlier chapters.
By the end you will have a fit, transform and inverse_transform implementation. You will also have a short test suite that shows the implementation is correct, and a list of edge cases that break naive versions.
The recipe
PCA from scratch is five operations on a feature matrix X with n rows and d columns.
- Compute the column means and subtract them (centering).
- Build the
d × dcovariance matrix of the centered data. - Decompose it into eigenvalues and eigenvectors.
- Sort the eigenpairs from largest to smallest eigenvalue.
- Keep the first
keigenvectors and multiply the centered data by them.
| Step | NumPy call | Result shape |
|---|---|---|
| Center | `X - X.mean(axis=0)` | `(n, d)` |
| Covariance | `np.cov(Xc, rowvar=False)` | `(d, d)` |
| Eigendecomposition | `np.linalg.eigh(cov)` | `(d,)` and `(d, d)` |
| Sort | `np.argsort(eigvals)[::-1]` | `(d,)` index array |
| Project | `Xc @ eigvecs[:, :k]` | `(n, k)` |
A first pass, step by step
Start with synthetic data whose structure you know. The mixing matrix makes the first two features strongly correlated and the third feature small.
import numpy as np
rng = np.random.default_rng(0)
mixing = np.array([[3.0, 0.0, 0.0],
[1.0, 1.0, 0.0],
[0.0, 0.0, 0.2]])
X = rng.normal(size=(200, 3)) @ mixing
Xc = X - X.mean(axis=0)
cov = np.cov(Xc, rowvar=False)
eigvals, eigvecs = np.linalg.eigh(cov)
order = np.argsort(eigvals)[::-1]
eigvals = eigvals[order]
eigvecs = eigvecs[:, order]
scores = Xc @ eigvecs[:, :2]
ratio = eigvals / eigvals.sum()
print(scores.shape)
print(ratio)The shape is (200, 2). The covariance of this data is close to mixing.T @ mixing, whose eigenvalues are about 10.1, 0.9 and 0.04. So ratio should be near 0.92, 0.08 and 0.004. The exact digits depend on the random sample.
Three details in this code matter.
np.cov(..., rowvar=False)tells NumPy that columns are variables. The default isrowvar=True, which silently gives a200 × 200matrix for this data. That is the most common bug in hand-written PCA.np.covdivides byn - 1by default. Scikit-learn does the same, so your eigenvalues will match itsexplained_variance_.eighis for symmetric matrices. It returns real eigenvalues in ascending order and orthonormal eigenvectors in the columns. The sort step reverses that order.
Packaging it as a class
A reusable version separates fitting from transforming. This matters because new data must be centered with the means learned from the training data, not with its own means.
import numpy as np
class PCAFromScratch:
def __init__(self, n_components):
self.n_components = n_components
def fit(self, X):
X = np.asarray(X, dtype=float)
n, d = X.shape
if not 1 <= self.n_components <= min(n, d):
raise ValueError("n_components must be between 1 and min(n, d)")
self.mean_ = X.mean(axis=0)
Xc = X - self.mean_
cov = np.cov(Xc, rowvar=False)
eigvals, eigvecs = np.linalg.eigh(cov)
order = np.argsort(eigvals)[::-1]
eigvals = np.clip(eigvals[order], 0.0, None)
eigvecs = eigvecs[:, order]
# Fix the sign: make the largest-magnitude entry of each axis positive.
peak = np.argmax(np.abs(eigvecs), axis=0)
signs = np.sign(eigvecs[peak, np.arange(d)])
signs[signs == 0] = 1.0
eigvecs = eigvecs * signs
k = self.n_components
self.total_variance_ = eigvals.sum()
self.explained_variance_ = eigvals[:k]
self.explained_variance_ratio_ = eigvals[:k] / self.total_variance_
self.components_ = eigvecs[:, :k].T # shape (k, d)
return self
def transform(self, X):
return (np.asarray(X, dtype=float) - self.mean_) @ self.components_.T
def inverse_transform(self, Z):
return np.asarray(Z, dtype=float) @ self.components_ + self.mean_
def fit_transform(self, X):
return self.fit(X).transform(X)Some choices here are deliberate.
components_has shape(k, d), one axis per row. This is the same layout as scikit-learn's attribute, so the two are easy to compare. It is also whytransformusescomponents_.Tandinverse_transformusescomponents_.np.clip(..., 0.0, None)removes tiny negative eigenvalues such as-1e-17. Rounding produces them for rank-deficient data. They would otherwise give negative variance ratios.- The ratio divides by the total over all
deigenvalues, computed before truncation. If you divided by the sum of only the kept eigenvalues, every ratio would look better than it is. - Eigenvectors are only defined up to sign, because
vand-vspan the same axis. Different LAPACK builds can return different signs. Fixing a convention makes results reproducible. It does not make them more correct.
Verifying the implementation
Do not trust a hand-written PCA because it runs. Check properties that must hold if the math is right.
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]])
pca = PCAFromScratch(n_components=2).fit(X)
Z = pca.transform(X)
# 1. Components are orthonormal.
print(np.allclose(pca.components_ @ pca.components_.T, np.eye(2)))
# 2. Scores are uncorrelated, and their variances are the eigenvalues.
print(np.allclose(np.cov(Z, rowvar=False), np.diag(pca.explained_variance_)))
# 3. Total variance is preserved: the eigenvalues sum to the trace.
print(np.isclose(pca.total_variance_, np.trace(np.cov(X, rowvar=False))))
# 4. Keeping every component reconstructs the data exactly.
full = PCAFromScratch(n_components=3).fit(X)
print(np.allclose(full.inverse_transform(full.transform(X)), X))
# 5. Rank-2 reconstruction error equals the discarded variance.
err = np.mean((X - pca.inverse_transform(Z)) ** 2)
print(err)The first four checks print True. The last prints about 0.013. That is the discarded eigenvalue (about 0.04) divided by the 3 features, scaled by (n - 1) / n. The link between discarded variance and reconstruction error is what justifies picking k by explained variance.
Edge cases that break naive versions
Fewer samples than features. If n < d, the covariance matrix is still d × d, but its rank is at most n - 1. The extra eigenvalues are zero up to rounding. Requesting more than min(n, d) components is meaningless, which is why fit validates n_components. For very wide data, such as genomics with 20,000 features and 100 samples, forming a d × d matrix wastes memory. The SVD route in a later chapter avoids it.
Standardizing constant columns. For standardization you divide by the column standard deviation. A constant column has standard deviation zero, which gives nan values that then poison the whole covariance matrix. Drop such columns first, or replace zero scales with 1.
Centering with the wrong means. For test data, subtract the training means, as transform does. Re-centering test data with its own means shifts it relative to the fitted axes and corrupts the projection.
Mixed scales. Without standardization, a feature measured in thousands dominates the first component because it has the largest variance. That reflects the units, not the structure. Standardize first when features have different units. Skip standardization when they share a unit and variance differences are meaningful.
Near-degenerate eigenvalues. If two eigenvalues are almost equal, any rotation within their plane is an equally good pair of axes. Individual components then become unstable between runs or samples, even though the plane they span is stable. Do not interpret such components one at a time.
Memory and cost. Building the covariance matrix costs O(n d²) time and O(d²) memory. The eigendecomposition costs O(d³). This is fine for hundreds or a few thousand features. Beyond that, use randomized or incremental methods.
Adding standardization
Standardization fits naturally as an optional step in the same class. This subclass stores the scale learned during fit and reuses it later.
class StandardizedPCA(PCAFromScratch):
def fit(self, X):
X = np.asarray(X, dtype=float)
scale = X.std(axis=0, ddof=1)
self.scale_ = np.where(scale == 0, 1.0, scale)
return super().fit(X / self.scale_)
def transform(self, X):
return super().transform(np.asarray(X, dtype=float) / self.scale_)
def inverse_transform(self, Z):
return super().inverse_transform(Z) * self.scale_This works because dividing by a constant per column commutes with subtracting the mean. The base class learns mean_ of the scaled data, so transform stays consistent. Use ddof=1 to match np.cov. After standardizing, the covariance matrix equals the correlation matrix of the original data, and its eigenvalues sum to d.
Exercise
You fit your PCA on training data Xtrain and then call transform on Xtest. A colleague proposes centering Xtest with Xtest.mean(axis=0) "to be safe". Why is that wrong, and what does it do to the scores?
Show answer
The components were learned relative to the training mean, which defines the origin of the principal axes. Centering Xtest with its own mean moves its origin, so every score is shifted by (training mean minus test mean) projected onto the components. Test points then no longer sit in the same coordinate system as the training scores. Always reuse mean (and scale_ if standardizing) from fit.
Exercise
For data with n = 50 samples and d = 200 features, how many eigenvalues of the covariance matrix can be meaningfully nonzero, and why?
Show answer
At most n - 1 = 49. After centering, the 50 rows sum to zero, so they span at most a 49-dimensional subspace. The covariance matrix therefore has rank at most 49, and the other eigenvalues are zero up to rounding error.