Computing eigenvalues and the SVD
Compute eigenvalues iteratively, from power iteration to the shifted QR algorithm used by LAPACK. Study SVD computation without forming AᵀA, eigenvalue sensitivity and the pseudospectra of nonnormal matrices.
After this lesson you can
- Implement power, inverse and Rayleigh quotient iteration and measure their convergence orders.
- Implement QR iteration with Hessenberg reduction, Wilkinson shifts and deflation.
- Explain how LAPACK computes an SVD and why eigenvalues of AᵀA are avoided.
- Use Bauer–Fike to predict eigenvalue sensitivity and recognize nonnormal matrices.
- Compute PageRank on a real graph by sparse power iteration.
Before you start
Motivation: four eigenvalue problems
Run np.linalg.eigh(C) on a covariance matrix and its principal components appear in milliseconds. Behind that are sixty years of numerical analysis, and almost nothing from eigenvalue theory survives as an algorithm: neither the characteristic polynomial nor solving by elimination. Before seeing what replaces them, here are four problems these tools will solve:
- PageRank. A page’s importance is a component of an eigenvector of a transition matrix with billions of rows. It does not fit in memory as a dense matrix, but can be multiplied by a vector: power iteration from the first section solves it (you will study PageRank on graphs).
- Vibration modes. A mass-and-spring structure obeys , and its natural frequencies come from , a symmetric problem. The lowest-frequency modes matter, not all of them: a typical case for shifted inverse iteration.
- Loss curvature. The largest eigenvalue of a network’s Hessian determines the stable learning rate. The Hessian has entries with in the millions, but a Hessian-vector product costs one backpropagation: again use power iteration (see Hessian spectra in real networks).
- Dynamical-system stability. decays if the spectral radius is below 1. But if is non-normal, computed eigenvalues may not mean what you think, and can grow several orders of magnitude before decaying. The final part explains when to trust them.
The lesson follows the problem’s history: from power to inverse and Rayleigh quotient iteration, then QR with the ingredients that make it practical (Hessenberg reduction, shifts, deflation), its symmetric and SVD versions, and finally when a computed eigenvalue is reliable. You will implement everything from scratch and compare with LAPACK.
Why not the characteristic polynomial?
In conditioning and stability you saw Wilkinson’s polynomial: eigenvalues of have condition number 1, yet roots of its characteristic polynomial can move in the third digit just from rounding coefficients to float64. Moving from matrix to coefficients chooses a severely ill-conditioned intermediate problem: an unstable algorithm even if each step is exact.
There is a second, deeper reason why no method can be “direct”.
Proof
Every monic polynomial is, up to sign, the characteristic polynomial of its companion matrix, which has ones on the subdiagonal, in the last column and zeros elsewhere. A finite eigenvalue algorithm applied to that matrix would give a formula for roots of using rational operations and radicals. For no such formula exists for every polynomial: this is the Abel–Ruffini theorem (Abel, 1824).
∎The design consequence is that every eigenvalue algorithm is iterative. Good ones converge so fast they seem direct, and divide work into two phases: a finite phase reducing to a form with many zeros (Hessenberg or tridiagonal) in operations, and an iterative phase on that form costing per eigenvalue or less. What follows builds both.
Power iteration
The idea is the one you saw when applying repeatedly: iterates align with the dominant eigenvector. An algorithm needs three decisions: normalization, eigenvalue estimation and stopping.
Normalization preserves direction and avoids overflow: without it, grows or decays like , and with overflows float64 around iteration 308. The Rayleigh quotient is the best eigenvalue estimate for a given vector: it minimizes over (the least-squares solution of ).
You prove the first part step by step in the final guided exercise. The second relies on a Rayleigh quotient property that reappears in the QR algorithm.
Proof
. Expanding gives . The first summand of the cross term is . The second also vanishes, but only by symmetry: . This leaves , and .
∎Vector error gives eigenvalue error : a vector correct to 8 digits gives an eigenvalue correct to 16. For nonsymmetric matrices, need not vanish and accuracy is only linear in .
When to stop
Stopping when stops changing is tempting and dangerous: with a small gap, the change between iterates is much smaller than the error. The correct criterion is residual , because of the backward error it certifies.
Proof
, and the 2-norm of rank-one matrix is . For the second part, write in an orthonormal eigenvector basis: .
∎So a good criterion is : the computed pair is exact for a matrix at relative distance from yours. This is backward stability applied to an iteration: if data errors are that size, you cannot ask for more. How this translates to eigenvalue error depends on its sensitivity, studied at the end.
import numpy as np
def matriz_con_espectro(lams, seed=0):
"""A = Q diag(lams) Q^T con Q ortogonal aleatoria: simétrica con autovalores conocidos."""
rng = np.random.default_rng(seed)
Q, _ = np.linalg.qr(rng.normal(size=(len(lams), len(lams))))
A = Q @ np.diag(lams) @ Q.T
return (A + A.T) / 2, Q # el producto en coma flotante no sale exactamente simétrico
def potencia(A, x0, tol=1e-12, max_iter=10_000):
"""Devuelve (rho, x, iteraciones). Para cuando ||A x - rho x|| <= tol * ||A||_1."""
escala = np.linalg.norm(A, 1)
x = x0 / np.linalg.norm(x0)
for k in range(1, max_iter + 1):
y = A @ x
rho = x @ y # cociente de Rayleigh de x (||x|| = 1)
if np.linalg.norm(y - rho * x) <= tol * escala:
return rho, x, k
x = y / np.linalg.norm(y)
return rho, x, max_iter
lams = np.array([10.0, 9.0, 5.0, 3.0, 2.0, 1.0, 0.5, 0.1])
A, Q = matriz_con_espectro(lams)
v1 = Q[:, 0]
x0 = np.ones(8)
rho, x, k = potencia(A, x0)
print(f"potencia: {k} iteraciones, rho = {rho:.15f}, |rho - 10| = {abs(rho - 10):.1e}")
# tasas medidas: el vector converge como 0.9^k y el cociente de Rayleigh como 0.81^k
x = x0 / np.linalg.norm(x0)
seno, err_rho = [], []
for _ in range(150):
x = A @ x
x /= np.linalg.norm(x)
seno.append(np.linalg.norm(x - (x @ v1) * v1))
err_rho.append(abs(x @ A @ x - 10))
k = np.arange(1, 151)
tasa_v = np.exp(np.polyfit(k[20:120], np.log(seno[20:120]), 1)[0])
tasa_r = np.exp(np.polyfit(k[10:60], np.log(err_rho[10:60]), 1)[0])
print(f"tasa del vector: {tasa_v:.4f} (|l2/l1| = {9/10})")
print(f"tasa del autovalor: {tasa_r:.4f} (|l2/l1|^2 = {(9/10)**2:.2f})")
print(f"iteraciones para reducir el error del vector 1e6: {np.ceil(np.log(1e-6) / np.log(0.9)):.0f}")The measured vector rate is and eigenvalue rate : the square of , as predicted. With tolerance relative to , 251 iterations are needed, although the eigenvalue was correct to 15 digits much earlier: the residual measures the vector, which converges at half the speed. This is the price of gap . For huge sparse matrices (PageRank, Hessians), this slowness is accepted because each iteration is cheap; otherwise there is something much better.
Inverse iteration and the Rayleigh quotient
The eigenvalues of are , with the same eigenvectors. The dominant one corresponds to the closest to , and power iteration on that matrix converges to with factor
This is shifted inverse iteration and its Rayleigh quotient version. With a good the factor can be arbitrarily small: with eigenvalues and it equals , and each step gains digits. Never invert the matrix: factor once with partial pivoting, and each iteration solves two triangular systems in .
What if the shift is updated each step with the best available estimate? That estimate is the Rayleigh quotient.
The argument fits in two lines. By the previous theorem, . One inverse iteration step with shift multiplies the angle’s tangent by a factor of order , so . Without symmetry, , leaving . Ostrowski proved this in papers from 1958 and 1959; full symmetric-case analysis is in chapter 4 of Parlett.
“Cubic” means correct digits triple at each step. In float64 this looks like a jump from about 3 digits to 10 and then to rounding. To really see it needs more precision: mpmath uses whatever you request.
import numpy as np
import mpmath as mp
A, Q = matriz_con_espectro(np.array([10.0, 9.0, 5.0, 3.0, 2.0, 1.0, 0.5, 0.1]))
mp.mp.dps = 150 # 150 cifras decimales
Am = mp.matrix(A.tolist())
x = mp.matrix([1] * 8)
x = x / mp.norm(x)
print(" k rho_k ||A x - rho x|| cifras")
for k in range(6):
rho = (x.T * Am * x)[0]
r = mp.norm(Am * x - rho * x)
print(f"{k:2d} {mp.nstr(rho, 20):24s} {mp.nstr(r, 3):>12s} {float(-mp.log10(r)):6.1f}")
y = mp.lu_solve(Am - rho * mp.eye(8), x)
x = y / mp.norm(y)Starting from the all-ones vector, residuals pass through , , , and : once convergence takes hold, digits progress as , tripling each step. A detail matters: matriz_con_espectro symmetrizes using (A + A.T) / 2, because floating-point product is not exactly symmetric. Without that line, asymmetry suffices to make convergence quadratic, as for a nonsymmetric matrix, after about 30 digits. Notice which eigenvalue it reaches: , not dominant , nor the one nearest the initial Rayleigh quotient , which is . The destination depends on the whole starting vector, not just . Rayleigh quotient iteration is extremely fast, but you do not choose its destination. In the earlier race, the pink curve reaches rounding in three or four steps, but check which vertex it approaches. In practice it is combined with something controlling the process globally, exactly what QR does.
From unshifted QR to the practical algorithm
The preceding iterations compute one eigenvector at a time. To find all simultaneously, naturally iterate a block of vectors and reorthogonalize at each step, so the first converges to , the second to the next orthogonal complement, and so on. This is simultaneous iteration, whose efficient form is one of the twentieth century’s most important algorithms.
Simultaneous iteration is the QR algorithm
Since , each step is an orthogonal similarity: . Every has the eigenvalues of . What it computes is surprising.
Proof
The second equality composes the similarities. For the first, use induction: for it is . If true for , , using .
∎Thus the first column of performs power iteration, and the first generate , converging to the invariant subspace of the dominant eigenvalues. If magnitudes are distinct, (and are not deficient with respect to those subspaces, generically true), approaches an upper triangular matrix with eigenvalues on its diagonal, the Schur form, and entry decays as . Linear convergence with the same ratios as power iteration: two more ideas are needed.
Hessenberg reduction
One QR step on a dense matrix costs , and order steps are needed: . The first idea is to prepare the matrix.
Why not go straight to triangular? Abel–Ruffini makes it impossible. If the first reflection tried to zero the entire first column below the diagonal (as in QR), applying it on the right would mix the first column with the others and destroy the zeros. Starting at row 2, right multiplication leaves column 1 alone, so zeros survive. Cost is about operations; if is symmetric, so is , hence it is tridiagonal, and exploiting symmetry reduces cost to (Trefethen and Bau, lecture 26).
The reduction pays off because it is preserved: if is Hessenberg and , then is also Hessenberg. If is invertible, is Hessenberg times upper triangular, which is Hessenberg, and is upper triangular times Hessenberg, again Hessenberg (the singular case follows by continuity or construction with rotations). Hessenberg QR uses Givens rotations, one per subdiagonal entry, and a step costs ; for tridiagonal matrices, .
Shifts
The second idea comes from inverse iteration. A QR step with shift is
again an orthogonal similarity. Look at the last column of . From follows , and since is lower triangular, its last column is :
The last column of is an inverse-iteration step with shift on , starting at . If is near an eigenvalue, the last row of rapidly approaches : entry vanishes and is an eigenvalue. With Rayleigh shift , the Rayleigh quotient of , QR performs Rayleigh quotient iteration in its last row: quadratic convergence in general and cubic if is symmetric.
When falls below , set it to zero: this is deflation. The matrix is block triangular, is an eigenvalue and the algorithm continues with the upper submatrix, which keeps shrinking. If an intermediate subdiagonal entry becomes negligible, the problem splits into two independent ones.
Wilkinson’s shift
Rayleigh’s shift can fail. With , , is already orthogonal, its QR is and : nothing ever changes. Eigenvalues are equally distant from and underlying inverse iteration has no preference. Wilkinson’s solution looks at the final block, , and takes as its eigenvalue nearest :
written without the catastrophic subtraction of the quadratic formula (with either sign may be chosen). Wilkinson proved in 1968 that with this shift QR on a symmetric tridiagonal matrix always converges, and in practice final convergence is cubic.
In the interactive, the matrix with spectrum needs 182 unshifted steps, 21 with Rayleigh and 18 with Wilkinson, just over two per eigenvalue. Subdiagonal curves show why: unshifted they fall in straight lines, while with Wilkinson the active block’s last goes from to and , tripling digits, and deflates next step. The zero-diagonal matrix has eigenvalues in equal-magnitude pairs . Without a shift, subdiagonal entries separating different pairs decay linearly, but those within each pair do not move, and final block , with , remains forever. Rayleigh behaves identically because the diagonal stays zero at every step and the shift is always 0: the earlier writ large. Wilkinson finishes in 18 steps. This matrix returns in SVD computation.
Francis and the implicit double shift
A real nonsymmetric matrix can have complex eigenvalues, which no real shift isolates: an block with a conjugate pair never vanishes. Complex shifts and arithmetic would double cost and lose real structure. J. G. F. Francis’s solution (1961), independently developed at the same time by Vera Kublanovskaya, takes two consecutive steps with and , eigenvalues of the final block. Together they are equivalent to factoring
which is real. Forming would cost , but is unnecessary thanks to the implicit Q theorem: if is unreduced Hessenberg (no subdiagonal zeros), is determined up to signs by its first column. Francis computes only the first column of , with three nonzeros, applies reflection taking it to (creating a “bulge” outside Hessenberg form), and chases the bulge downward with small reflections until Hessenberg form returns. The theorem gives the same result as an explicit double step in about operations using real arithmetic. The limit is real Schur form: nearly triangular, with blocks for real eigenvalues and blocks for complex pairs.
Modern LAPACK goes further: hseqr chains many small shifts at once to use level-3 BLAS and seeks deflations in a wide window at the matrix end (“aggressive early deflation”, Braman, Byers and Mathias, 2002). Francis’s idea remains the core. Golub and Van Loan count about operations for eigenvalues and if Schur vectors are also needed.
Implementation from scratch
The version below uses complex arithmetic with one Wilkinson shift (the eigenvalue of the final nearest the corner, potentially complex): simpler than Francis’s double step and converging the same way, but losing real structure at a constant-factor cost. Hessenberg reduction follows the definition, with Householder reflections applied on both sides.
import numpy as np
import scipy.linalg as sla
def hessenberg(A):
"""H = Q^H A Q de Hessenberg superior con reflexiones de Householder. Devuelve (H, Q)."""
H = np.array(A, dtype=complex if np.iscomplexobj(A) else float)
n = H.shape[0]
Q = np.eye(n, dtype=H.dtype)
for k in range(n - 2):
x = H[k + 1:, k]
nx = np.linalg.norm(x)
if nx == 0:
continue
v = x.copy()
fase = x[0] / abs(x[0]) if x[0] != 0 else 1.0
v[0] += fase * nx # sin cancelación: mismo signo (fase) que x[0]
v /= np.linalg.norm(v)
H[k + 1:, k:] -= 2 * np.outer(v, v.conj() @ H[k + 1:, k:]) # por la izquierda
H[:, k + 1:] -= 2 * np.outer(H[:, k + 1:] @ v, v.conj()) # por la derecha
Q[:, k + 1:] -= 2 * np.outer(Q[:, k + 1:] @ v, v.conj())
H[k + 2:, k] = 0 # ceros exactos donde deben estar
return H, Q
rng = np.random.default_rng(1)
A = rng.normal(size=(6, 6))
H, Q = hessenberg(A)
print("ceros bajo la subdiagonal:", np.allclose(np.tril(H, -2), 0))
print("Q ortogonal: ", np.allclose(Q.T @ Q, np.eye(6)))
print("Q H Q^T = A: ", np.allclose(Q @ H @ Q.T, A))
print("mismos autovalores: ", np.allclose(np.sort_complex(np.linalg.eigvals(H)), np.sort_complex(np.linalg.eigvals(A))))
S = A + A.T
T, _ = hessenberg(S)
print("simétrica -> tridiagonal: ", np.allclose(np.triu(T, 2), 0) and np.allclose(np.tril(T, -2), 0))
print("coincide con scipy (|h_ij|):", np.allclose(np.abs(H), np.abs(sla.hessenberg(A))))Comparison with scipy.linalg.hessenberg uses absolute values: both use Householder reflections, but SciPy’s (LAPACK gehrd) may choose another sign, and Hessenberg form is determined only up to signs (the implicit Q theorem). Now the QR algorithm.
import numpy as np
import scipy.linalg as sla
import time
def desplazamiento_wilkinson(B):
"""Autovalor de la 2x2 final de B más cercano a la esquina B[-1, -1] (puede ser complejo)."""
a, b, c, d = B[-2, -2], B[-2, -1], B[-1, -2], B[-1, -1]
media, det = (a + d) / 2, a * d - b * c
disc = np.sqrt(complex(media * media - det))
l1, l2 = media + disc, media - disc
return l1 if abs(l1 - d) <= abs(l2 - d) else l2
def paso_qr(H, mu):
"""Un paso QR con desplazamiento sobre la Hessenberg H (in situ) con rotaciones de Givens."""
n = H.shape[0]
H[np.diag_indices(n)] -= mu
G = []
for k in range(n - 1): # H - mu I = Q R: anula la subdiagonal
a, b = H[k, k], H[k + 1, k]
r = np.hypot(abs(a), abs(b))
c, s = (a / r, b / r) if r > 0 else (1.0, 0.0)
g = np.array([[np.conj(c), np.conj(s)], [-s, c]])
H[k:k + 2, k:] = g @ H[k:k + 2, k:]
G.append(g)
for k, g in enumerate(G): # R Q: las mismas rotaciones por la derecha
H[:k + 2, k:k + 2] = H[:k + 2, k:k + 2] @ g.conj().T
H[np.diag_indices(n)] += mu
def qr_autovalores(A, tol=np.finfo(float).eps, max_pasos=None):
"""Todos los autovalores de A con Hessenberg + QR con desplazamiento de Wilkinson + deflación."""
H, _ = hessenberg(np.asarray(A, dtype=complex))
n = H.shape[0]
max_pasos = max_pasos or 30 * n
lam = np.zeros(n, dtype=complex)
hi, pasos = n - 1, 0
while hi > 0:
# deflación en la esquina
if abs(H[hi, hi - 1]) <= tol * (abs(H[hi, hi]) + abs(H[hi - 1, hi - 1])):
H[hi, hi - 1] = 0
lam[hi] = H[hi, hi]
hi -= 1
continue
# bloque activo [lo, hi]: hasta el primer elemento subdiagonal despreciable
lo = hi - 1
while lo > 0 and abs(H[lo, lo - 1]) > tol * (abs(H[lo, lo]) + abs(H[lo - 1, lo - 1])):
lo -= 1
if lo > 0:
H[lo, lo - 1] = 0
B = H[lo:hi + 1, lo:hi + 1].copy()
paso_qr(B, desplazamiento_wilkinson(B))
H[lo:hi + 1, lo:hi + 1] = B
pasos += 1
if pasos > max_pasos:
raise RuntimeError("el algoritmo QR no converge")
lam[0] = H[0, 0]
return lam, pasos
rng = np.random.default_rng(1)
for n in (10, 40, 80):
S = rng.normal(size=(n, n)); S = S + S.T # simétrica
G = rng.normal(size=(n, n)) # general: pares complejos
lam_s, p_s = qr_autovalores(S)
lam_g, p_g = qr_autovalores(G)
err_s = np.max(np.abs(np.sort(lam_s.real) - sla.eigh(S, eigvals_only=True))) / np.linalg.norm(S, 2)
ref = sla.eigvals(G)
err_g = max(np.min(np.abs(ref - l)) for l in lam_g) / np.linalg.norm(G, 2)
print(f"n = {n:3d} simétrica: {p_s:4d} pasos ({p_s / n:.2f} por autovalor), error {err_s:.1e}"
f" general: {p_g:4d} pasos ({p_g / n:.2f}), error {err_g:.1e}")
n = 80
S = rng.normal(size=(n, n)); S = S + S.T
t0 = time.perf_counter(); qr_autovalores(S); t_nuestro = time.perf_counter() - t0
t0 = time.perf_counter()
for _ in range(20): sla.eig(S)
t_eig = (time.perf_counter() - t0) / 20
t0 = time.perf_counter()
for _ in range(20): sla.eigh(S, eigvals_only=True)
t_eigh = (time.perf_counter() - t0) / 20
print(f"\nn = 80: nuestro QR / scipy eig = {t_nuestro / t_eig:.0f} scipy eig / eigvalsh = {t_eig / t_eigh:.1f}")Errors are of order relative to , as expected from a backward-stable algorithm, and step counts confirm theory: about 2 per eigenvalue for symmetric matrices (cubic convergence) and 3 for general ones (quadratic). Our version is tens of times slower than scipy.linalg.eig (about 30 in the cell run, though the ratio varies by machine) because each rotation is a Python call with matrices; the algorithm is the same, and in a compiled language the loop costs per step as theory promises. The last line anticipates the next section: for the same symmetric matrix, eig is several times slower than eigh for eigenvalues only.
The symmetric case
When everything improves at once. The spectral theorem guarantees real eigenvalues and an orthonormal eigenvector basis; reduction gives a tridiagonal in operations; and sensitivity is as low as possible.
Since LAPACK’s symmetric algorithms are backward stable with symmetric perturbation , each computed eigenvalue has absolute error of order , independent of anything else. Eigenvectors are different: the Davis–Kahan theorem bounds the angle between exact and computed eigenvectors by , where the gap is the distance from to the rest of the spectrum. With nearly repeated eigenvalues individual eigenvectors are poorly determined, even when their joint subspace is well determined.
For the tridiagonal, LAPACK offers several symmetric methods:
| Method | Routine | Idea | Tridiagonal cost |
|---|---|---|---|
| Implicit QR | steqr | previous section’s method with Wilkinson | eigenvalues; with vectors |
| Divide and conquer | stedc | splits the tridiagonal with a rank-one correction (Cuppen, 1981) and merges spectra by solving a secular equation | with vectors, much less in practice due to deflation |
| Bisection and inverse iteration | stebz, stein | counts eigenvalues below using Sylvester’s inertia law and refines with inverse iteration | for eigenvalues, plus reorthogonalizing vectors for clustered eigenvalues |
| MRRR | stemr | relatively robust representations: orthogonal eigenvectors without reorthogonalization (Dhillon and Parlett, 2004) |
np.linalg.eigh calls syevd (divide and conquer), and scipy.linalg.eigh defaults to syevr (MRRR), with argument driver to choose another and subset_by_index or subset_by_value to request a subset. In both cases, dense matrices are dominated by tridiagonalization and transformation back to the original basis, not the tridiagonal phase.
Why not use eig, which accepts symmetric matrices too? Because eig does not know the matrix is symmetric: it reduces to Hessenberg form (which would be tridiagonal in exact arithmetic, but is not exactly symmetric in floating point) and applies the general algorithm.
import numpy as np
import scipy.linalg as sla
import time
rng = np.random.default_rng(0)
X = rng.normal(size=(30, 50)) # 30 muestras de 50 variables: más variables que muestras
C = np.cov(X, rowvar=False) # 50x50, simétrica, semidefinida positiva, de rango 29
w, V = np.linalg.eig(C)
print("eig : dtype", w.dtype, "| autovalores con parte imaginaria no nula:", np.sum(w.imag != 0),
"| max |Im| =", f"{np.abs(w.imag).max():.1e}")
print(" ||V^T V - I|| =", f"{np.linalg.norm(V.conj().T @ V - np.eye(50)):.2f}",
"| autovalores negativos:", np.sum(w.real < 0))
wh, Vh = np.linalg.eigh(C)
print("eigh: dtype", wh.dtype, "| ordenados:", bool(np.all(np.diff(wh) >= 0)),
"| ||V^T V - I|| =", f"{np.linalg.norm(Vh.T @ Vh - np.eye(50)):.1e}",
"| mínimo:", f"{wh[0]:.1e}")
# coste: eig frente a eigh y eigvalsh
S = rng.normal(size=(200, 200)); S = S + S.T
def mide(f, rep=3):
t0 = time.perf_counter()
for _ in range(rep): f()
return (time.perf_counter() - t0) / rep
t_eig = mide(lambda: np.linalg.eig(S))
t_eigh = mide(lambda: np.linalg.eigh(S))
t_eigvalsh = mide(lambda: np.linalg.eigvalsh(S))
print(f"\nn = 200: eig / eigh = {t_eig / t_eigh:.1f} eig / eigvalsh = {t_eig / t_eigvalsh:.1f}")
# solo los 3 mayores con scipy
top = sla.eigh(S, subset_by_index=[197, 199], eigvals_only=True)
print("los 3 mayores (subset_by_index):", np.round(top, 6), " coinciden:", np.allclose(top, np.linalg.eigvalsh(S)[-3:]))With 30 samples of 50 variables, covariance has rank 29 and a zero eigenvalue of multiplicity 21. Here eig returns a complex array, with several imaginary parts of order among the zero eigenvalues, and nonorthogonal eigenvectors: any basis works in a repeated eigenspace, and eig has no reason to choose an orthonormal one. eigh returns ordered real eigenvalues and a basis orthonormal to rounding. Both return some slightly negative eigenvalues (the smallest from eigh is ): this is rounding error guaranteed by Weyl, and why clipping to zero before taking roots is useful. eigh is also several times faster.
SVD on a computer
The SVD is tied to the symmetric problem: are eigenvalues of and columns of their eigenvectors. The obvious recipe is to form , call eigh and take square roots. This is a mistake; the interactive shows why.
The red curve tracks truth until , then departs: below it values are of order unrelated to the truth, or negative eigenvalues have no real square root. Error accounting explains this. Forming in floating point incurs symmetric error with of order (times a dimension-dependent constant), and Weyl says each eigenvalue moves by up to . Relative error in is then of order and in half that. Once , meaning , no digits survive. This is the same loss as for normal equations: squaring the condition number. A backward-stable SVD instead gives exact singular values of with , and by Weyl’s singular-value version, : absolute error , not .
Golub–Kahan bidiagonalization
The correct way to compute SVD imitates the symmetric case without forming . Phase 1 (Golub and Kahan, 1965): alternating Householder reflections on left and right reduce to upper bidiagonal form,
in about operations. Left reflections zero column below the diagonal; right reflections zero row starting at the second superdiagonal. The right side may start one position later because similarity is unnecessary: and differ. If , it is cheaper first to compute QR, , then bidiagonalize square (Lawson–Hanson–Chan bidiagonalization).
Phase 2: singular values of . The zero-diagonal tridiagonal from the heatmap returns. Symmetric matrix of size has eigenvalues , and reordering rows and columns as turns it into the tridiagonal
with zero diagonal. SVD is therefore a symmetric tridiagonal problem, and the previous section’s methods adapt to work directly on : Golub and Reinsch’s implicit QR (1970), equivalent to symmetric QR applied to without forming it; Demmel and Kahan’s variant (1990), computing every singular value of a bidiagonal matrix with small relative error, even tiny ones; Fernando and Parlett’s dqds algorithm (1994) for values alone; and divide and conquer (bdsdc). np.linalg.svd and scipy.linalg.svd default to gesdd, the divide-and-conquer version; scipy.linalg.svd(..., lapack_driver="gesvd") uses QR, slower and sometimes more robust.
import numpy as np
def householder(x):
"""v unitario con (I - 2 v v^T) x = -sign(x0) ||x|| e1."""
v = x.astype(float).copy()
v[0] += np.copysign(np.linalg.norm(x), x[0])
nv = np.linalg.norm(v)
return v / nv if nv > 0 else v
def bidiagonalizar(A):
"""B = U^T A V bidiagonal superior (n x n) con reflexiones alternas. Solo devuelve B."""
B = np.array(A, dtype=float)
m, n = B.shape
for k in range(n):
v = householder(B[k:, k]) # columna k: ceros bajo la diagonal
B[k:, k:] -= 2 * np.outer(v, v @ B[k:, k:])
if k < n - 2:
v = householder(B[k, k + 1:]) # fila k: ceros desde la 2.ª superdiagonal
B[k:, k + 1:] -= 2 * np.outer(B[k:, k + 1:] @ v, v)
return B[:n, :n]
rng = np.random.default_rng(0)
m, n = 60, 12
U, _ = np.linalg.qr(rng.normal(size=(m, n)))
V, _ = np.linalg.qr(rng.normal(size=(n, n)))
s = np.logspace(0, -14, n) # sigma_1 = 1, ..., sigma_12 = 1e-14
A = U @ np.diag(s) @ V.T
B = bidiagonalizar(A)
print("bidiagonal:", np.allclose(np.tril(B, -1), 0, atol=1e-15) and np.allclose(np.triu(B, 2), 0, atol=1e-15))
d, e = np.diag(B), np.diag(B, 1)
off = np.empty(2 * n - 1); off[0::2] = d; off[1::2] = e
T = np.diag(off, 1) + np.diag(off, -1) # Golub-Kahan: diagonal nula
w = np.linalg.eigvalsh(T)
print("autovalores de T_GK = ±sigma:", np.allclose(np.sort(w[w > 0])[::-1], np.linalg.svd(B, compute_uv=False)))
s_svd = np.linalg.svd(A, compute_uv=False)
lam = np.linalg.eigvalsh(A.T @ A)[::-1]
s_ata = np.sqrt(np.clip(lam, 0, None))
print("\n sigma svd: err. abs AtA: err. abs lambda(AtA)")
for i in range(n):
print(f"{s[i]:8.1e} {abs(s_svd[i] - s[i]):9.1e} {abs(s_ata[i] - s[i]):9.1e} {lam[i]: .1e}")The table repeats the interactive with different numbers: SVD has absolute error at most for all singular values, and has error of order while (for example with and with ). Below that it returns numbers of order unrelated to truth, and the last two eigenvalues are negative: clipped to 0, the error is itself. Singular values of from SVD have relative error , no better: that is the problem’s limit, since storing in float64 already perturbs it by .
Sensitivity: Bauer–Fike, non-normal matrices and pseudospectra
For symmetric matrices Weyl says it all. For others, “how much does an eigenvalue move if the matrix moves?” has very different answers depending on the matrix; knowing them distinguishes algorithm failure from an ill-conditioned problem.
Proof
If is an eigenvalue of there is nothing to prove. Otherwise is invertible. Since is singular, so are and therefore . A matrix with is invertible (its Neumann series converges), so , because the 2-norm of diagonal is .
∎This is eigenvalue sensitivity in its simplest form. If is normal (: symmetric, skew-symmetric, orthogonal, circulant…), it is diagonalizable by a unitary matrix, , and no eigenvalue moves more than . Otherwise factor can be huge, and if is defective there is no and the bound says nothing.
The Bauer–Fike bound treats all eigenvalues alike. For a simple there is an individual measure: if and are its right and left eigenvectors (, ), a first-order expansion gives
For normal matrices and coincide and . The closer left and right eigenvectors are to perpendicular, the more sensitive the eigenvalue. scipy.linalg.eig(A, left=True) returns both, letting you compute for each.
The limiting case is Jordan block (zeros on the diagonal, ones on the superdiagonal), whose only eigenvalue is . Perturbing only the bottom-left corner, has characteristic polynomial : its eigenvalues are the -th roots of , with magnitude . With and , float64 rounding, eigenvalues move .
Pseudospectra
Eigenvalues of a non-normal matrix are so fragile that asking for them in floating point is often the wrong question. The robust question is where eigenvalues of nearby matrices can lie.
Proof
(b) (c): if , ; if , . (a) (b): if with , then and . (b) (a): let have unit singular vectors , meaning . With , whose norm is , .
∎Form (b) is computed: evaluate on a complex-plane grid and draw contours. For a normal matrix, and is the union of disks of radius centered on eigenvalues. For a non-normal matrix it can be much larger.
For the normal matrix, the cloud of perturbed eigenvalues is invisible for any small : each moves at most . For the size-8 Jordan block and , the cloud is a ring of radius to , of order and five orders larger than the perturbation; contours are nearly concentric circles with radii growing like . The triangular matrix with distinct eigenvalues is diagonalizable, with for and for : its disks merge into one elongated region as grows. The Toeplitz matrix is also one Jordan block (nilpotent of rank ), but pseudospectra are not circles: with and the boundary already has the loop shape of dashed curve , obtained from its coefficients. Reichel and Trefethen (1992) proved that banded Toeplitz pseudospectra approach, as , those of the infinite Toeplitz operator, containing the region enclosed by that curve, the “symbol”, even though each finite matrix’s spectrum is only .
What does this mean for a computed eigenvalue? eig is backward stable: it returns exact eigenvalues of with of order . Computed eigenvalues lie in , and that is all one can guarantee: if that pseudospectrum is small, they are accurate; if large, no float64 algorithm will do better, because the problem itself does not determine eigenvalues more accurately.
import numpy as np
import scipy.linalg as sla
rng = np.random.default_rng(3)
n = 8
# 1. Bauer-Fike en una triangular no normal con autovalores distintos
d = np.linspace(-0.8, 0.8, n)
A = np.diag(d) + np.diag(np.ones(n - 1), 1)
w, VL, VR = sla.eig(A, left=True, right=True)
kV = np.linalg.cond(VR)
peor = 0.0
for _ in range(200):
E = rng.normal(size=(n, n)) + 1j * rng.normal(size=(n, n))
E *= 1e-10 / np.linalg.norm(E, 2)
mu = np.linalg.eigvals(A + E)
peor = max(peor, max(np.min(np.abs(d - m)) for m in mu))
print(f"triangular: kappa_2(V) = {kV:.1e}; con ||E||_2 = 1e-10, mayor desplazamiento = {peor:.1e}, cota = {kV * 1e-10:.1e}")
kappa = 1 / np.abs(np.sum(VL.conj() * VR, axis=0)) # columnas unitarias: 1 / |y^* x|
orden = np.argsort(w.real)
print("kappa(lambda_i):", np.array2string(kappa[orden], formatter={"float_kind": lambda t: f"{t:.1e}"}))
# 2. Jordan: la esquina eps da las raíces n-ésimas de eps
J = np.diag(np.ones(n - 1), 1)
for eps in (1e-16, 1e-8, 1e-4):
Je = J.copy(); Je[-1, 0] = eps
print(f"J_8 + eps e_8 e_1^T, eps = {eps:.0e}: max |lambda| = {np.abs(np.linalg.eigvals(Je)).max():.3f}, eps^(1/8) = {eps ** (1 / 8):.3f}")
# 3. el redondeo basta: J_8 girada por una ortogonal aleatoria
Q, _ = np.linalg.qr(rng.normal(size=(n, n)))
lam = np.linalg.eigvals(Q @ J @ Q.T)
print(f"eigvals(Q J_8 Q^T): max |lambda| = {np.abs(lam).max():.3f} (exacto: 0; u^(1/8) = {(2.0**-53) ** (1 / 8):.3f})")
# 4. no normalidad en el tiempo: radio espectral 0.9 y, aun así, ||A^k|| crece
B = 0.9 * np.eye(n) + 0.9 * J
normas = [np.linalg.norm(np.linalg.matrix_power(B, k), 2) for k in range(0, 121)]
kmax = int(np.argmax(normas))
print(f"\nB = 0.9 (I + J_8): radio espectral 0.9, max_k ||B^k|| = {max(normas):.0f} en k = {kmax}, ||B^120|| = {normas[120]:.1f}")The size-8 triangular matrix has and comfortably satisfies Bauer–Fike: with the largest movement in 200 perturbations is , about 8 times below the bound because a random perturbation does not choose the most damaging direction. Even so, it is 200 times the perturbation. Individual condition numbers range from 29 at the extremes to 410 in the center: eigenvalues are not equally sensitive, and Bauer–Fike, seeing only , is pessimistic for all. The Jordan block reproduces the -th roots: moves the eigenvalue , and moves it . Merely writing in another orthonormal basis, without deliberate perturbation, makes eigvals return eigenvalues away from 0: rounding the similarity itself is the perturbation. Finally has spectral radius , so , but rises to at and at it is still . Eigenvalues describe the limit; pseudospectra describe transient behavior. Trefethen and Embree (chapter 16) quantify this: for every , , where is the greatest magnitude of a point in .
PageRank: power iteration at scale
Return to the first example. In a directed graph with nodes, let be the weight of the link from to and the column-stochastic matrix with : from , jump to with probability proportional to weight. Google’s matrix mixes with uniform jumps:
and the PageRank vector is stationary distribution , (Brin and Page, 1998). is dense and never formed: since for any distribution,
a sparse product costing proportionally to the number of links. Nodes without outgoing links (dangling nodes) leave zero columns in ; conventionally their mass is distributed uniformly, adding another rank-one term that is not formed. Convergence speed is (Haveliwala and Kamvar, 2003), independent of graph size. Moreover, for two distributions , , and column-stochastic does not increase the 1-norm, so . With , every iteration gains at least digits, and 175 iterations guarantee error for any graph.
import numpy as np
import scipy.sparse as sp
import networkx as nx
G = nx.les_miserables_graph() # coapariciones de personajes (Knuth, 1993): 77 nodos, 254 aristas con peso
nodos = list(G.nodes())
W = nx.to_scipy_sparse_array(G, nodelist=nodos, weight="weight", format="csr")
grado = np.asarray(W.sum(axis=0)).ravel() # peso total de las aristas de cada nodo
P = sp.csr_array(W @ sp.diags_array(1.0 / grado)) # estocástica por columnas, dispersa
print(f"N = {P.shape[0]}, no nulos = {P.nnz} de {P.shape[0] ** 2} ({P.nnz / P.shape[0] ** 2:.1%})")
def pagerank(P, alfa=0.85, tol=1e-12, max_iter=1000):
N = P.shape[0]
colgante = np.asarray(P.sum(axis=0)).ravel() == 0
x = np.full(N, 1.0 / N)
for k in range(1, max_iter + 1):
x_nuevo = alfa * (P @ x) + (alfa * x[colgante].sum() + 1 - alfa) / N
cambio = np.abs(x_nuevo - x).sum()
x = x_nuevo
if cambio < tol:
return x, k
return x, max_iter
pi, iters = pagerank(P)
ref = nx.pagerank(G, alpha=0.85, tol=1e-14)
print(f"iteraciones: {iters} max |pi - networkx| = {np.max(np.abs(pi - np.array([ref[u] for u in nodos]))):.1e}")
print("top 5 PageRank:", [(nodos[i], round(pi[i], 4)) for i in np.argsort(-pi)[:5]])
print("top 5 por grado:", [(nodos[i], int(grado[i])) for i in np.argsort(-grado)[:5]])
lam = np.sort(np.abs(np.linalg.eigvals(P.toarray())))[::-1]
print(f"|lambda_2(P)| = {lam[1]:.4f} alfa |lambda_2(P)| = {0.85 * lam[1]:.4f}")
for alfa in (0.5, 0.85, 0.95, 0.99):
print(f"alfa = {alfa}: {pagerank(P, alfa)[1]} iteraciones")The matrix has 8.6 % nonzero entries (on the real web, a tiny fraction), and 95 iterations give the same vector as networkx.pagerank to . Valjean leads both rankings but the rest differ. In a connected undirected graph, the stationary distribution without jumps () is proportional to weighted degree; jumps with probability separate PageRank from degree. Bishop Myriel is the striking case: 16th by total weight and 3rd by PageRank. Seven characters (Napoleon, Geborand, Cravatte…) appear only with him, and of the mass uniform jumps place on them, fraction passes to Myriel next step. Since comes from an undirected graph, it is similar to symmetric and has real eigenvalues; bounds convergence rate. Bringing toward 1 increases iterations (31, 95, 182 and 276): the model resembles the graph more and converges more slowly. Power iteration fits for three reasons: it only needs matrix-vector products, its spectral gap is guaranteed by , and ranking does not require greater precision. For sparse problems needing several eigenvalues, Krylov subspace methods (Lanczos, Arnoldi) generalize power iteration and converge much faster.
The professional version
| Function | LAPACK | Returns | When to use |
|---|---|---|---|
np.linalg.eigvals, np.linalg.eig | geev | unordered (complex) eigenvalues and eigenvectors | general square matrix |
scipy.linalg.eig(A, left=True) | geev | left eigenvectors too | condition , Markov chains |
scipy.linalg.schur | gees | (real) Schur form and Schur vectors | non-normal: stable orthonormal basis |
np.linalg.eigh, eigvalsh | syevd | ascending real eigenvalues, orthonormal vectors | symmetric or Hermitian, always |
scipy.linalg.eigh(A, subset_by_index=...) | syevr | a subset | the largest or smallest of a dense matrix |
scipy.linalg.eigh_tridiagonal | stemr, stebz | tridiagonal eigenvalues | tridiagonal already available (Lanczos) |
np.linalg.svd, scipy.linalg.svd | gesdd | , descending , | dense SVD; full_matrices=False almost always |
scipy.sparse.linalg.eigsh, eigs, svds | ARPACK | extreme of a sparse matrix or operator | large and sparse (next lesson) |
torch.linalg.eigh, torch.linalg.svd | cuSOLVER / LAPACK | same, on GPU and differentiable | inside a model |
import numpy as np
import scipy.linalg as sla
rng = np.random.default_rng(7)
n = 60
S = rng.normal(size=(n, n)); S = (S + S.T) / 2
G = rng.normal(size=(n, n))
lam_s, _ = qr_autovalores(S)
lam_g, _ = qr_autovalores(G)
print("simétrica, max |nuestro - eigvalsh|:", f"{np.max(np.abs(np.sort(lam_s.real) - sla.eigvalsh(S))):.1e}")
ref = sla.eigvals(G)
print("general, max dist. a eigvals: ", f"{max(np.min(np.abs(ref - l)) for l in lam_g):.1e}")
print("pares complejos en G:", int(np.sum(ref.imag > 0)))
# potencia, inversa y Rayleigh contra eigh, en la misma simétrica
w, V = sla.eigh(S)
rho, x, k = potencia(S, np.ones(n), tol=1e-10)
j = np.argmax(np.abs(w))
print(f"\npotencia: {k} iteraciones hacia lambda = {w[j]:.6f} (|l2/l1| = {np.sort(np.abs(w))[-2] / np.abs(w[j]):.3f}),"
f" |rho - lambda| = {abs(rho - w[j]):.1e}")
# signo libre: comparar autovectores por el ángulo, no por las componentes
v_ref = V[:, j]
print("componentes iguales:", np.allclose(x, v_ref), " ángulo:", f"{np.linalg.norm(x - (x @ v_ref) * v_ref):.1e}")
# SVD: gesdd frente a gesvd, mismos valores
A = rng.normal(size=(80, 30))
s1 = sla.svd(A, compute_uv=False, lapack_driver="gesdd")
s2 = sla.svd(A, compute_uv=False, lapack_driver="gesvd")
print(f"\nsvd gesdd frente a gesvd: max diferencia {np.max(np.abs(s1 - s2)):.1e}")The final comparison confirms expectations: our QR matches LAPACK to even on a general matrix with 26 complex pairs; power iteration needs 1908 iterations on random symmetric because (random matrices have tightly clustered extreme eigenvalues); and an eigenvector computed two ways has opposite signs, so components differ even though their angle is .
Common mistakes
Connections and further reading
- Theory (eigenvalues, the spectral theorem, SVD, Jordan form) is in linear algebra; here we compute it. Revisit Jordan form if the behavior of surprises you.
- Spectral graph methods (spectral clustering, embeddings, personalized PageRank) compute Laplacian eigenvectors with these algorithms or Krylov variants: normalized Laplacians.
- PCA, spectral embeddings and truncated SVD use
eigh,svdor randomized SVD, which uses QR and a small dense SVD. - A network’s Hessian spectrum is estimated by power iteration (or Lanczos) on Hessian-vector products, as in the first section.
- Further reading: Trefethen and Bau, lectures 24–31, tell this story in greater detail; Golub and Van Loan, chapters 7 and 8, cover algorithms and costs; Parlett covers the symmetric case; Trefethen and Embree cover pseudospectra.
Exercises
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 4. How do you write ?
rayleigh_quotient_iteration(A, x0, tol=1e-12, max_iter=20) for symmetric . Return (lam, x, k): eigenvalue, unit eigenvector and number of iterations performed (systems solved). Robust stopping criterion: before each solve, check residual and stop if satisfied; if np.linalg.solve fails because is exactly singular, or returns nonfinite values, the current vector is already an eigenvector: stop then too. Do not call eig or eigh.import numpy as np
def rayleigh_quotient_iteration(A, x0, tol=1e-12, max_iter=20):
"""Devuelve (lam, x, k) con A x = lam x, ||x|| = 1 y k sistemas resueltos."""
A = np.asarray(A, dtype=float)
x = np.asarray(x0, dtype=float)
x = x / np.linalg.norm(x)
escala = np.linalg.norm(A, 1)
k = 0
# tu código: rho = cociente de Rayleigh, residuo, parada, solve protegido, normalizar
lam = x @ A @ x
return lam, x, kSummary
- Power iteration only needs products and converges as (the Rayleigh quotient at its square if is symmetric). Stop using the residual, a backward error. It is useful for PageRank and network Hessians.
- Inverse iteration with shift targets the eigenvalue nearest with factor ; Rayleigh quotient shifts give cubic convergence for symmetric matrices, but do not let you choose the destination.
- QR is simultaneous iteration; Hessenberg reduces each step to , shifts make its last row Rayleigh iteration, Wilkinson ensures it starts, and Francis uses real arithmetic with an implicit double shift.
- For symmetric matrices,
eigh: eigenvalues with absolute error (Weyl), orthonormal vectors and lower cost. SVD uses Golub–Kahan bidiagonalization, never , which loses . - A stable algorithm’s computed eigenvalue is exact for a nearby matrix; its error depends on sensitivity: in Bauer–Fike, for each eigenvalue, in a Jordan block. Pseudospectra map sensitivity and explain non-normal transient behavior.