Algorithm Search⌘K

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.

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
Properties
deterministiclinearnearest neighborsupervised
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 M×MM \times M matrix, with MM the number of training images, instead of a P×PP \times P matrix, with PP 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 MM face images Γ1,…,ΓM\Gamma_1, \dots, \Gamma_M, each a vector of PP gray values, with a person label for each image, and a number K≤M−1K \le M - 1. 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 Γ\Gamma 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 Ψ\Psi be the mean image and A=[Φ1⋯ΦM]A = [\Phi_1 \cdots \Phi_M] the P×MP \times M matrix of the differences Φi=Γi−Ψ\Phi_i = \Gamma_i - \Psi. The eigenfaces are the leading eigenvectors of the scatter matrix AATA A^T, which is MM times the covariance matrix of the images. This is principal component analysis of the faces. If ATAv=λvA^T A v = \lambda v, then AAT(Av)=λ(Av)A A^T (A v) = \lambda (A v), so the eigenvectors of the small matrix ATAA^T A give those of the big one.

  1. EIGENFACES-TRAIN(Γ_1, ..., Γ_M, labels, K)
  2. 1Ψ ← (1/M) Σ_i Γ_i
  3. 2Φ_i ← Γ_i - Ψ for each i; A ← [Φ_1 ... Φ_M]
  4. 3B ← Aᵀ A ▷ M × M, entries Φ_iᵀ Φ_j
  5. 4(λ_l, v_l) ← eigenpairs of B, with λ_1 ≥ λ_2 ≥ ...
  6. 5u_l ← A v_l / ‖A v_l‖ for l = 1 .. K ▷ only λ_l > 0
  7. 6Ω_c ← mean of (u_1ᵀ Φ_i, ..., u_Kᵀ Φ_i) over the images i of class c
  8. 7return Ψ, u_1 .. u_K, Ω
  1. EIGENFACES-RECOGNIZE(Γ, θ_face, θ_class)
  2. 1ω_l ← u_lᵀ (Γ - Ψ) for l = 1 .. K
  3. 2ε ← ‖(Γ - Ψ) - Σ_l ω_l u_l‖ ▷ distance from face space
  4. 3if ε > θ_face then return "not a face"
  5. 4c ← the class with the least ‖ω - Ω_c‖
  6. 5if ‖ω - Ω_c‖ > θ_class then return "unknown"
  7. 6return c

Example

Take four training images of 2×22 \times 2 pixels, written as vectors: person a has (8,3,3,6)(8, 3, 3, 6) and (6,3,3,8)(6, 3, 3, 8), and person b has (3,9,5,3)(3, 9, 5, 3) and (3,5,9,3)(3, 5, 9, 3). The mean is Ψ=(5,5,5,5)\Psi = (5, 5, 5, 5). The small matrix of line L3 is

ATA=(1814−16−161418−16−16−16−16248−16−16824),A^T A = \begin{pmatrix} 18 & 14 & -16 & -16 \\ 14 & 18 & -16 & -16 \\ -16 & -16 & 24 & 8 \\ -16 & -16 & 8 & 24 \end{pmatrix},

with the eigenvalues 64,16,4,064, 16, 4, 0. The eigenvalue 00 comes from the fact that the four differences sum to zero. The first eigenface is u1=(0.5,−0.5,−0.5,0.5)u_1 = (0.5, -0.5, -0.5, 0.5): bright corners on one diagonal, dark on the other, which is what separates a from b. Keep K=1K = 1. All images of a get the weight 44 and those of b get −4-4, so Ωa=4\Omega_a = 4 and Ωb=−4\Omega_b = -4.

The new image (7,4,3,6)(7, 4, 3, 6) has Φ=(2,−1,−2,1)\Phi = (2, -1, -2, 1) and the weight ω=3\omega = 3. It is at distance 11 from Ωa\Omega_a and 77 from Ωb\Omega_b, so it is person a. Its distance from face space is ∥Φ−3u1∥=1\lVert \Phi - 3 u_1 \rVert = 1.

