Algorithmcore
Eigenfaces
Also called Turk-Pentland face recognition.
Recognize aligned face images by projecting them on the leading principal components of a training set, found from a small M x M matrix, and taking the nearest class.
- Solves
- Object recognition
- Time
- O(M^2 P + M^3) worst · average · best
- Space
- O(M P + M^2) extra
- Where
- K = the number of eigenfaces kept; M = the number of training images; P = the number of pixels per image
- Model
- Real RAM
- Properties
- deterministiclinearnearest neighborsupervised
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Matthew Turk, Alex Pentland, 1991
Eigenfaces is an algorithm that recognizes faces in images that are already cropped and aligned. It treats each image as one long vector of pixel values, finds the directions in which a training set of faces varies most (the principal components, which look like ghostly faces and are called eigenfaces), and describes each face by a few weights on these directions. A new image is recognized as the person whose average weights are nearest. Turk and Pentland (1991) also used the distance from the space of eigenfaces to decide whether an image is a face at all. The main trick is to find the eigenfaces from an matrix, with the number of training images, instead of a matrix, with the number of pixels.
In plain words
Each face photo has thousands of pixels, but faces are alike: two eyes, a nose, a mouth, in about the same places. So a face can be described as the average face plus a mix of a few typical patterns. The program learns these patterns from a set of photos. They are the ways in which the photos differ most from the average.
To recognize a new photo, the program finds how much of each pattern it contains. These few numbers are like a short code for the face. The program compares the code with the codes of known people and picks the closest one. If the photo cannot be built well from the patterns at all, it is probably not a face.
The problem
The input is a training set of face images , each a vector of gray values, with a person label for each image, and a number . All images have the same size, and the faces are centered and scaled the same way. The output is a model that maps a new image to a person label, to "unknown", or to "not a face". This is a case of object recognition by nearest neighbor search in a learned space.
The algorithm
Let be the mean image and the matrix of the differences . The eigenfaces are the leading eigenvectors of the scatter matrix , which is times the covariance matrix of the images. This is principal component analysis of the faces. If , then , so the eigenvectors of the small matrix give those of the big one.
EIGENFACES-TRAIN(Γ_1, ..., Γ_M, labels, K)- 1
Ψ ← (1/M) Σ_i Γ_i - 2
Φ_i ← Γ_i - Ψ for each i; A ← [Φ_1 ... Φ_M] - 3
B ← Aᵀ A ▷ M × M, entries Φ_iᵀ Φ_j - 4
(λ_l, v_l) ← eigenpairs of B, with λ_1 ≥ λ_2 ≥ ... - 5
u_l ← A v_l / ‖A v_l‖ for l = 1 .. K ▷ only λ_l > 0 - 6
Ω_c ← mean of (u_1ᵀ Φ_i, ..., u_Kᵀ Φ_i) over the images i of class c - 7
return Ψ, u_1 .. u_K, Ω
EIGENFACES-RECOGNIZE(Γ, θ_face, θ_class)- 1
ω_l ← u_lᵀ (Γ - Ψ) for l = 1 .. K - 2
ε ← ‖(Γ - Ψ) - Σ_l ω_l u_l‖ ▷ distance from face space - 3
if ε > θ_face then return "not a face" - 4
c ← the class with the least ‖ω - Ω_c‖ - 5
if ‖ω - Ω_c‖ > θ_class then return "unknown" - 6
return c
Example
Take four training images of pixels, written as vectors: person a has and , and person b has and . The mean is . The small matrix of line L3 is
with the eigenvalues . The eigenvalue comes from the fact that the four differences sum to zero. The first eigenface is : bright corners on one diagonal, dark on the other, which is what separates a from b. Keep . All images of a get the weight and those of b get , so and .
The new image has and the weight . It is at distance from and from , so it is person a. Its distance from face space is .
The image has , exactly . But its distance from face space is , larger than for any training image. With it is rejected as "not a face". The test file checks these numbers.
Correctness
The full proof is in proofs/correctness.md. The facts that are proved:
- Theorem (small matrix). Each eigenpair of with gives a unit eigenvector of with the same eigenvalue. These vectors are orthonormal, and every positive eigenvalue of arises this way.
- Theorem (rank). has rank at most , because the differences sum to zero. So there are at most useful eigenfaces.
- Theorem (best subspace). Among all -dimensional subspaces, the span of the first eigenfaces has the least total squared distance to the training differences, and that distance is the sum of the dropped eigenvalues. This is the optimality of PCA.
- Theorem (projection). The weights give the nearest point of face space, and distances between weight vectors equal distances between the projected images.
These theorems are about the computation. Whether the nearest class is the right person is an empirical question, and the answer depends on lighting, pose and alignment.
Proof: Correctness of eigenfacesfull
This proof covers lines L1 to L13 of the main page. The training set has images , each with a class label. Line L1 gives the mean , and line L2 gives and the matrix . The scatter matrix is ; the covariance of Turk and Pentland is , which has the same eigenvectors. Arithmetic is exact. The claim is about the linear algebra, not about how well the method recognizes faces.
Lemma 1 (the small matrix)
Let with and . Then is a unit eigenvector of with the eigenvalue , and . If are orthonormal eigenvectors of with positive eigenvalues, the vectors are orthonormal. Each positive eigenvalue of is an eigenvalue of with the same multiplicity.
Proof. , and , so . For two such vectors,
In the other direction, if with , then and , because . The two maps and are injective on the eigenspaces of , so the eigenspaces have the same dimension.
So line L3 builds the matrix , line L4 finds its eigenpairs, and line L5 turns them into the leading eigenvectors of , the eigenfaces. Their eigenvalues for are .
Lemma 2 (rank)
has rank at most , so there are at most eigenfaces with a positive eigenvalue.
Proof. , so the columns of are linearly dependent and .
The code stops at eigenvalues that are up to rounding, so it returns at most eigenfaces, and with all of them it rebuilds each training image exactly (they lie in ).
Lemma 3 (projection)
Let have orthonormal columns. For an image with , the weights of line L8 give the point of the face space that is closest to , and the distance of line L9 satisfies . For two images, is the distance between their projections.
Proof. is the orthogonal projection onto , so is orthogonal to the span, and the Pythagorean theorem gives both the minimality and . Also because .
Theorem 1 (eigenfaces are the best subspace)
Let be the eigenvalues of . For each matrix with orthonormal columns,
and equality holds for the eigenfaces of line L5.
Proof. By Lemma 3 for each , the left side is . Write with orthonormal eigenvectors . Then
Each lies in , because is a projection, and . Under these constraints the sum is largest when for the largest and for the others: moving weight from a larger to a smaller one never increases the sum. So , and the left side is at least . For , the eigenfaces, for and otherwise, which gives equality.
When the best subspace is not unique, and the eigenfaces are one of the best ones.
Theorem 2 (recognition)
Line L6 stores, for each class , the mean of the weight vectors of its training images. Lines L8 to L13 return "not a face" if ; otherwise they return the class whose is nearest to , or "unknown" if that distance is above .
Proof. Line L8 computes and line L9 the distance of Lemma 3. Lines L10 to L13 test the thresholds and scan the classes for the least distance. By Lemma 3 the distances in weight space are distances in face space.
What is not proved
Nothing here says that the nearest class is the right person. The eigenfaces keep the directions of largest variance of the training set, and these can come from lighting or pose rather than identity. Belhumeur, Hespanha and Kriegman (1997) showed that such variation can dominate the first eigenfaces. That is a limit of the model, not of the computation.
Complexity
The cost model is the real-RAM. Eigenvalues cannot be computed exactly with a finite number of field operations in general, so line L4 is counted as an eigen solver to a fixed precision, with operations. This is standard for the QR method and is the practical cost of the Jacobi method of cvla.py, which makes a few sweeps of each.
- Training. Line L3 costs , line L4 , line L5 and line L6 . With , the total is . The extra space is for and the eigenfaces and for .
- The direct way. The matrix costs to build, space and to decompose. For images, , and is over 4 billion entries. The small matrix trick makes the method practical when .
- A thin SVD of gives the same eigenfaces in time and is better conditioned, because it does not square the singular values. See singular value decomposition.
- Recognition. Line L8 costs , line L9 , and the search of line L11 for classes, which is at most .
Properties
- Linear and fast. A query costs dot products with images, plus a search over -dimensional vectors.
- Optimal for reconstruction, not for recognition. PCA keeps the directions of largest variance. These can come from lighting rather than identity, so the first eigenfaces may describe the light. This is a heuristic observation, shown in experiments by Belhumeur, Hespanha and Kriegman (1997).
- Needs alignment. The pixel vectors are compared position by position, so the faces must be cropped, centered and scaled the same way.
- Detects non-faces. The distance from face space measures how well the image fits the model at all.
- Unsupervised features. The labels are used only in line L6. The eigenfaces do not depend on them.
Variants and improvements
- Fisherfaces (Belhumeur, Hespanha and Kriegman 1997) project first with PCA and then with linear discriminant analysis, which uses the labels to separate the classes. They report lower error rates under changes of lighting and expression. That is a benchmark result on their data.
- Dropping the first components. Some systems drop the first few eigenfaces to reduce the effect of lighting. This is a heuristic.
- Modular eigenspaces. Pentland, Moghaddam and Starner (1994) used separate eigenspaces for views and for features such as eyes and nose.
- Probabilistic and Bayesian versions model the variation within a person and between persons with Gaussians.
- Kernel PCA finds nonlinear components, see kernel PCA.
- Shape and texture models. Active appearance models apply PCA to shape and to texture after warping, which removes much of the alignment problem.
- Modern recognition uses deep networks trained on very large data sets. Eigenfaces remain a baseline and a teaching example.
When to use it
Use it as a simple baseline for recognition of aligned faces, or of other aligned objects, under controlled lighting and pose, and as a first step to reduce the dimension before another classifier. Use linear discriminant analysis when labels are available and the lighting varies. For faces in the wild, use a modern learned method. For finding faces in an image, use a detector such as Viola-Jones first.
Pitfalls
- Unaligned faces. A shift of a few pixels changes the vectors much more than a change of person. Align the eyes first.
- Lighting. Changes of light dominate the variance. Normalize the images or use Fisherfaces.
- Forgetting the mean. Project , not .
- Normalizing . , not . Without the division the weights have the wrong scale.
- Zero eigenvalues. At most eigenvalues are positive. An eigenvector of a zero eigenvalue gives , which cannot be normalized.
- Squaring. Forming squares the condition number. A thin SVD of avoids that.
- Thresholds. and must be tuned on data. With infinite thresholds every image gets a label.
Implementations
The Python code in impl/python/eigenfaces.py trains the model with the small matrix of lines L1 to L7, using the symmetric eigen solver of cvla.py, and recognizes with lines L8 to L13. It also computes the eigenvectors of the big matrix the direct way, for the tests. The tests check the example above, the agreement of the small and the big matrix, the orthonormality of the eigenfaces, the rank bound and the exact rebuild of the training images, the identity between the residual and the dropped eigenvalues, the optimality of PCA against random subspaces, and the recognition of noisy synthetic faces.
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the computer vision pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra for the computer vision pages.
A matrix is a list of rows. A vector is a flat list. The functions do not
change their arguments. Entries are floats, but zeros, eye, transpose, add,
sub, scale, mul, matvec, dot, cross, skew, solve, inv and det also work with
fractions.Fraction entries and then give exact results.
Tolerances:
- solve, inv and det raise ValueError only on an exact zero pivot. A matrix
that is close to singular gives large entries; check the condition yourself.
- sym_eig and svd stop a Jacobi sweep when every off-diagonal term is below
1e-15 times the size of its pair (at most 100 sweeps).
- polyroots_real keeps a root z when |Im z| <= imag_tol * max(1, |z|), with
imag_tol = 1e-6 by default. Roots of multiplicity k are found with an error
of about 1e-16^(1/k) relative, so a double root keeps an imaginary part near
1e-8.
This module holds no algorithm of a computer vision page.
"""
from __future__ import annotations
import cmath
import math
from typing import List, Sequence, Tuple
Matrix = List[List[float]]
Vector = List[float]
_JACOBI_EPS = 1e-15
_MAX_SWEEPS = 100
# ---------------------------------------------------------------- basics
def zeros(m: int, n: int) -> Matrix:
"""The m x n zero matrix."""
return [[0.0] * n for _ in range(m)]
def eye(n: int) -> Matrix:
"""The n x n identity matrix."""
return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
def _is_matrix(a) -> bool:
return len(a) > 0 and isinstance(a[0], (list, tuple))
def transpose(a: Sequence[Sequence[float]]) -> Matrix:
"""The transpose of a matrix."""
return [list(col) for col in zip(*a)]
def add(a, b):
"""a + b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x + y for x, y in zip(a, b)]
def sub(a, b):
"""a - b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x - y for x, y in zip(a, b)]
def scale(a, c):
"""c times a, for a vector or a matrix a and a number c."""
if _is_matrix(a):
return [[c * x for x in row] for row in a]
return [c * x for x in a]
def mul(a: Sequence[Sequence[float]], b: Sequence[Sequence[float]]) -> Matrix:
"""The matrix product a b."""
if len(a[0]) != len(b):
raise ValueError("mul: shapes do not match")
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a: Sequence[Sequence[float]], x: Sequence[float]) -> Vector:
"""The product a x of a matrix and a vector."""
if len(a[0]) != len(x):
raise ValueError("matvec: shapes do not match")
return [sum(p * q for p, q in zip(row, x)) for row in a]
def dot(x: Sequence[float], y: Sequence[float]) -> float:
"""The inner product of two vectors."""
return sum(p * q for p, q in zip(x, y))
def norm(a) -> float:
"""The Euclidean norm of a vector, or the Frobenius norm of a matrix."""
if _is_matrix(a):
return math.sqrt(sum(float(x) * float(x) for row in a for x in row))
return math.sqrt(sum(float(x) * float(x) for x in a))
def cross(a: Sequence[float], b: Sequence[float]) -> Vector:
"""The cross product a x b of two 3-vectors."""
return [a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0]]
def skew(a: Sequence[float]) -> Matrix:
"""The skew matrix [a]_x, with skew(a) b = cross(a, b)."""
z = a[0] - a[0]
return [[z, -a[2], a[1]],
[a[2], z, -a[0]],
[-a[1], a[0], z]]
# ---------------------------------------------------- Gaussian elimination
def _eliminate(a: Matrix, b: Matrix) -> Tuple[Matrix, Matrix, int]:
"""Reduce [a | b] to upper triangular form with partial pivoting.
Works in place on copies made by the caller. Returns a, b and the sign
of the row permutation.
"""
n = len(a)
sign = 1
for k in range(n):
p = max(range(k, n), key=lambda i: abs(a[i][k]))
if a[p][k] == 0:
raise ValueError("singular matrix")
if p != k:
a[k], a[p] = a[p], a[k]
b[k], b[p] = b[p], b[k]
sign = -sign
piv = a[k][k]
for i in range(k + 1, n):
f = a[i][k] / piv
if f == 0:
continue
ai, ak = a[i], a[k]
for j in range(k, n):
ai[j] = ai[j] - f * ak[j]
bi, bk = b[i], b[k]
for j in range(len(bi)):
bi[j] = bi[j] - f * bk[j]
return a, b, sign
def solve(a: Sequence[Sequence[float]], b):
"""Solve a x = b for a square a, by Gaussian elimination with partial
pivoting. b is a vector or a matrix (several right-hand sides); the
result has the same form. Raises ValueError on an exact zero pivot."""
n = len(a)
if any(len(row) != n for row in a):
raise ValueError("solve: matrix is not square")
vec = not _is_matrix(b)
rhs = [[x] for x in b] if vec else [list(row) for row in b]
if len(rhs) != n:
raise ValueError("solve: shapes do not match")
u, c, _ = _eliminate([list(row) for row in a], rhs)
m = len(c[0]) if n else 0
x = [[0.0] * m for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(m):
s = c[i][j]
for k in range(i + 1, n):
s = s - u[i][k] * x[k][j]
x[i][j] = s / u[i][i]
return [row[0] for row in x] if vec else x
def inv(a: Sequence[Sequence[float]]) -> Matrix:
"""The inverse of a square matrix. Raises ValueError if it is singular."""
n = len(a)
one = a[0][0] - a[0][0] + 1 if n else 1.0
ident = [[one if i == j else one - one for j in range(n)] for i in range(n)]
return solve(a, ident)
def det(a: Sequence[Sequence[float]]) -> float:
"""The determinant of a square matrix, by Gaussian elimination."""
n = len(a)
if any(len(row) != n for row in a):
raise ValueError("det: matrix is not square")
if n == 0:
return 1.0
try:
u, _, sign = _eliminate([list(row) for row in a], [[] for _ in range(n)])
except ValueError:
return a[0][0] - a[0][0]
d = u[0][0] - u[0][0] + sign
for i in range(n):
d = d * u[i][i]
return d
# ------------------------------------------------------- Jacobi methods
def sym_eig(a: Sequence[Sequence[float]]) -> Tuple[Vector, Matrix]:
"""Eigenvalues and eigenvectors of a real symmetric matrix by the cyclic
Jacobi method. Returns (w, V): w ascending, and column j of V is a unit
eigenvector for w[j], so a = V diag(w) V^T. Only the upper triangle of
a is read (the lower triangle is taken as its mirror)."""
n = len(a)
s = [[float(a[min(i, j)][max(i, j)]) for j in range(n)] for i in range(n)]
v = eye(n)
for _ in range(_MAX_SWEEPS):
rotated = False
for p in range(n - 1):
for q in range(p + 1, n):
apq = s[p][q]
if apq == 0.0:
continue
app, aqq = s[p][p], s[q][q]
if abs(apq) <= _JACOBI_EPS * math.sqrt(abs(app * aqq)) or \
abs(apq) < 1e-300:
s[p][q] = s[q][p] = 0.0
continue
rotated = True
theta = (aqq - app) / (2.0 * apq)
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
sn = t * c
for k in range(n):
skp, skq = s[k][p], s[k][q]
s[k][p] = c * skp - sn * skq
s[k][q] = sn * skp + c * skq
for k in range(n):
spk, sqk = s[p][k], s[q][k]
s[p][k] = c * spk - sn * sqk
s[q][k] = sn * spk + c * sqk
s[p][q] = s[q][p] = 0.0
for k in range(n):
vkp, vkq = v[k][p], v[k][q]
v[k][p] = c * vkp - sn * vkq
v[k][q] = sn * vkp + c * vkq
if not rotated:
break
order = sorted(range(n), key=lambda i: s[i][i])
w = [s[i][i] for i in order]
vs = [[v[k][i] for i in order] for k in range(n)]
return w, vs
def _complete_basis(cols: List[Vector], m: int, need: List[int]) -> None:
"""Replace the columns with index in need by unit vectors orthogonal to
all other columns (Gram-Schmidt on the standard basis)."""
keep = [c for i, c in enumerate(cols) if i not in need]
for i in need:
best, best_norm = None, -1.0
for e in range(m):
x = [0.0] * m
x[e] = 1.0
for _ in range(2):
for c in keep:
d = dot(c, x)
x = [xi - d * ci for xi, ci in zip(x, c)]
nx = norm(x)
if nx > best_norm:
best, best_norm = x, nx
u = [xi / best_norm for xi in best]
cols[i] = u
keep.append(u)
def _svd_tall(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
m, n = len(a), len(a[0])
cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
for _ in range(_MAX_SWEEPS):
rotated = False
for p in range(n - 1):
for q in range(p + 1, n):
cp, cq = cols[p], cols[q]
alpha = sum(x * x for x in cp)
beta = sum(x * x for x in cq)
gamma = sum(x * y for x, y in zip(cp, cq))
if gamma == 0.0 or abs(gamma) <= _JACOBI_EPS * math.sqrt(alpha * beta):
continue
rotated = True
zeta = (beta - alpha) / (2.0 * gamma)
t = (1.0 if zeta >= 0 else -1.0) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
c = 1.0 / math.sqrt(1.0 + t * t)
s = c * t
cols[p] = [c * x - s * y for x, y in zip(cp, cq)]
cols[q] = [s * x + c * y for x, y in zip(cp, cq)]
vp, vq = vcols[p], vcols[q]
vcols[p] = [c * x - s * y for x, y in zip(vp, vq)]
vcols[q] = [s * x + c * y for x, y in zip(vp, vq)]
if not rotated:
break
sv = [norm(c) for c in cols]
order = sorted(range(n), key=lambda i: -sv[i])
sv = [sv[i] for i in order]
cols = [cols[i] for i in order]
vcols = [vcols[i] for i in order]
smax = sv[0] if sv else 0.0
ucols: List[Vector] = []
need: List[int] = []
for i, c in enumerate(cols):
if sv[i] > 1e-13 * smax and sv[i] > 1e-300:
ucols.append([x / sv[i] for x in c])
else:
ucols.append([0.0] * m)
need.append(i)
if need:
_complete_basis(ucols, m, need)
return transpose(ucols), sv, transpose(vcols)
def svd(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Vector, Matrix]:
"""Thin singular value decomposition by the one-sided Jacobi method.
For an m x n matrix a with k = min(m, n), returns (U, S, V) with U of
size m x k, S a list of k values in descending order and V of size
n x k, such that a = U diag(S) V^T. U and V have orthonormal columns.
For m >= n, V is square (n x n)."""
m, n = len(a), len(a[0])
if m >= n:
return _svd_tall(a)
u, s, v = _svd_tall(transpose(a))
return v, s, u
def nullvec(a: Sequence[Sequence[float]]) -> Vector:
"""A unit vector x that minimizes ||a x||: the right singular vector of
the smallest singular value. If a has fewer rows than columns, zero rows
are added first, so the result is in the null space. The sign is not
fixed."""
m, n = len(a), len(a[0])
rows = [list(map(float, r)) for r in a] + [[0.0] * n for _ in range(n - m)]
_, _, v = _svd_tall(rows)
return [v[i][n - 1] for i in range(n)]
# ---------------------------------------------- orthogonal factorizations
def qr(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
"""QR factorization by Householder reflections. For an m x n matrix a,
returns Q (m x m, orthogonal) and R (m x n, upper triangular) with
a = Q R. The signs are chosen so that the diagonal of R is >= 0."""
m, n = len(a), len(a[0])
r = [[float(x) for x in row] for row in a]
q = eye(m)
for k in range(min(m - 1, n)):
x = [r[i][k] for i in range(k, m)]
nx = norm(x)
if nx == 0.0:
continue
alpha = -nx if x[0] >= 0 else nx
v = list(x)
v[0] -= alpha
nv = norm(v)
if nv == 0.0:
continue
v = [vi / nv for vi in v]
for j in range(n):
d = sum(v[i - k] * r[i][j] for i in range(k, m))
if d != 0.0:
for i in range(k, m):
r[i][j] -= 2.0 * v[i - k] * d
for i in range(m):
d = sum(q[i][l] * v[l - k] for l in range(k, m))
if d != 0.0:
for l in range(k, m):
q[i][l] -= 2.0 * d * v[l - k]
for k in range(min(m, n)):
if r[k][k] < 0:
r[k] = [-x for x in r[k]]
for i in range(m):
q[i][k] = -q[i][k]
for i in range(m):
for j in range(min(i, n)):
r[i][j] = 0.0
return q, r
def rq(a: Sequence[Sequence[float]]) -> Tuple[Matrix, Matrix]:
"""RQ factorization of a square matrix: returns R (upper triangular,
with a diagonal >= 0) and Q (orthogonal) with a = R Q. It is computed
from the QR factorization of the transpose of the row-reversed matrix."""
n = len(a)
if any(len(row) != n for row in a):
raise ValueError("rq: matrix is not square")
flipped = transpose([list(row) for row in reversed(a)])
q1, r1 = qr(flipped)
rt = transpose(r1)
r = [list(reversed(row)) for row in reversed(rt)]
q = [list(row) for row in reversed(transpose(q1))]
return r, q
def cholesky(a: Sequence[Sequence[float]]) -> Matrix:
"""The lower triangular L with a = L L^T, for a symmetric positive
definite a. Raises ValueError if a pivot is not positive."""
n = len(a)
low = zeros(n, n)
for j in range(n):
d = a[j][j] - sum(low[j][k] * low[j][k] for k in range(j))
if d <= 0:
raise ValueError("cholesky: matrix is not positive definite")
low[j][j] = math.sqrt(d)
for i in range(j + 1, n):
low[i][j] = (a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
return low
# ---------------------------------------------------------- polynomials
def _horner(c: Sequence[complex], x):
p = 0.0
for ci in c:
p = p * x + ci
return p
def polyroots_real(coeffs: Sequence[float], imag_tol: float = 1e-6) -> Vector:
"""Real roots of the polynomial with the given coefficients, highest
power first. All complex roots are found by the Durand-Kerner method.
A root z is kept as real when |Im z| <= imag_tol * max(1, |z|); its real
part is then polished by Newton steps on the real polynomial. Returns
the real roots in ascending order, with repeats for multiple roots."""
c = [float(x) for x in coeffs]
while c and c[0] == 0.0:
c.pop(0)
n = len(c) - 1
if n < 1:
return []
c = [x / c[0] for x in c]
rho = max([abs(c[i]) ** (1.0 / i) for i in range(1, n + 1)] + [0.0])
if rho == 0.0:
return [0.0] * n
z = [rho * cmath.exp(1j * (2.0 * math.pi * k / n + 0.4)) for k in range(n)]
for _ in range(2000):
moved = 0.0
for k in range(n):
den = 1.0 + 0j
for j in range(n):
if j != k:
den *= z[k] - z[j]
if den == 0:
den = 1e-12 * rho
step = _horner(c, z[k]) / den
z[k] -= step
moved = max(moved, abs(step) / max(1.0, abs(z[k])))
if moved <= 1e-15:
break
deriv = [c[i] * (n - i) for i in range(n)]
roots = []
for zk in z:
if abs(zk.imag) > imag_tol * max(1.0, abs(zk)):
continue
x = zk.real
px = _horner(c, x)
for _ in range(8):
dp = _horner(deriv, x)
if dp == 0.0 or px == 0.0:
break
xn = x - px / dp
pn = _horner(c, xn)
if abs(pn) >= abs(px):
break
x, px = xn, pn
roots.append(x)
return sorted(roots)
# ------------------------------------------------------------ self-test
def self_test() -> None:
"""Check svd, sym_eig and polyroots_real. Raises AssertionError."""
import random
rng = random.Random(7)
for _ in range(3):
a = [[rng.uniform(-1, 1) for _ in range(5)] for _ in range(5)]
u, s, v = svd(a)
rec = mul(mul(u, [[s[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(v))
assert norm(sub(rec, a)) <= 1e-10
assert all(s[i] >= s[i + 1] for i in range(4))
sym = add(a, transpose(a))
w, vv = sym_eig(sym)
rec = mul(mul(vv, [[w[i] if i == j else 0.0 for j in range(5)] for i in range(5)]), transpose(vv))
assert norm(sub(rec, sym)) <= 1e-10
assert all(w[i] <= w[i + 1] for i in range(4))
r = polyroots_real([1.0, -6.0, 11.0, -6.0])
assert len(r) == 3
assert all(abs(x - y) <= 1e-10 for x, y in zip(r, [1.0, 2.0, 3.0]))
if __name__ == "__main__":
self_test()
eigenfaces.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/eigenfaces/. The authors are listed in prov/22X5JB.jsonl.
"""Eigenfaces of Turk and Pentland (1991).
A face image is a flat list of P gray values (row by row). The training set
has M images with labels. The eigenfaces are the leading eigenvectors of
A A^T, where the columns of A are the training images minus their mean. They
are found from the small M x M matrix A^T A: if A^T A v = lambda v, then
A A^T (A v) = lambda (A v). Recognition projects a new image on the
eigenfaces and takes the nearest class mean in that space.
"""
import math
from cvla import sym_eig
def train(images, labels, k):
"""Return a model dict with the mean, the k eigenfaces, their eigenvalues
(of A^T A) and the mean weight vector of each class."""
m = len(images)
p = len(images[0])
mean = [sum(img[j] for img in images) / m for j in range(p)] # @line L1
phi = [[img[j] - mean[j] for j in range(p)] for img in images] # @line L2
small = [[sum(a * b for a, b in zip(phi[i], phi[j])) for j in range(m)] for i in range(m)] # @line L3
w, v = sym_eig(small) # @line L4
order = sorted(range(m), key=lambda i: -w[i])
faces, values = [], []
for i in order[:k]:
if w[i] <= 1e-10 * max(w[order[0]], 1e-300):
break
u = [sum(v[r][i] * phi[r][j] for r in range(m)) for j in range(p)]
nu = math.sqrt(sum(x * x for x in u))
faces.append([x / nu for x in u]) # @line L5
values.append(w[i])
classes = {}
for img, lab in zip(images, labels):
classes.setdefault(lab, []).append(project_on(faces, mean, img))
centers = {lab: [sum(c) / len(ws) for c in zip(*ws)] for lab, ws in classes.items()} # @line L6
return {"mean": mean, "faces": faces, "values": values, "centers": centers} # @line L7
def project_on(faces, mean, img):
"""The weights omega_l = u_l^T (img - mean)."""
d = [x - y for x, y in zip(img, mean)]
return [sum(a * b for a, b in zip(u, d)) for u in faces]
def project(model, img):
return project_on(model["faces"], model["mean"], img)
def reconstruct(model, weights):
"""mean + sum of weights[l] * u_l."""
out = list(model["mean"])
for wl, u in zip(weights, model["faces"]):
for j in range(len(out)):
out[j] += wl * u[j]
return out
def distance_from_face_space(model, img):
"""|| (img - mean) - its projection on the eigenfaces ||."""
rec = reconstruct(model, project(model, img))
return math.sqrt(sum((x - y) ** 2 for x, y in zip(img, rec)))
def recognize(model, img, theta_face=math.inf, theta_class=math.inf):
"""Return (label, distance). label is "not a face" if the image is far
from face space and None if it is far from every class."""
omega = project(model, img) # @line L8
eps_face = distance_from_face_space(model, img) # @line L9
if eps_face > theta_face: # @line L10
return "not a face", eps_face
best, dist = None, math.inf
for lab, c in model["centers"].items(): # @line L11
d = math.sqrt(sum((a - b) ** 2 for a, b in zip(omega, c)))
if d < dist:
best, dist = lab, d
if dist > theta_class: # @line L12
return None, dist
return best, dist # @line L13
def covariance_eigen(images):
"""Eigenvalues (descending) and eigenvectors of the P x P matrix A A^T, the
direct way, for tests on tiny images."""
m = len(images)
p = len(images[0])
mean = [sum(img[j] for img in images) / m for j in range(p)]
phi = [[img[j] - mean[j] for j in range(p)] for img in images]
big = [[sum(f[a] * f[b] for f in phi) for b in range(p)] for a in range(p)]
w, v = sym_eig(big)
order = sorted(range(p), key=lambda i: -w[i])
return [w[i] for i in order], [[v[r][i] for r in range(p)] for i in order]
test_eigenfaces.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/eigenfaces/. The authors are listed in prov/22X5JB.jsonl.
import math
import random
from eigenfaces import (
covariance_eigen,
distance_from_face_space,
project,
recognize,
reconstruct,
train,
)
EXAMPLE = [[8, 3, 3, 6], [6, 3, 3, 8], [3, 9, 5, 3], [3, 5, 9, 3]]
EXAMPLE_LABELS = ["a", "a", "b", "b"]
def dot(x, y):
return sum(a * b for a, b in zip(x, y))
def random_set(rng, m, p):
return [[rng.uniform(0, 255) for _ in range(p)] for _ in range(m)]
def test_example():
model = train(EXAMPLE, EXAMPLE_LABELS, 3)
assert model["mean"] == [5.0, 5.0, 5.0, 5.0]
assert [round(x, 9) for x in model["values"]] == [64.0, 16.0, 4.0]
assert [round(x, 9) for x in model["faces"][0]] == [0.5, -0.5, -0.5, 0.5]
model = train(EXAMPLE, EXAMPLE_LABELS, 1)
assert {k: round(v[0], 9) for k, v in model["centers"].items()} == {"a": 4.0, "b": -4.0}
label, dist = recognize(model, [7, 4, 3, 6])
assert label == "a" and abs(dist - 1.0) < 1e-9
assert abs(distance_from_face_space(model, [7, 4, 3, 6]) - 1.0) < 1e-9
label, dist = recognize(model, [5, 9, 9, 5])
assert label == "b" and abs(dist) < 1e-9
label, dist = recognize(model, [5, 9, 9, 5], theta_face=2.0)
assert label == "not a face" and abs(dist - 4.0) < 1e-9
def test_small_matrix_gives_the_covariance_eigenvectors():
rng = random.Random(3)
images = random_set(rng, 5, 12)
model = train(images, list(range(5)), 4)
big_w, big_v = covariance_eigen(images)
for lam, u, w, v in zip(model["values"], model["faces"], big_w, big_v):
assert abs(lam - w) < 1e-7 * big_w[0]
assert abs(abs(dot(u, v)) - 1.0) < 1e-8
assert all(abs(w) < 1e-7 * big_w[0] for w in big_w[4:])
def test_eigenfaces_are_orthonormal():
rng = random.Random(5)
model = train(random_set(rng, 8, 30), list(range(8)), 7)
faces = model["faces"]
assert len(faces) == 7
for i, u in enumerate(faces):
for j, v in enumerate(faces):
assert abs(dot(u, v) - (1.0 if i == j else 0.0)) < 1e-9
def test_rank_is_at_most_m_minus_one_and_training_set_is_rebuilt():
rng = random.Random(6)
images = random_set(rng, 6, 20)
model = train(images, list(range(6)), 10)
assert len(model["faces"]) == 5
for img in images:
rec = reconstruct(model, project(model, img))
assert max(abs(a - b) for a, b in zip(rec, img)) < 1e-8
def test_residual_equals_discarded_eigenvalues():
rng = random.Random(8)
images = random_set(rng, 7, 16)
full = train(images, list(range(7)), 6)
for k in range(1, 6):
model = train(images, list(range(7)), k)
resid = sum(distance_from_face_space(model, img) ** 2 for img in images)
assert abs(resid - sum(full["values"][k:])) < 1e-6 * full["values"][0]
def test_pca_beats_random_subspaces():
rng = random.Random(10)
images = random_set(rng, 6, 10)
model = train(images, list(range(6)), 2)
best = sum(distance_from_face_space(model, img) ** 2 for img in images)
for _ in range(50):
basis = []
for _ in range(2):
x = [rng.gauss(0, 1) for _ in range(10)]
for b in basis:
c = dot(x, b)
x = [xi - c * bi for xi, bi in zip(x, b)]
n = math.sqrt(dot(x, x))
basis.append([xi / n for xi in x])
other = dict(model, faces=basis)
assert sum(distance_from_face_space(other, img) ** 2 for img in images) >= best - 1e-9
def test_recognizes_noisy_faces():
rng = random.Random(12)
p = 64
people = [[rng.uniform(40, 220) for _ in range(p)] for _ in range(4)]
images, labels = [], []
for who, proto in enumerate(people):
for _ in range(3):
images.append([x + rng.gauss(0, 8) for x in proto])
labels.append(who)
model = train(images, labels, 6)
correct = 0
for who, proto in enumerate(people):
for _ in range(5):
label, _ = recognize(model, [x + rng.gauss(0, 8) for x in proto])
correct += label == who
assert correct == 20
noise = [rng.uniform(0, 255) for _ in range(p)]
face = [x + rng.gauss(0, 8) for x in people[0]]
assert distance_from_face_space(model, noise) > 2 * distance_from_face_space(model, face)
History
Sirovich and Kirby (1987) showed that faces can be represented well by a small number of principal components of a face set, which they called eigenpictures. Turk and Pentland (1991) used these components for recognition and detection. They added the classification by distance in face space and the distance from face space. On a database of over 2500 images of 16 people, they reported about 96% correct classification over changes of lighting, 85% over changes of head orientation and 64% over changes of size. These are benchmark results. A shorter conference version appeared at CVPR the same year. Belhumeur, Hespanha and Kriegman (1997) showed the limits of PCA under changes of lighting and proposed Fisherfaces. Eigenfaces made appearance-based recognition popular, and their ideas carried over to active appearance models and to subspace methods in general.
References
- Matthew Turk and Alex Pentland, Eigenfaces for recognition, Journal of Cognitive Neuroscience 3(1), 71-86, 1991, The computation of the eigenfaces from the M x M matrix, the classification by distance in face space, the distance from face space, and the experiments on 16 subjects
- L. Sirovich and M. Kirby, Low-dimensional procedure for the characterization of human faces, Journal of the Optical Society of America A 4(3), 519-524, 1987, Principal components of face images and their use to represent faces
- Peter N. Belhumeur, Joao P. Hespanha and David J. Kriegman, Eigenfaces vs. Fisherfaces, recognition using class specific linear projection, IEEE TPAMI 19(7), 711-720, 1997, The comparison of eigenfaces with Fisherfaces under changes of lighting and expression
- Richard Szeliski, Computer Vision: Algorithms and Applications, 1st edition, Springer, 2011, Section 14.2.1, Eigenfaces
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 22X5JB Edit this page History Report an error Markdown