SciPy Matrix Decompositions
A decomposition (or factorization) rewrites a matrix as a product of simpler matrices — triangular, orthogonal or diagonal ones. It's like factoring 60 into 2 × 2 × 3 × 5: the pieces reveal structure and make later work easier. Almost every linear-algebra routine you call uses one of these behind the scenes.
| Decomposition | Form | Typical use |
|---|---|---|
| LU | A = P L U | Solving many systems with the same A |
| Cholesky | A = L Lᵀ | Symmetric positive definite matrices (covariances) |
| QR | A = Q R | Least squares, orthogonal bases |
| Eigen | A v = λ v | Vibrations, stability, PCA, Markov chains |
| SVD | A = U Σ Vᵀ | Rank, compression, pseudo-inverse, PCA |
LU decomposition
LU splits a square matrix into a lower-triangular L and an upper-triangular U (with a permutation P for row swaps). Triangular systems are trivial to solve, so once you have the factors, each new right-hand side is cheap:
import numpy as np
from scipy import linalg
A = np.array([[2.0, 1.0, 1.0],
[4.0, 3.0, 3.0],
[8.0, 7.0, 9.0]])
P, L, U = linalg.lu(A)
print("L =")
print(L)
print("U =")
print(U)
print("P @ L @ U == A:", np.allclose(P @ L @ U, A))
# Factor once, solve for several right-hand sides
lu, piv = linalg.lu_factor(A)
for b in ([4.0, 10.0, 24.0], [1.0, 1.0, 1.0]):
print("solution:", np.round(linalg.lu_solve((lu, piv), b), 4) + 0.0)L =
[[1. 0. 0. ]
[0.25 1. 0. ]
[0.5 0.66666667 1. ]]
U =
[[ 8. 7. 9. ]
[ 0. -0.75 -1.25 ]
[ 0. 0. -0.66666667]]
P @ L @ U == A: True
solution: [1. 1. 1.]
solution: [ 1. -1. 0.]
Cholesky decomposition
A symmetric positive definite matrix — like a covariance matrix — can be written as L @ L.T. Cholesky is about twice as fast as LU, and it fails if the matrix isn't positive definite, which makes it a handy test:
import numpy as np
from scipy import linalg
cov = np.array([[4.0, 2.0],
[2.0, 3.0]])
L = linalg.cholesky(cov, lower=True)
print("L =")
print(np.round(L, 4))
print("L @ L.T == cov:", np.allclose(L @ L.T, cov))
try:
linalg.cholesky(np.array([[1.0, 2.0], [2.0, 1.0]]))
except linalg.LinAlgError as err:
print("not positive definite:", err)L =
[[2. 0. ]
[1. 1.4142]]
L @ L.T == cov: True
not positive definite: 2-th leading minor of the array is not positive definite
QR decomposition
QR writes A = Q R, where Q has orthonormal columns and R is upper triangular. It's the numerically stable way to do least squares:
import numpy as np
from scipy import linalg
A = np.array([[1.0, 1.0],
[1.0, 2.0],
[1.0, 3.0],
[1.0, 4.0]])
b = np.array([6.0, 5.0, 7.0, 10.0])
Q, R = linalg.qr(A, mode="economic")
print("Q columns are orthonormal:", np.allclose(Q.T @ Q, np.eye(2)))
coef = linalg.solve_triangular(R, Q.T @ b)
print("intercept, slope:", np.round(coef, 4))Q columns are orthonormal: True
intercept, slope: [3.5 1.4]
Eigenvalues and eigenvectors
An eigenvector v of a matrix A is a direction that A only stretches, never rotates: A v = λ v, where the eigenvalue λ is the stretch factor. For symmetric matrices use eigh(), which is faster and returns real, sorted eigenvalues:
import numpy as np
from scipy import linalg
A = np.array([[2.0, 1.0],
[1.0, 2.0]])
values, vectors = linalg.eigh(A)
print("eigenvalues:", values)
print("eigenvectors (columns):")
print(np.round(vectors, 4))
v = vectors[:, 1]
print("A @ v == 3 * v:", np.allclose(A @ v, 3 * v))eigenvalues: [1. 3.]
eigenvectors (columns):
[[-0.7071 0.7071]
[ 0.7071 0.7071]]
A @ v == 3 * v: True
Eigenvectors have a nice application to Markov chains. Here a city's weather moves between sunny and rainy days; the long-run share of each is the eigenvector with eigenvalue 1:
import numpy as np
from scipy import linalg
# Column j = probabilities of tomorrow's weather given today is j
T = np.array([[0.8, 0.4], # -> sunny
[0.2, 0.6]]) # -> rainy
values, vectors = linalg.eig(T)
k = np.argmin(abs(values - 1))
steady = np.real(vectors[:, k])
steady = steady / steady.sum()
print("eigenvalues:", np.round(np.real(values), 4))
print(f"long run: {steady[0]:.1%} sunny, {steady[1]:.1%} rainy")eigenvalues: [1. 0.4]
long run: 66.7% sunny, 33.3% rainy
Singular value decomposition
The SVD works for any matrix, even non-square ones: A = U Σ Vᵀ. The singular values in Σ measure how much each direction matters. Keeping only the largest ones gives the best low-rank approximation, the idea behind image compression and PCA:
import numpy as np
from scipy import linalg
# Ratings of 4 films by 5 viewers: two "tastes" plus a little noise
rng = np.random.default_rng(5)
taste = np.array([[5, 4, 1, 1], [1, 1, 5, 4]], dtype=float)
weights = np.array([[1, 0], [0.9, 0.1], [0, 1], [0.2, 0.8], [0.5, 0.5]])
ratings = weights @ taste + rng.normal(0, 0.1, size=(5, 4))
U, s, Vt = linalg.svd(ratings, full_matrices=False)
print("singular values:", np.round(s, 3))
approx = U[:, :2] @ np.diag(s[:2]) @ Vt[:2]
print("rank-2 max error:", round(abs(ratings - approx).max(), 3))singular values: [12.277 6.004 0.173 0.051]
rank-2 max error: 0.087
Two singular values dominate and the rest are tiny — the data really has only two "tastes", and a rank-2 approximation reproduces it almost perfectly.
Test yourself
Which decomposition only works for symmetric positive definite matrices?
- LU
- QR
- Cholesky
- SVD
Why use eigh instead of eig for a symmetric matrix?
- eig doesn't work on symmetric matrices
- eigh is faster and returns real, sorted eigenvalues
- eigh returns only one eigenvalue
- They are identical
Which decomposition works on any matrix, including non-square ones?
- Cholesky
- SVD
- eigh
- LU with lu_solve