The image (5,9,9,5)(5, 9, 9, 5) has ω=−4\omega = -4, exactly Ωb\Omega_b. But its distance from face space is 44, larger than for any training image. With θface=2\theta_{\text{face}} = 2 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 ATAA^T A with λ>0\lambda > 0 gives a unit eigenvector Av/λA v / \sqrt\lambda of AATA A^T with the same eigenvalue. These vectors are orthonormal, and every positive eigenvalue of AATA A^T arises this way.
  • Theorem (rank). AATA A^T has rank at most M−1M - 1, because the differences sum to zero. So there are at most M−1M - 1 useful eigenfaces.
  • Theorem (best subspace). Among all KK-dimensional subspaces, the span of the first KK 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 ω\omega 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 MM images Γ1,…,ΓM∈RP\Gamma_1, \dots, \Gamma_M \in \mathbb R^P, each with a class label. Line L1 gives the mean Ψ\Psi, and line L2 gives Φi=Γi−Ψ\Phi_i = \Gamma_i - \Psi and the P×MP \times M matrix A=[Φ1⋯ΦM]A = [\Phi_1 \cdots \Phi_M]. The scatter matrix is S=AAT=∑iΦiΦiTS = A A^T = \sum_i \Phi_i \Phi_i^T; the covariance of Turk and Pentland is C=1MSC = \frac1M S, 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 ATAv=λvA^T A v = \lambda v with ∥v∥=1\lVert v \rVert = 1 and λ>0\lambda > 0. Then u=Av/∥Av∥u = A v / \lVert A v \rVert is a unit eigenvector of S=AATS = A A^T with the eigenvalue λ\lambda, and ∥Av∥=λ\lVert A v \rVert = \sqrt{\lambda}. If v1,…,vrv_1, \dots, v_r are orthonormal eigenvectors of ATAA^T A with positive eigenvalues, the vectors u1,…,uru_1, \dots, u_r are orthonormal. Each positive eigenvalue of SS is an eigenvalue of ATAA^T A with the same multiplicity.

Proof. S(Av)=A(ATAv)=λAvS (A v) = A (A^T A v) = \lambda A v, and ∥Av∥2=vTATAv=λ>0\lVert A v \rVert^2 = v^T A^T A v = \lambda > 0, so Av≠0A v \ne 0. For two such vectors,

uiTuj=viTATAvjλiλj=λj viTvjλiλj=δij.u_i^T u_j = \frac{v_i^T A^T A v_j}{\sqrt{\lambda_i \lambda_j}} = \frac{\lambda_j\, v_i^T v_j}{\sqrt{\lambda_i \lambda_j}} = \delta_{ij}.

In the other direction, if Su=λuS u = \lambda u with λ>0\lambda > 0, then ATA(ATu)=λATuA^T A (A^T u) = \lambda A^T u and ATu≠0A^T u \ne 0, because ∥ATu∥2=λ\lVert A^T u \rVert^2 = \lambda. The two maps v↦Avv \mapsto A v and u↦ATuu \mapsto A^T u are injective on the eigenspaces of λ\lambda, so the eigenspaces have the same dimension. □\square

So line L3 builds the M×MM \times M matrix ATAA^T A, line L4 finds its eigenpairs, and line L5 turns them into the leading eigenvectors of SS, the eigenfaces. Their eigenvalues for CC are λ/M\lambda / M.

Lemma 2 (rank)

SS has rank at most M−1M - 1, so there are at most M−1M - 1 eigenfaces with a positive eigenvalue.

Proof. ∑iΦi=∑iΓi−MΨ=0\sum_i \Phi_i = \sum_i \Gamma_i - M \Psi = 0, so the columns of AA are linearly dependent and rank⁡S=rank⁡A≤M−1\operatorname{rank} S = \operatorname{rank} A \le M - 1. □\square

The code stops at eigenvalues that are 00 up to rounding, so it returns at most M−1M - 1 eigenfaces, and with all of them it rebuilds each training image exactly (they lie in Ψ+span⁡(A)\Psi + \operatorname{span}(A)).

Lemma 3 (projection)

Let U=[u1⋯uK]U = [u_1 \cdots u_K] have orthonormal columns. For an image Γ\Gamma with Φ=Γ−Ψ\Phi = \Gamma - \Psi, the weights ω=UTΦ\omega = U^T \Phi of line L8 give the point Ψ+Uω\Psi + U \omega of the face space Ψ+span⁡(U)\Psi + \operatorname{span}(U) that is closest to Γ\Gamma, and the distance of line L9 satisfies ϵ2=∥Φ∥2−∥ω∥2\epsilon^2 = \lVert \Phi \rVert^2 - \lVert \omega \rVert^2. For two images, ∥ω−ω′∥\lVert \omega - \omega' \rVert is the distance between their projections.

Proof. UUTU U^T is the orthogonal projection onto span⁡(U)\operatorname{span}(U), so Φ−UUTΦ\Phi - U U^T \Phi is orthogonal to the span, and the Pythagorean theorem gives both the minimality and ∥Φ∥2=∥Uω∥2+ϵ2=∥ω∥2+ϵ2\lVert \Phi \rVert^2 = \lVert U \omega \rVert^2 + \epsilon^2 = \lVert \omega \rVert^2 + \epsilon^2. Also ∥Uω−Uω′∥=∥ω−ω′∥\lVert U \omega - U \omega' \rVert = \lVert \omega - \omega' \rVert because UTU=IdU^T U = \mathrm{Id}. □\square

Theorem 1 (eigenfaces are the best subspace)

