Skip to content

Eigenvectors, SVD, and PCA

PCA chooses directions along which centered observations vary most. The calculation combines the geometry of projections with the covariance between variables. This page builds that calculation from a small invented matrix before using a library implementation.

Read linear algebra and geometry and random variables first. The matrix below contains samples in rows and three transformed gene measurements in columns.

For a square matrix A, an eigenvector v satisfies A @ v = lambda*v. The vector must be nonzero. Its eigenvalue lambda tells how the transformation scales that direction.

Start with a transformation in two dimensions. Consider one vector along the rising diagonal and another along the falling diagonal. Applying the matrix to either vector changes its length but preserves its line through the origin.

import numpy as np
transformation = np.array([[2.0, 1.0], [1.0, 2.0]])
directions = np.array([[1.0, 1.0], [1.0, -1.0]])
for direction in directions:
transformed = transformation @ direction
multiplier = (direction @ transformed) / (direction @ direction)
print("Direction:", direction, "Transformed:", transformed)
print(f"Eigenvalue: {multiplier:.1f}")
assert np.allclose(transformed, multiplier * direction)
Direction: [1. 1.] Transformed: [3. 3.]
Eigenvalue: 3.0
Direction: [ 1. -1.] Transformed: [ 1. -1.]
Eigenvalue: 1.0

The multiplier is the eigenvalue for that direction. A general vector can combine both directions, so the transformation scales its components differently and can change its overall direction. Eigenvectors identify the directions whose behavior is easier to describe.

A covariance matrix is symmetric and positive semidefinite. Its eigenvectors can form perpendicular unit directions, and its eigenvalues are nonnegative apart from numerical error. The largest eigenvalue identifies a direction of greatest variance.

Symmetric means that swapping the row and column indices leaves each covariance unchanged. Positive semidefinite means that v.T @ covariance @ v is nonnegative for every vector v. That expression is the variance of the projected observations, and a variance cannot be negative.

Perpendicular unit directions are called orthonormal. They separate the coordinate directions without changing vector lengths when all directions are retained. PCA chooses such directions in order of decreasing variance.

import numpy as np
measurements = np.array([
[2.0, 1.0, 4.0],
[3.0, 2.0, 3.0],
[4.0, 2.0, 5.0],
[7.0, 5.0, 6.0],
[8.0, 6.0, 5.0],
[9.0, 7.0, 7.0],
])
centered = measurements - measurements.mean(axis=0)
covariance = centered.T @ centered / (centered.shape[0] - 1)
eigenvalues, eigenvectors = np.linalg.eigh(covariance)
print("Covariance matrix:")
print(np.round(covariance, 3))
print("Eigenvalues, largest first:", np.round(eigenvalues[::-1], 4))
assert np.allclose(covariance @ eigenvectors, eigenvectors * eigenvalues)
Covariance matrix:
[[8.3 7.1 3.4 ]
[7.1 6.167 2.8 ]
[3.4 2.8 2. ]]
Eigenvalues, largest first: [15.8165 0.6117 0.0384]

NumPy’s eigh returns eigenvalues in ascending order. It uses the symmetry of the covariance matrix. A repeated eigenvalue can allow several equally valid choices of basis within its eigenspace.

Singular value decomposition writes the centered matrix as X = U @ diag(s) @ V.T. The columns of V are directions in feature space. The columns of U describe sample directions, while s contains their nonnegative scale factors.

For centered data with n rows, the sample covariance eigenvalues equal s**2 / (n-1). PCA scores are X @ V, which also equals U * s with columnwise multiplication.

left_vectors, singular_values, right_transpose = np.linalg.svd(
centered, full_matrices=False
)
scores = centered @ right_transpose.T
component_variance = singular_values ** 2 / (centered.shape[0] - 1)
explained_ratio = component_variance / component_variance.sum()
print("Singular values:", np.round(singular_values, 4))
print("Explained variance ratio:", np.round(explained_ratio, 4))
assert np.allclose(centered, (left_vectors * singular_values) @ right_transpose)
assert np.allclose(component_variance, eigenvalues[::-1])
Singular values: [8.8928 1.7489 0.4385]
Explained variance ratio: [0.9605 0.0371 0.0023]

The rank counts independent directions. Centering limits the rank to at most min(n-1, p). Thousands of genes do not create thousands of independent sample directions when only a few samples exist.

Retaining only the first components approximates the centered matrix. Add the original column means to return to the measurement scale. The discarded singular values determine the squared reconstruction error.

from sklearn.decomposition import PCA
retained = 2
reconstructed = scores[:, :retained] @ right_transpose[:retained]
squared_error = np.sum((centered - reconstructed) ** 2)
model = PCA(n_components=retained, svd_solver="full").fit(measurements)
print(f"Squared reconstruction error: {squared_error:.4f}")
print("Library variance ratios:", np.round(model.explained_variance_ratio_, 4))
assert np.isclose(squared_error, np.sum(singular_values[retained:] ** 2))
assert np.allclose(model.explained_variance_ratio_, explained_ratio[:retained])
Squared reconstruction error: 0.1922
Library variance ratios: [0.9605 0.0371]

An eigenvector and its negative describe the same axis. Two implementations can reverse a score axis without changing the PCA solution. Compare explained variance or reconstruction before treating a sign difference as an error.

from pathlib import Path
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2, figsize=(9, 3.8))
axes[0].bar(np.arange(1, 4), explained_ratio)
axes[0].set(xlabel="Component", ylabel="Explained variance ratio",
xticks=[1, 2, 3])
axes[1].scatter(scores[:, 0], scores[:, 1])
for index, point in enumerate(scores):
axes[1].annotate(str(index + 1), point[:2], xytext=(4, 4),
textcoords="offset points")
axes[1].set(xlabel="PC1 score", ylabel="PC2 score")
fig.tight_layout()
Path("outputs").mkdir(exist_ok=True)
fig.savefig("outputs/pca_geometry.png", dpi=160)
plt.close(fig)

The left plot gives variance by component, and the right plot locates the six invented samples on the first two components.

This example centers columns without standardizing their variance. Standardization would change the question by giving each feature unit variance. Neither choice identifies technical effects automatically.

A dominant component can reflect biology, batch, or an outlier. A small component can still contain useful biology. There is no universal explained variance threshold that proves which components are signal.

If a component direction changes sign, why does the reconstructed data stay the same?

The corresponding scores also change sign because they are dot products with that direction. Multiplying the reversed score by the reversed direction cancels both sign changes. The reconstruction therefore remains unchanged, even though a score plot appears reflected.

  • MIT Linear Algebra

    The course provides lectures and exercises on eigenvalues and matrix decompositions. These topics connect covariance directions to the SVD calculation.

  • NumPy SVD reference

    The reference defines returned matrix shapes and reconstruction identities. Compare full_matrices options when you reconstruct the centered measurement matrix.

See the NumPy SVD reference for the returned matrix shapes. The applied PCA guide covers a larger expression example. Continue with optimization.