Algorithmadvanced
Coherent point drift
Also called CPD.
Registers two point sets by fitting one as the centroids of a Gaussian mixture to the other with EM. It has rigid, affine and non-rigid forms; the non-rigid form keeps the motion smooth.
- Time
- Θ(N K n) worst · averageΘ(K n) best
- Space
- Θ(K n) extra
- Where
- K = the number of centroids; N = the number of iterations; n = the number of data points
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Andriy Myronenko, Xubo Song, Miguel Á. Carreira Perpiñán, 2010
Coherent point drift (CPD) registers two point sets by treating one of them as a Gaussian mixture model. The points of the moving set are the centroids of the mixture, all with the same variance , and the points of the fixed set are the data. CPD moves the centroids so that the mixture explains the data as well as possible, by the expectation maximization (EM) algorithm. The E-step computes soft correspondences: for each data point, the probability that each centroid produced it. The M-step computes the transformation that best fits these weighted pairs, in closed form for a rigid motion with scale and for an affine map. A third form allows a smooth deformation, and so solves the non-rigid registration problem. A uniform component of weight absorbs outliers. Each iteration does not increase the negative log-likelihood, but, like iterative closest point, CPD is a local method.
In plain words
Put a soft, round cloud of fog around each point of the first set. Now look at the second set. Each of its points asks every fog cloud: how likely is it that I came from you? Near clouds get a large share of the point, far clouds get almost nothing.
With these shares fixed, find the turn, slide and stretch of the first set that makes the shares fit best. Move the first set. Then make the fog clouds a little smaller, because the sets now match better, and ask again.
At first the fog is wide, so every point pulls a little on every other point, and small details do not matter. As the fog shrinks, the matches become sharp. A point of the second set that is far from every cloud is counted as noise and pulls on nothing.
The problem
Input. A fixed set and a moving set in , with and ; an outlier weight ; and a family of transformations . (The paper writes for and for .)
Output. A transformation and a variance at a stationary point of the EM iteration for the likelihood of under the mixture
For the rigid form, with , a scale and a translation . For the affine form, with any matrix . For the non-rigid form, , where is the Gaussian kernel matrix and is a matrix of coefficients. The non-rigid form also adds the penalty to the negative log-likelihood, which is the motion coherence prior: it makes nearby centroids move together. CPD does not promise the global maximum of the likelihood. The problem is a form of point cloud registration with soft correspondences.
The algorithm
In the E-step, the posterior that data point comes from centroid is
The constant comes from the uniform component. A point far from every centroid gets small values for all , so it has little effect on the M-step. Below, is a vector of ones, is the diagonal matrix of a vector , is the matrix of the data and is the matrix of the centroids. The pseudocode is the rigid form.
CPD-RIGID(X, Y, w, tol) ▷ X = (x_1 .. x_n), Y = (y_1 .. y_K), in R^D- 1
R ← I ; s ← 1 ; t ← 0 ; σ² ← (1/(D n K)) Σ_k Σ_i |x_i - y_k|² - 2
repeat (up to an iteration cap) - 3
P_ki ← E-step with T(y) = s R y + t ; E ← -Σ_i log p(x_i) - 4
if E_prev - E ≤ tol · max(1, |E|) or σ² ≤ σ²_min then exit the loop - 5
N_P ← 1ᵀ P 1 ; μ_x ← Xᵀ Pᵀ 1 / N_P ; μ_y ← Yᵀ P 1 / N_P ; X̂ ← X - 1 μ_xᵀ ; Ŷ ← Y - 1 μ_yᵀ - 6
A ← X̂ᵀ Pᵀ Ŷ ; U Σ Vᵀ ← SVD(A) - 7
R ← U diag(1, .., 1, det(U Vᵀ)) Vᵀ ; s ← tr(Aᵀ R) / tr(Ŷᵀ d(P 1) Ŷ) ; t ← μ_x - s R μ_y - 8
σ² ← (tr(X̂ᵀ d(Pᵀ 1) X̂) - 2 s tr(Aᵀ R) + s² tr(Ŷᵀ d(P 1) Ŷ)) / (N_P D) - 9
return R, s, t
Line L1 starts at the identity, with a large variance: the mean squared distance over all pairs, divided by . Line L3 is the E-step; it also gives the negative log-likelihood of the current parameters at no extra cost, because the denominators of are the mixture densities up to a constant. Line L4 stops when no longer falls by more than a relative tol, or when reaches a floor. Lines L5 to L8 are the M-step. Line L5 computes the weighted means and centers both sets. Line L6 forms the weighted cross-covariance and its SVD. Line L7 is the weighted form of the Kabsch algorithm with the sign fix of Umeyama, followed by the best scale and translation. Line L8 is the best variance for the new pose. With the scale fixed to 1, line L7 skips the scale, and line L8 keeps the same formula with . The paper writes line L8 as , which is the same value when is the optimal scale.
The other forms change only lines L5 to L8.
- Affine. , and .
- Non-rigid. Solve for , set , and set . The reference code multiplies the linear system by , which gives and avoids a division by a small entry of .
The width of the kernel sets how far the motion of one centroid spreads to its neighbors, and sets how much the method prefers smooth motion to a close fit. Both are tuning values that the user must choose.
Example
Take the moving set , , , in the plane. The data are the same points turned by 60 degrees and moved by : , , , . Run rigid CPD with scale, . The start variance is . With this wide variance the first E-step spreads each point over all centroids; for example, gives the weights 0.379, 0.148, 0.237 and 0.237 to .
| M-steps | angle of | after the step | ||
|---|---|---|---|---|
| 0 | 0 | 1 | 1.0647 | 10.5804 |
| 1 | 12.31° | 0.3778 | 0.4206 | 8.3821 |
| 2 | 30.97° | 0.3761 | 0.4058 | 8.2040 |
| 3 | 46.52° | 0.4534 | 0.3728 | 7.9732 |
| 4 | 55.16° | 0.5869 | 0.3040 | 7.5036 |
| 5 | 58.75° | 0.7437 | 0.2004 | 6.4142 |
| 6 | 59.38° | 0.8986 | 0.0821 | 3.1250 |
| 7 | 59.95° | 0.9973 | 0.00226 | -11.4655 |
| 8 | 60.00° | 1.0000 | (the floor) | -97.6274 |
The negative log-likelihood falls at every step. The scale first drops to about 0.38: with a wide variance, every data point pulls on every centroid, so the best fit squeezes the moving set toward the weighted mean. As falls, the soft matches become sharp, the scale returns to 1, and the eighth M-step gives the exact pose. The data fit exactly, so goes to 0 and the code stops at its floor .
CPD is local. With the same four points and the scale fixed to 1, a true rotation of 90 degrees ends at 32.6 degrees, and a true rotation of 150 degrees ends at -30.1 degrees. Both are stationary points of EM that are not the truth.
Correctness
Claim: each iteration does not increase the negative log-likelihood , provided , and the new . The proof has two parts. First, the EM bound: by Jensen's inequality, , where uses the posteriors of the old parameters. Second, lines L5 to L8 minimize exactly. The translation drops out by centering. For a fixed scale, the rotation must maximize over , which the SVD with the sign fix does (Umeyama's theorem). The scale and the variance then have closed forms. The affine M-step is a least squares solve. The non-rigid M-step minimizes a convex function of and then , so it is a generalized EM step, and the bound holds for plus the penalty. The full proof is in proofs/correctness.md. The claim does not give the global maximum of the likelihood, and it does not bound the number of iterations.
Proof: Each CPD iteration does not increase the negative log-likelihoodfull
We use the notation of the page. The data points are and the centroids are , all in . For a transformation and a variance , the mixture density is
with a fixed outlier weight . The negative log-likelihood is . We assume exact arithmetic.
Claim. Let be the parameters before one iteration of the rigid loop (lines L3 to L8) and the parameters after it. If the weight sum is positive, the new scale is positive and the new variance is positive, then . The same holds for the affine M-step, and for the non-rigid M-step when is replaced by and is positive definite.
Lemma 1 (the EM bound). Fix the old parameters and let be the posteriors of line L3, that is evaluated at , and for the outlier component. Define
Then for every .
Proof. For each , the posteriors are positive and sum to 1. Write for the term of component in , so and . By the concavity of the logarithm (Jensen's inequality),
The outlier term does not depend on , so its log ratio is 0. For , . Sum over and change the sign. The constants cancel, and what is left is .
So any step that does not increase does not increase . It remains to show that each M-step does not increase .
Lemma 2 (the rigid M-step). Lines L5 to L8 return a global minimizer of over , , and , when , the new is positive and the new is positive.
Proof. Fix and . The sum is a convex quadratic in . Its gradient is zero at , with the weighted means of line L5, so this is optimal for every and . Put it in. With the centered points and , the sum becomes
because . For every fixed , is least when is greatest. With the SVD , the maximum of over is attained at with . This is the theorem of Umeyama (1991), proved on the Kabsch algorithm page. Line L7 computes this , and it does not depend on . For this , is a quadratic in with a positive leading term, least at , which is the of line L7. (With the scale fixed to 1, this step is skipped and is the only choice.) Finally, for a fixed value , the function has the derivative , which is negative below and positive above it. Line L8 sets with the least value of . For every fixed , increases with , so no other choice of gives a smaller .
Lemma 3 (the affine M-step). The step , , minimizes over all , and , when is invertible.
Proof. The translation is eliminated as in Lemma 2. What is left, , is a convex quadratic in whose gradient vanishes at the stated . The variance step is as in Lemma 2.
Lemma 4 (the non-rigid M-step). Let be positive definite and let be fixed. The that solves minimizes over .
Proof. The function is plus a constant. It is convex in : the first part is a convex quadratic of the linear map , and the second part is convex because is positive semidefinite. Its gradient is . The stated makes the bracket zero, so the gradient is zero, and a stationary point of a convex function is a global minimizer.
The non-rigid loop then sets to the minimizer for the new , as in Lemma 2. Two steps that each do not increase give a total step that does not increase it. The penalty does not depend on or on , so Lemma 1 holds with the penalty added to both and .
Proof of the claim. The old parameters are one candidate of each M-step, so by Lemmas 2, 3 and 4, (with the penalty in the non-rigid case). By Lemma 1, .
What the claim does not say. The values of do not increase, and they are bounded below while stays away from 0, so they converge. This does not mean that the parameters converge to the global minimum of . EM can stop at a local minimum or a saddle point, and the result depends on the start, as the example on the page shows. When the data fit exactly, goes to 0 and goes to ; the code stops at the floor sigma2_min.
Floating point. The code computes the sums of line L3 with a shift by the least squared distance, so the posteriors are finite even when all the Gaussian terms underflow. The tests check the nonincreasing property with a relative slack of .
Complexity
The model is the real RAM, and is a constant. Line L3 computes squared distances and exponentials, time. Lines L5 and L6 compute the row sums, the column sums and , also , and the SVD of the matrix takes time. So a rigid or affine iteration takes time, and iterations take . The best case stops after the second E-step, . The matrix needs extra space; an implementation that never stores can make two passes over the pairs and use space.
The non-rigid form also forms in time and solves a dense system in each iteration, by Gaussian elimination, so an iteration takes time and space. The paper lowers these costs with the fast Gauss transform for the sums of line L3 and a low-rank approximation of ; these are approximations with their own error. The number of iterations has no useful bound. EM usually converges linearly, and the rate gets worse when the mixture components overlap much.
Properties
- Monotone. The negative log-likelihood (plus the penalty in the non-rigid form) never increases.
- Local. The result depends on the start. The example has wrong stationary points at 90 and 150 degrees.
- Soft correspondences. No hard nearest neighbor decision is made. Every pair has a weight, which makes the cost smooth in the parameters.
- Coarse to fine without a schedule. The variance is estimated, not set. It starts large and shrinks as the fit improves, which gives a coarse-to-fine search similar to the annealing of robust point matching, but driven by the data.
- Robust to outliers in X. The uniform component with weight gives a data point far from all centroids a small total weight.
- Not symmetric. and play different roles: every centroid is a mixture component, but data points can be outliers.
- Deterministic. The same input gives the same output.
Variants and improvements
- Fast sums. The paper uses the fast Gauss transform for the E-step and a low-rank approximation of for the non-rigid solve, which makes large sets practical.
- Other kernels and priors. The motion coherence prior uses a Gaussian kernel. Other kernels, such as the thin plate spline kernel of robust point matching, give other kinds of smooth motion.
- Fixed scale. Rigid CPD without scale is a probabilistic form of ICP with soft matches. As , each posterior becomes a hard match to the closest centroid.
- Features. The posteriors can be multiplied by a feature similarity, so that points with different colors or descriptors do not match.
- Bayesian forms. Later work gives a Bayesian form of CPD with a prior on the transformation and a variational EM; it is outside this page.
When to use it
Use CPD for small and medium point sets with noise and some outliers when a rough start is known. It is a good default for non-rigid registration of shapes such as contours, faces or organs, where the motion is smooth. For the rigid case on large clouds, ICP with a k-d tree is cheaper, because CPD looks at all pairs in each iteration unless the fast sums are used. Without a rough start, use a global method first, such as fast global registration or TEASER. When most of has no partner in , the model is wrong: every centroid is a component that must explain some data, so the outlier term protects only against extra points in .
Pitfalls
- The roles of X and Y. moves and is the mixture; is the data and may hold outliers. Swapping them changes the result and the meaning of .
- A wrong sign in line L7. Without , the rotation can be a reflection.
- Underflow in line L3. When is small, all terms of a column can underflow to 0, and the posterior becomes 0/0. Shift each column by its least squared distance before the exponential, as the reference code does.
- Sigma squared reaching zero. On exact data and . Use a floor and stop there.
- Shrinking scale. In the first iterations, the rigid form with scale can shrink by a large factor, as in the example. It recovers on good data, but with many outliers it can stay small. Fix the scale if it is known.
- Choice of w, beta and lambda. These are tuning values. A that is too large makes CPD ignore real points; a small or lets the non-rigid form overfit noise.
- Units. , and the outlier constant depend on the units. Normalize both sets to zero mean and unit variance first, and undo the normalization after.
Implementations
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
# Part of https://algorithm.tamnd.com/coherent-point-drift/. The authors are listed in prov/HWYJKB.jsonl.
"""Coherent point drift (CPD) of Myronenko and Song, 2010.
The moving set Y = [y_1, ..., y_K] gives the centroids of a Gaussian
mixture with one shared isotropic variance sigma2. The fixed set X = [x_1,
..., x_n] holds the data points. (The paper writes M for K and N for n; the
code keeps the paper's letters M and N as variable names.) A uniform
component of weight w models outliers. EM alternates two steps:
- E-step: the posterior P[k][i] that the point x_i comes from the centroid
T(y_k).
- M-step: the transformation T and sigma2 that maximize the expected
complete log-likelihood for this P.
Three kinds of T are given: rigid with scale (R, s, t), affine (B, t), and
non-rigid T(Y) = Y + G W with a Gaussian kernel matrix G and a penalty
(lam / 2) tr(W^T G W) on the motion field. All points are in R^D for any
D >= 1. Each iteration costs Theta(K n D) for the E-step; the non-rigid
M-step adds a dense K x K solve, Theta(K^3).
Every fit returns the negative log-likelihood of each iteration (plus the
penalty in the non-rigid case). EM makes this list nonincreasing.
"""
from __future__ import annotations
import math
from typing import Dict, List, Optional, Sequence, Tuple
from cvla import det, mul, solve, svd, transpose
Matrix = List[List[float]]
Vector = List[float]
def _d2(a: Sequence[float], b: Sequence[float]) -> float:
return sum((p - q) * (p - q) for p, q in zip(a, b))
def initial_sigma2(X: Sequence[Sequence[float]], TY: Sequence[Sequence[float]]) -> float:
"""sigma2 = (1 / (D N M)) sum_{m, n} |x_n - T(y_m)|^2, the start value."""
N, M, D = len(X), len(TY), len(X[0])
return sum(_d2(x, y) for x in X for y in TY) / (D * N * M)
def e_step(X: Sequence[Sequence[float]], TY: Sequence[Sequence[float]],
sigma2: float, w: float) -> Tuple[Matrix, float]:
"""The posterior matrix P (M rows, N columns) and the negative
log-likelihood of X under the mixture with centroids TY.
P[m][n] = exp(-|x_n - T(y_m)|^2 / (2 sigma2)) / (sum_k exp(...) + c),
with c = (2 pi sigma2)^(D/2) (w / (1 - w)) (M / N). The sums are done
with a shift by the least distance, so no column underflows to 0 / 0."""
N, M, D = len(X), len(TY), len(X[0])
if not 0.0 <= w < 1.0:
raise ValueError("w must be in [0, 1)")
if w > 0.0:
log_c = 0.5 * D * math.log(2.0 * math.pi * sigma2) + math.log(w / (1.0 - w)) + math.log(M / N)
else:
log_c = -math.inf
base = math.log((1.0 - w) / M) - 0.5 * D * math.log(2.0 * math.pi * sigma2)
P = [[0.0] * N for _ in range(M)]
nll = 0.0
for n, x in enumerate(X):
d2 = [_d2(x, y) for y in TY]
dmin = min(d2)
e = [math.exp(-(d - dmin) / (2.0 * sigma2)) for d in d2]
log_sum = math.log(sum(e))
lc = log_c + dmin / (2.0 * sigma2)
hi, lo = max(log_sum, lc), min(log_sum, lc)
log_den = hi + math.log1p(math.exp(lo - hi)) if lo > -math.inf else hi
for m in range(M):
P[m][n] = math.exp(-(d2[m] - dmin) / (2.0 * sigma2) - log_den)
nll -= base - dmin / (2.0 * sigma2) + log_den
return P, nll
def _sums(P: Matrix) -> Tuple[Vector, Vector, float]:
P1 = [sum(row) for row in P]
Pt1 = [sum(col) for col in zip(*P)]
return P1, Pt1, sum(P1)
def _centered(X, Y, P1, Pt1, Np):
D = len(X[0])
mux = [sum(Pt1[n] * X[n][d] for n in range(len(X))) / Np for d in range(D)]
muy = [sum(P1[m] * Y[m][d] for m in range(len(Y))) / Np for d in range(D)]
Xh = [[x[d] - mux[d] for d in range(D)] for x in X]
Yh = [[y[d] - muy[d] for d in range(D)] for y in Y]
return mux, muy, Xh, Yh
def _cross_cov(P: Matrix, Xh: Matrix, Yh: Matrix) -> Matrix:
"""A = Xh^T P^T Yh, a D x D matrix."""
D = len(Xh[0])
PXh = [[sum(row[n] * Xh[n][d] for n in range(len(Xh))) for d in range(D)] for row in P]
return [[sum(PXh[m][i] * Yh[m][j] for m in range(len(Yh))) for j in range(D)] for i in range(D)]
def _apply_rigid(R, s, t, Y):
return [[s * sum(R[i][k] * y[k] for k in range(len(y))) + t[i] for i in range(len(t))] for y in Y]
def _converged(hist: List[float], tol: float) -> bool:
return len(hist) >= 2 and hist[-2] - hist[-1] <= tol * max(1.0, abs(hist[-1]))
def cpd_rigid(X: Sequence[Sequence[float]], Y: Sequence[Sequence[float]],
w: float = 0.0, scale: bool = True, max_iter: int = 200,
tol: float = 1e-10, sigma2_min: float = 1e-12) -> Dict[str, object]:
"""Rigid CPD: find R (det R = +1), s > 0 and t so that s R y_m + t fit X.
With scale=False, s stays 1. Returns a dict with "R", "s", "t",
"sigma2", "P" (the last posterior), "TY" (the moved Y) and "nll" (the
negative log-likelihood at the start of each iteration)."""
D = len(X[0])
R = [[1.0 if i == j else 0.0 for j in range(D)] for i in range(D)] # @line L1
s, t = 1.0, [0.0] * D
TY = [list(map(float, y)) for y in Y]
sigma2 = initial_sigma2(X, TY)
hist: List[float] = []
P: Matrix = []
for _ in range(max_iter): # @line L2
P, nll = e_step(X, TY, sigma2, w) # @line L3
hist.append(nll)
if _converged(hist, tol) or sigma2 <= sigma2_min: # @line L4
break
P1, Pt1, Np = _sums(P) # @line L5
mux, muy, Xh, Yh = _centered(X, Y, P1, Pt1, Np)
A = _cross_cov(P, Xh, Yh) # @line L6
U, _, V = svd(A)
C = [[1.0 if i == j else 0.0 for j in range(D)] for i in range(D)]
C[D - 1][D - 1] = 1.0 if det(mul(U, transpose(V))) > 0.0 else -1.0
R = mul(mul(U, C), transpose(V)) # @line L7
trAR = sum(A[i][j] * R[i][j] for i in range(D) for j in range(D))
yPy = sum(P1[m] * sum(v * v for v in Yh[m]) for m in range(len(Y)))
xPx = sum(Pt1[n] * sum(v * v for v in Xh[n]) for n in range(len(X)))
s = trAR / yPy if scale else 1.0
t = [mux[i] - s * sum(R[i][k] * muy[k] for k in range(D)) for i in range(D)]
sigma2 = (xPx - 2.0 * s * trAR + s * s * yPy) / (Np * D) # @line L8
sigma2 = max(sigma2, sigma2_min)
TY = _apply_rigid(R, s, t, Y)
return {"R": R, "s": s, "t": t, "sigma2": sigma2, "P": P, "TY": TY, "nll": hist} # @line L9
def cpd_affine(X: Sequence[Sequence[float]], Y: Sequence[Sequence[float]],
w: float = 0.0, max_iter: int = 200, tol: float = 1e-10,
sigma2_min: float = 1e-12) -> Dict[str, object]:
"""Affine CPD: find B and t so that B y_m + t fit X. The M-step is
B = (Xh^T P^T Yh)(Yh^T d(P1) Yh)^-1 and t = mu_x - B mu_y."""
D = len(X[0])
B = [[1.0 if i == j else 0.0 for j in range(D)] for i in range(D)]
t = [0.0] * D
TY = [list(map(float, y)) for y in Y]
sigma2 = initial_sigma2(X, TY)
hist: List[float] = []
for _ in range(max_iter):
P, nll = e_step(X, TY, sigma2, w)
hist.append(nll)
if _converged(hist, tol) or sigma2 <= sigma2_min:
break
P1, Pt1, Np = _sums(P)
mux, muy, Xh, Yh = _centered(X, Y, P1, Pt1, Np)
A = _cross_cov(P, Xh, Yh)
YdY = [[sum(P1[m] * Yh[m][i] * Yh[m][j] for m in range(len(Y))) for j in range(D)] for i in range(D)]
B = transpose(solve(YdY, transpose(A)))
xPx = sum(Pt1[n] * sum(v * v for v in Xh[n]) for n in range(len(X)))
trAB = sum(A[i][j] * B[i][j] for i in range(D) for j in range(D))
t = [mux[i] - sum(B[i][k] * muy[k] for k in range(D)) for i in range(D)]
sigma2 = max((xPx - trAB) / (Np * D), sigma2_min)
TY = _apply_rigid(B, 1.0, t, Y)
return {"B": B, "t": t, "sigma2": sigma2, "TY": TY, "nll": hist}
def gaussian_kernel(Y: Sequence[Sequence[float]], beta: float) -> Matrix:
"""G[i][j] = exp(-|y_i - y_j|^2 / (2 beta^2))."""
return [[math.exp(-_d2(a, b) / (2.0 * beta * beta)) for b in Y] for a in Y]
def cpd_nonrigid(X: Sequence[Sequence[float]], Y: Sequence[Sequence[float]],
beta: float = 2.0, lam: float = 2.0, w: float = 0.0,
max_iter: int = 100, tol: float = 1e-8,
sigma2_min: float = 1e-12) -> Dict[str, object]:
"""Non-rigid CPD: T(Y) = Y + G W. The M-step solves
(d(P1) G + lam sigma2 I) W = P X - d(P1) Y, the form of the paper's
equation multiplied by d(P1), so no entry of P1 is divided by. The
list "nll" holds the negative log-likelihood plus (lam / 2) tr(W^T G W)."""
M, D = len(Y), len(X[0])
G = gaussian_kernel(Y, beta)
W = [[0.0] * D for _ in range(M)]
TY = [list(map(float, y)) for y in Y]
sigma2 = initial_sigma2(X, TY)
hist: List[float] = []
for _ in range(max_iter):
P, nll = e_step(X, TY, sigma2, w)
GW = mul(G, W)
pen = 0.5 * lam * sum(W[m][d] * GW[m][d] for m in range(M) for d in range(D))
hist.append(nll + pen)
if _converged(hist, tol) or sigma2 <= sigma2_min:
break
P1, Pt1, Np = _sums(P)
PX = [[sum(row[n] * X[n][d] for n in range(len(X))) for d in range(D)] for row in P]
lhs = [[P1[i] * G[i][j] + (lam * sigma2 if i == j else 0.0) for j in range(M)] for i in range(M)]
rhs = [[PX[m][d] - P1[m] * Y[m][d] for d in range(D)] for m in range(M)]
W = solve(lhs, rhs)
GW = mul(G, W)
TY = [[Y[m][d] + GW[m][d] for d in range(D)] for m in range(M)]
xPx = sum(Pt1[n] * sum(v * v for v in X[n]) for n in range(len(X)))
cross = sum(PX[m][d] * TY[m][d] for m in range(M) for d in range(D))
tPt = sum(P1[m] * sum(v * v for v in TY[m]) for m in range(M))
sigma2 = max((xPx - 2.0 * cross + tPt) / (Np * D), sigma2_min)
return {"W": W, "G": G, "TY": TY, "sigma2": sigma2, "nll": hist}
cvla.py 494 lines
# 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()
test_coherent_point_drift.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/coherent-point-drift/. The authors are listed in prov/HWYJKB.jsonl.
import math
import random
import unittest
from cvla import det, mul, transpose
from coherent_point_drift import (cpd_affine, cpd_nonrigid, cpd_rigid, e_step,
gaussian_kernel, initial_sigma2)
def rotation(axis, angle):
"""Rotation by angle (radians) about axis, by the Rodrigues formula."""
n = math.sqrt(sum(a * a for a in axis))
x, y, z = (a / n for a in axis)
c, s = math.cos(angle), math.sin(angle)
d = 1.0 - c
return [[c + x * x * d, x * y * d - z * s, x * z * d + y * s],
[y * x * d + z * s, c + y * y * d, y * z * d - x * s],
[z * x * d - y * s, z * y * d + x * s, c + z * z * d]]
def rot_angle(R1, R2):
m = mul(transpose(R1), R2)
c = (m[0][0] + m[1][1] + m[2][2] - 1.0) / 2.0
s = 0.5 * math.sqrt((m[2][1] - m[1][2]) ** 2 + (m[0][2] - m[2][0]) ** 2 + (m[1][0] - m[0][1]) ** 2)
return math.atan2(s, c)
def cloud(rng, n, d=3):
return [[rng.uniform(-1.0, 1.0) for _ in range(d)] for _ in range(n)]
def move(R, s, t, Y):
return [[s * sum(R[i][k] * y[k] for k in range(len(y))) + t[i] for i in range(len(t))] for y in Y]
def nonincreasing(hist, rel=1e-9):
return all(b <= a + rel * max(1.0, abs(a)) for a, b in zip(hist, hist[1:]))
class TestEStep(unittest.TestCase):
def test_columns_sum_to_one_without_outliers(self):
rng = random.Random(1)
X, Y = cloud(rng, 12), cloud(rng, 9)
P, _ = e_step(X, Y, 0.3, 0.0)
for n in range(12):
self.assertAlmostEqual(sum(P[m][n] for m in range(9)), 1.0, places=12)
def test_matches_direct_formula(self):
rng = random.Random(2)
X, Y = cloud(rng, 7), cloud(rng, 5)
sigma2, w, D = 0.4, 0.25, 3
P, nll = e_step(X, Y, sigma2, w)
c = (2 * math.pi * sigma2) ** (D / 2) * w / (1 - w) * 5 / 7
ref_nll = 0.0
for n, x in enumerate(X):
e = [math.exp(-sum((a - b) ** 2 for a, b in zip(x, y)) / (2 * sigma2)) for y in Y]
for m in range(5):
self.assertAlmostEqual(P[m][n], e[m] / (sum(e) + c), places=12)
p = w / 7 + (1 - w) / 5 * (2 * math.pi * sigma2) ** (-D / 2) * sum(e)
ref_nll -= math.log(p)
self.assertAlmostEqual(nll, ref_nll, places=9)
def test_far_point_does_not_underflow(self):
X = [[0.0, 0.0], [1000.0, 0.0]]
Y = [[0.0, 0.0], [0.1, 0.0]]
P, nll = e_step(X, Y, 1e-4, 0.1)
self.assertTrue(math.isfinite(nll))
self.assertTrue(all(math.isfinite(v) for row in P for v in row))
self.assertLess(P[0][1] + P[1][1], 1e-12)
class TestRigid(unittest.TestCase):
def test_exact_recovery(self):
rng = random.Random(3)
Y = cloud(rng, 30)
R0 = rotation([1.0, 2.0, -0.5], math.radians(50))
s0, t0 = 1.3, [0.4, -0.2, 0.3]
X = move(R0, s0, t0, Y)
rng.shuffle(X)
out = cpd_rigid(X, Y)
self.assertLess(rot_angle(out["R"], R0), 1e-5)
self.assertAlmostEqual(out["s"], s0, places=5)
for a, b in zip(out["t"], t0):
self.assertAlmostEqual(a, b, places=5)
self.assertAlmostEqual(det(out["R"]), 1.0, places=12)
def test_without_scale(self):
rng = random.Random(4)
Y = cloud(rng, 25)
R0 = rotation([0.0, 0.0, 1.0], math.radians(35))
X = move(R0, 1.0, [0.1, 0.2, 0.0], Y)
out = cpd_rigid(X, Y, scale=False)
self.assertEqual(out["s"], 1.0)
self.assertLess(rot_angle(out["R"], R0), 1e-5)
def test_noise_and_outliers(self):
rng = random.Random(5)
Y = cloud(rng, 40)
R0 = rotation([0.3, -1.0, 0.4], math.radians(40))
t0 = [0.2, 0.1, -0.3]
X = [[v + rng.gauss(0.0, 0.01) for v in p] for p in move(R0, 1.0, t0, Y)]
X += [[rng.uniform(-2.0, 2.0) for _ in range(3)] for _ in range(15)]
out = cpd_rigid(X, Y, w=0.3, scale=False)
self.assertLess(rot_angle(out["R"], R0), math.radians(1.0))
self.assertTrue(nonincreasing(out["nll"]))
def test_likelihood_never_rises(self):
rng = random.Random(6)
Y = cloud(rng, 20)
X = [[v + rng.gauss(0.0, 0.05) for v in p]
for p in move(rotation([1.0, 1.0, 1.0], 0.6), 0.9, [0.3, 0.0, 0.1], Y)]
out = cpd_rigid(X, Y, w=0.1)
self.assertGreater(len(out["nll"]), 5)
self.assertTrue(nonincreasing(out["nll"]))
def test_two_dimensions(self):
rng = random.Random(7)
Y = cloud(rng, 20, 2)
a = math.radians(30)
R0 = [[math.cos(a), -math.sin(a)], [math.sin(a), math.cos(a)]]
X = move(R0, 1.0, [0.5, -0.5], Y)
out = cpd_rigid(X, Y)
self.assertAlmostEqual(out["R"][1][0], math.sin(a), places=5)
self.assertAlmostEqual(out["s"], 1.0, places=5)
def test_initial_sigma2(self):
X = [[0.0, 0.0], [2.0, 0.0]]
Y = [[0.0, 1.0]]
self.assertAlmostEqual(initial_sigma2(X, Y), (1.0 + 5.0) / (2 * 2 * 1))
class TestAffine(unittest.TestCase):
def test_exact_recovery(self):
rng = random.Random(8)
Y = cloud(rng, 30)
B0 = [[1.1, 0.2, 0.0], [-0.1, 0.9, 0.15], [0.05, 0.0, 1.2]]
t0 = [0.1, -0.1, 0.2]
X = move(B0, 1.0, t0, Y)
out = cpd_affine(X, Y)
for i in range(3):
for j in range(3):
self.assertAlmostEqual(out["B"][i][j], B0[i][j], places=4)
self.assertTrue(nonincreasing(out["nll"]))
class TestNonRigid(unittest.TestCase):
def test_kernel(self):
G = gaussian_kernel([[0.0], [1.0]], 1.0)
self.assertAlmostEqual(G[0][1], math.exp(-0.5))
self.assertEqual(G[0][0], 1.0)
def test_objective_never_rises_and_fit_improves(self):
rng = random.Random(9)
Y = [[math.cos(2 * math.pi * k / 20), math.sin(2 * math.pi * k / 20)] for k in range(20)]
X = [[y[0] + 0.15 * math.sin(3 * y[1]), y[1] + 0.1 * y[0] * y[0]] for y in Y]
X = [[v + rng.gauss(0.0, 0.005) for v in p] for p in X]
out = cpd_nonrigid(X, Y, beta=1.0, lam=1.0)
self.assertTrue(nonincreasing(out["nll"]))
before = sum(min(sum((a - b) ** 2 for a, b in zip(x, y)) for y in Y) for x in X)
after = sum(min(sum((a - b) ** 2 for a, b in zip(x, y)) for y in out["TY"]) for x in X)
self.assertLess(after, 0.1 * before)
if __name__ == "__main__":
unittest.main()
History
Myronenko, Song and Carreira-Perpiñán presented the non-rigid method at NIPS in 2006. Myronenko and Song published the full method in IEEE TPAMI in 2010, with the rigid, affine and non-rigid forms, the uniform outlier term and fast implementations. The non-rigid prior follows the motion coherence theory of Yuille and Grzywacz, which asks that nearby points move together. Earlier methods that also used soft correspondences include the softassign method of Gold, Rangarajan and others (1998), and its thin plate spline form by Chui and Rangarajan (2003), see robust point matching. The EM algorithm itself is due to Dempster, Laird and Rubin (1977).
References
- Andriy Myronenko and Xubo Song, Point set registration: Coherent point drift, IEEE Transactions on Pattern Analysis and Machine Intelligence 32(12), 2010, 2262-2275, The Gaussian mixture model with the uniform outlier term, the E-step, and the closed-form M-steps of the rigid, affine and non-rigid forms; the motion coherence prior and the fast Gauss transform and low-rank speed-ups
- A. P. Dempster, N. M. Laird and D. B. Rubin, Maximum likelihood from incomplete data via the EM algorithm, Journal of the Royal Statistical Society, Series B 39(1), 1977, 1-38, The EM algorithm and the proof that each iteration does not decrease the likelihood
- Shinji Umeyama, Least-squares estimation of transformation parameters between two point patterns, IEEE Transactions on Pattern Analysis and Machine Intelligence 13(4), 1991, 376-380, The main theorem: the best rotation and scale by the SVD, with the sign of the determinant, used in the rigid M-step
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 HWYJKB Edit this page History Report an error Markdown