Let λ1≥λ2≥⋯≥λP≥0\lambda_1 \ge \lambda_2 \ge \dots \ge \lambda_P \ge 0 be the eigenvalues of SS. For each P×KP \times K matrix QQ with orthonormal columns,

∑i=1M∥Φi−QQTΦi∥2≥∑l>Kλl,\sum_{i=1}^M \lVert \Phi_i - Q Q^T \Phi_i \rVert^2 \ge \sum_{l > K} \lambda_l,

and equality holds for the KK eigenfaces of line L5.

Proof. By Lemma 3 for each Φi\Phi_i, the left side is ∑i∥Φi∥2−∑i∥QTΦi∥2=tr⁡S−tr⁡(QTSQ)\sum_i \lVert \Phi_i \rVert^2 - \sum_i \lVert Q^T \Phi_i \rVert^2 = \operatorname{tr} S - \operatorname{tr}(Q^T S Q). Write S=∑lλlelelTS = \sum_l \lambda_l e_l e_l^T with orthonormal eigenvectors ele_l. Then

tr⁡(QTSQ)=∑lλl∥QTel∥2=∑lλlcl,cl=∥QTel∥2.\operatorname{tr}(Q^T S Q) = \sum_l \lambda_l \lVert Q^T e_l \rVert^2 = \sum_l \lambda_l c_l, \qquad c_l = \lVert Q^T e_l \rVert^2 .

Each clc_l lies in [0,1][0, 1], because QQTQ Q^T is a projection, and ∑lcl=∥Q∥F2=K\sum_l c_l = \lVert Q \rVert_F^2 = K. Under these constraints the sum ∑lλlcl\sum_l \lambda_l c_l is largest when cl=1c_l = 1 for the KK largest λl\lambda_l and 00 for the others: moving weight from a larger λ\lambda to a smaller one never increases the sum. So tr⁡(QTSQ)≤∑l≤Kλl\operatorname{tr}(Q^T S Q) \le \sum_{l \le K} \lambda_l, and the left side is at least tr⁡S−∑l≤Kλl=∑l>Kλl\operatorname{tr} S - \sum_{l \le K} \lambda_l = \sum_{l > K} \lambda_l. For Q=UQ = U, the eigenfaces, cl=1c_l = 1 for l≤Kl \le K and 00 otherwise, which gives equality. □\square

When λK=λK+1\lambda_K = \lambda_{K+1} the best subspace is not unique, and the eigenfaces are one of the best ones.

Theorem 2 (recognition)

Line L6 stores, for each class cc, the mean Ωc\Omega_c of the weight vectors of its training images. Lines L8 to L13 return "not a face" if ϵ>θface\epsilon > \theta_{\text{face}}; otherwise they return the class whose Ωc\Omega_c is nearest to ω\omega, or "unknown" if that distance is above θclass\theta_{\text{class}}.

Proof. Line L8 computes ω\omega and line L9 the distance ϵ\epsilon 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. □\square

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 O(M3)O(M^3) 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 O(M3)O(M^3) each.

  • Training. Line L3 costs O(M2P)O(M^2 P), line L4 O(M3)O(M^3), line L5 O(KMP)O(K M P) and line L6 O(MKP)O(M K P). With K<MK < M, the total is O(M2P+M3)O(M^2 P + M^3). The extra space is O(MP)O(MP) for AA and the eigenfaces and O(M2)O(M^2) for ATAA^T A.
  • The direct way. The P×PP \times P matrix AATA A^T costs O(P2M)O(P^2 M) to build, O(P2)O(P^2) space and O(P3)O(P^3) to decompose. For 256×256256 \times 256 images, P=65536P = 65536, and P2P^2 is over 4 billion entries. The small matrix trick makes the method practical when M≪PM \ll P.
  • A thin SVD of AA gives the same eigenfaces in O(PM2)O(P M^2) time and is better conditioned, because it does not square the singular values. See singular value decomposition.
  • Recognition. Line L8 costs O(KP)O(KP), line L9 O(KP)O(KP), and the search of line L11 O(KC)O(K C) for CC classes, which is at most O(KM)O(KM).

Properties

  • Linear and fast. A query costs KK dot products with images, plus a search over KK-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 Γ−Ψ\Gamma - \Psi, not Γ\Gamma.
  • Normalizing AvA v. ∥Av∥=λ\lVert A v \rVert = \sqrt\lambda, not 11. Without the division the weights have the wrong scale.
  • Zero eigenvalues. At most M−1M - 1 eigenvalues are positive. An eigenvector of a zero eigenvalue gives Av=0A v = 0, which cannot be normalized.
  • Squaring. Forming ATAA^T A squares the condition number. A thin SVD of AA avoids that.
  • Thresholds. θface\theta_{\text{face}} and θclass\theta_{\text{class}} 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.

cvla.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example