Find the top k eigenpairs with power iteration and deflation
Full eigendecomposition is expensive for big covariance or graph matrices, and often you only need the top few directions. Power iteration finds the dominant one with matrix-vector products; deflation removes it so the next one becomes dominant.
Write top_eigs(A, k, iters=1000, tol=1e-12). A is a symmetric positive semidefinite (n, n) array whose top k eigenvalues are distinct and positive. Repeat k times:
1. Start from v = [1, 2, ..., n] scaled to unit length.
2. Repeat up to iters times: w = A v, w = w / ||w||. If ||w - v|| < tol, set v = w and stop; otherwise set v = w.
3. The eigenvalue is the Rayleigh quotient lam = v^T A v.
4. Fix the sign: flip v so that its entry with the largest absolute value (lowest index on ties) is positive.
5. Deflate: A = A - lam * outer(v, v).
Return (vals, vecs): vals is a list of k floats in descending order, vecs is a (k, n) array of unit eigenvectors.
def top_eigs(A, k, iters=1000, tol=1e-12)Example
A = diag(1, 5, 3), k = 2 gives vals [5.0, 3.0] and vecs [[0, 1, 0], [0, 0, 1]].
Understand the idea
Power iteration finds the largest eigenvector by multiplying a vector by the matrix again and again and normalising; the strongest direction takes over, like the loudest voice in a room after repeated echoes. The eigenvalue is the Rayleigh quotient v^T A v. Deflation then subtracts lam v v^T, which zeroes that eigenvalue so the next one becomes the strongest. Worked example: A = [[2, 1], [1, 2]], eigenvalues 3 and 1. Start v = [1, 2] / sqrt(5) = [0.447, 0.894]. A v = [1.789, 2.236], normalised [0.625, 0.781], moving toward [0.707, 0.707]. At convergence lam = 3. Deflate: A - 3 v v^T = [[0.5, -0.5], [-0.5, 0.5]], whose top eigenvector is [0.707, -0.707] with eigenvalue 1; the sign rule makes the largest-magnitude entry positive, lowest index on ties, so it stays [0.707, -0.707]. Rule: iterate w = A v / |A v| until |w - v| < tol, lam = v^T A v, fix sign, A -= lam outer(v, v); repeat k times. PageRank and PCA on huge matrices use this idea.