Algorithmadvanced
MLESAC
Also called maximum likelihood estimation sample consensus.
RANSAC that scores each model by the likelihood of a mixture of Gaussian inliers and uniform outliers; for each model, EM estimates only the mixing weight.
- Solves
- Robust model fitting
- Time
- Θ(k m n) worst · average · best
- Space
- Θ(n) extra
- Where
- k = the number of samples drawn, at most a set cap; m = the number of EM steps for each model; n = the number of data items
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Philip H. S. Torr, Andrew Zisserman, 2000
MLESAC (maximum likelihood estimation sample consensus) is a variant of RANSAC that scores a model by a likelihood instead of an inlier count. It models the residual of an item as a mixture: with probability the item is an inlier, and its residual is Gaussian with a known standard deviation ; with probability it is an outlier, and its residual is uniform on a range of size . For each model from a minimal sample, a few steps of expectation maximization estimate the mixing weight , and nothing else, because the model itself is fixed by the sample. The model of largest likelihood wins. Torr and Zisserman (2000) introduced MLESAC together with MSAC, which uses a truncated quadratic instead.
In plain words
RANSAC and MSAC need a hard limit that splits points into good and bad. MLESAC uses a softer rule. It says: a good point is near the guess, with small errors much more likely than large ones; a bad point can be anywhere in the picture with the same chance. Each point then gets a degree of belief that it is good.
Before a guess can be scored, MLESAC must know what fraction of the points are good. It does not know, so it starts at one half and improves the fraction a few times: it computes the belief of each point and takes their average as the new fraction.
The score of the guess is how well this mix of good and bad points explains all the points at once. The guess with the best score wins.
The problem
The input is data , a minimal solver for samples of items, a residual , the inlier noise , the size of the range of outlier residuals, a confidence , a cap and a number of EM steps. With , the negative log-likelihood of a model with mixing weight is
The goal is a model of small . MLESAC searches only the models of minimal samples, so it is a randomized heuristic for this goal, a case of robust model fitting by maximum likelihood.
The algorithm
MLESAC(D, s, σ, v, p, k_max, m) ▷ n = |D|- 1
θ* ← none, L* ← ∞, γ* ← 0, k ← k_max, t ← 0 - 2
while t < k do - 3
t ← t + 1 - 4
S ← s distinct items of D, drawn uniformly at random - 5
θ ← FIT-MINIMAL(S) ▷ none for a degenerate sample - 6
if θ is none then continue - 7
g_i ← φ_σ(r(θ, x_i)) for i = 1, …, n - 8
γ ← 1/2 - 9
repeat m times - 10
z_i ← γ g_i / (γ g_i + (1 − γ)/v) for i = 1, …, n - 11
γ ← (1/n) Σ_i z_i - 12
L ← − Σ_i log(γ g_i + (1 − γ)/v) - 13
if L < L* then - 14
θ* ← θ, L* ← L, γ* ← γ - 15
k ← min(k_max, ⌈log(1 − p) / log(1 − γ^s)⌉) - 16
if θ* is none then return failure - 17
θ ← weighted least squares on D with the weights z_i of θ* and γ* - 18
return θ, γ*, L*
Lines L8 to L11 are EM for one unknown. The E step of line L10 computes , the posterior probability that item is an inlier. The M step of line L11 sets to their mean. The model stays fixed: EM here does not refit the model, it only estimates the inlier fraction for the model at hand. Line L15 is the adaptive rule of RANSAC with as the inlier ratio. Line L17 is a final refit; the code uses a weighted least squares fit with the weights , a choice of this code.
Example
Take the 7 points , lines with , the point-to-line distance, , and . Three samples:
| sample | line | after 1 step | after 5 steps | ||
|---|---|---|---|---|---|
| 1 | 0.6903 | 0.7040 | 3.3040 | ||
| 2 | 0.4181 | 0.4139 | 9.7382 | ||
| 3 | 0.6925 | 0.7050 | 2.8107 |
The slanted line passes exactly through 3 of the 7 points, and EM gives it , a little below , because the other points are far. The lines and both have five close points, but is closer to them, so its likelihood is larger and is smaller: MLESAC prefers , as MSAC does. With , line L15 gives rounds. The weighted refit gives the line ; the weights of the two outliers are almost 0.
Correctness
MLESAC keeps an invariant at line L2: has the least value of among the models of the samples drawn so far, where is computed with the of EM steps from . The loop ends after at most rounds. For a fixed model, is concave in , and one EM step is , which never decreases (the ascent property of EM). So more EM steps only make the score of a model better, and a fixed point inside is the maximum likelihood weight. The guarantee of the sampling part is the same as for MSAC: if the model of least score is the model of every sample in its inlier set, a run of rounds finds it with probability at least . The stopping rule with is a heuristic. The proof is below.
Proof: The EM step of MLESAC never lowers the likelihood, and MLESAC keeps the sampled model of best scorefull
We use the notation of the page. For a fixed model , write and , and let and for . The model of computation is the real RAM with and as exact operations.
Claim. (a) is concave on . (b) For , the EM step of lines L10 and L11, , satisfies , and . A is a fixed point of the step if and only if it maximizes on . (c) At each test of line L2, has the least score among the models of the samples drawn so far, where each score uses the of EM steps from , and the loop ends after at most rounds.
Lemma 1 (concavity). Part (a) holds.
Proof. is affine in and positive on , so .
Lemma 2 (the step as a gradient step). For , , and .
Proof. , so , and the sum is . Each posterior lies strictly between 0 and 1 because and , so their mean does too.
Lemma 3 (ascent). For , .
Proof. With and ,
The logarithm is concave, so by Jensen's inequality with the weights and , . Summing over and using gives the first inequality. The right side is times the Kullback-Leibler divergence between the Bernoulli laws with parameters and , which is nonnegative by Gibbs' inequality.
Lemma 4 (fixed points). A is a fixed point of the step if and only if it maximizes on .
Proof. By Lemma 2, if and only if , since . By Lemma 1, is concave, so an interior point with is a maximum on , and an interior maximum has .
Lemmas 2 to 4 prove (b). Lines L8 to L11 start at and apply the step times, so by Lemma 2 every value stays in and by Lemma 3 the likelihood does not decrease along the way.
Proof of (c). Before the first round, . In a round, either line L6 skips the sample and nothing changes, or line L12 computes the score of the new model with its own . Line L13 replaces exactly when , so after line L14 is the least score among the old models and the new one. The value starts at and line L15 sets it only to values at most ; each round increases by 1, so after rounds the test of line L2 fails.
Remark (sampling). If a model of least score is the model of every sample inside its set of likely inliers , and the samples are independent, then rounds find it with probability at least , where is the probability that a sample lies in , by the argument for MSAC. The count of line L15 uses the estimate of the best model so far, which is not a bound on the inlier ratio of the best model overall, so the stopping rule is a heuristic.
Complexity
One round costs the minimal solver, for a fixed model type, then densities in line L7, EM steps of each and one sum of logarithms, so in the real RAM with and as unit-cost operations. With rounds the time is , against for RANSAC and MSAC. With a small fixed , the cost per round is a constant factor more than MSAC. The extra space is . The number of rounds is random, at most , and follows the iteration bound with in place of the inlier ratio.
Properties
- Soft inliers. Each item has a posterior inlier probability instead of a yes or no label.
- Two parameters instead of a threshold. MLESAC needs and . An implicit threshold remains: an item is more likely an inlier than an outlier when .
- EM estimates only . The model is the model of the sample. The EM is a one-dimensional fit, cheap and with a unique optimum, since the log-likelihood is concave in (a theorem).
- Bounded influence. A far outlier adds about to whatever its residual is, so, as for MSAC, its influence has a ceiling.
- Accuracy. Torr and Zisserman report that MLESAC gives more accurate fundamental matrices than RANSAC in their experiments (a benchmark result).
Variants and improvements
- MSAC is the cheaper relative: a truncated quadratic cost with no EM. Each round costs one pass over the data.
- Guided MLESAC. Tordoff and Murray (2002) use the match scores of the feature matcher as prior inlier probabilities, both to choose the samples and in the mixture. PROSAC uses the ordering of the scores instead of their values.
- MAGSAC keeps a likelihood view but removes the fixed by marginalizing over it.
- LO-RANSAC adds local optimization of the best model, which works with any of these scores.
- More EM. One can run EM over both and the model, which turns the last step into an iteratively reweighted fit, as in the iteratively reweighted least squares step of MAGSAC++.
When to use it
Use MLESAC when the inlier noise is known well, the outliers spread over a known range, and an accurate score matters more than a few EM steps per model. If the outlier range is not known, or the speed of each round matters, use MSAC. If is not known well, use MAGSAC.
Pitfalls
- The wrong . The implicit threshold falls as the outlier density grows. If is too small, true inliers with moderate residuals are explained as outliers. If is too large, outliers near the model are explained as inliers. Set from the range of residuals that are possible, for example the size of the search window in pixels.
- Numerical underflow. For large residuals underflows to 0. The mixture term keeps the logarithm finite, so do not drop it, and do not compute the log of the Gaussian term alone.
- EM from a bad start. The concavity makes the start harmless in the limit, but with few EM steps the estimate of is not converged. Use the same for all models so that their scores are comparable.
- for stopping. is an estimate of the inlier ratio for the best model so far, not a bound on the ratio of the best model overall, so the stopping rule is a heuristic.
Implementations
The Python code fits a line in the plane with . The functions em_mixing and mixture_nll give the EM estimate of and the score of any model, and the tests use them to check the ascent of EM and the invariant on every sampled model.
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/mlesac/. The authors are listed in prov/3GWPBP.jsonl.
"""MLESAC (maximum likelihood estimation sample consensus), Torr and Zisserman 2000.
The RANSAC loop with a likelihood score. A residual e has the mixture density
gamma * N(e; 0, sigma^2) + (1 - gamma) / v,
Gaussian inliers with known sigma and uniform outliers on a range of size v.
For each hypothesis, a few EM steps from gamma = 1/2 estimate the mixing weight
gamma only; the model of least negative log-likelihood wins. The default model
is a line in the plane, a x + b y + c = 0 with a^2 + b^2 = 1, from s = 2 points.
The final model is a weighted least squares refit with the posterior inlier
probabilities as weights (a choice of this code). Standard library only.
Cost: O(k (C + m n)) for k trials, m EM steps and n data items.
"""
import math
import random
def line_through(sample):
"""The line through two points, as (a, b, c) with a^2 + b^2 = 1, or None if they coincide."""
(x1, y1), (x2, y2) = sample
a, b = y1 - y2, x2 - x1
nrm = math.hypot(a, b)
if nrm == 0.0:
return None
a, b = a / nrm, b / nrm
return canonical_line((a, b, -(a * x1 + b * y1)))
def canonical_line(line):
a, b, c = line
if a < 0 or (a == 0 and b < 0):
return (-a, -b, -c)
return (a, b, c)
def point_line_distance(line, pt):
a, b, c = line
return abs(a * pt[0] + b * pt[1] + c)
def fit_line_weighted(points, weights):
"""Weighted total least squares line, or None if the weights or the spread vanish."""
sw = sum(weights)
if len(points) < 2 or sw <= 0.0:
return None
mx = sum(w * p[0] for w, p in zip(weights, points)) / sw
my = sum(w * p[1] for w, p in zip(weights, points)) / sw
sxx = sum(w * (p[0] - mx) ** 2 for w, p in zip(weights, points))
syy = sum(w * (p[1] - my) ** 2 for w, p in zip(weights, points))
sxy = sum(w * (p[0] - mx) * (p[1] - my) for w, p in zip(weights, points))
if sxx == 0.0 and syy == 0.0:
return None
theta = 0.5 * math.atan2(2.0 * sxy, sxx - syy)
a, b = -math.sin(theta), math.cos(theta)
return canonical_line((a, b, -(a * mx + b * my)))
def ransac_trials(p, w, s):
"""Smallest k with 1 - (1 - w^s)^k >= p."""
q = w ** s
if q >= 1.0:
return 1
if q <= 0.0:
return math.inf
return math.ceil(math.log(1.0 - p) / math.log1p(-q))
def gauss(e, sigma):
return math.exp(-0.5 * (e / sigma) ** 2) / (math.sqrt(2.0 * math.pi) * sigma)
def mixture_nll(residuals, gamma, sigma, v):
"""Negative log-likelihood of the residuals under the mixture."""
return -sum(math.log(gamma * gauss(e, sigma) + (1.0 - gamma) / v) for e in residuals)
def em_mixing(residuals, sigma, v, steps=5, gamma=0.5):
"""EM for the mixing weight only, from the given start, for a fixed number of steps."""
g = [gauss(e, sigma) for e in residuals]
u = 1.0 / v
for _ in range(steps):
gamma = sum(gamma * gi / (gamma * gi + (1.0 - gamma) * u) for gi in g) / len(g)
return gamma
def mlesac(data, sigma, v, rng=None, s=2, p=0.99, max_trials=10000, em_steps=5,
fit_minimal=line_through, residual=point_line_distance, refit=fit_line_weighted):
"""Return (model, gamma, nll, trials).
nll is the negative log-likelihood of the best sampled model, gamma its
estimated inlier fraction, and model the weighted refit with the posterior
inlier probabilities (or the sampled model if the refit fails). Returns
(None, 0.0, inf, trials) if no sample gives a model.
"""
rng = rng if rng is not None else random.Random()
n = len(data)
if n < s:
return None, 0.0, math.inf, 0
u = 1.0 / v
best, best_nll, best_gamma, k, t = None, math.inf, 0.0, max_trials, 0 # @line L1
while t < k: # @line L2
t += 1 # @line L3
idx = rng.sample(range(n), s) # @line L4
theta = fit_minimal([data[i] for i in idx]) # @line L5
if theta is None: # @line L6
continue
g = [gauss(residual(theta, x), sigma) for x in data] # @line L7
gamma = 0.5 # @line L8
for _ in range(em_steps): # @line L9
z = [gamma * gi / (gamma * gi + (1.0 - gamma) * u) for gi in g] # @line L10
gamma = sum(z) / n # @line L11
nll = -sum(math.log(gamma * gi + (1.0 - gamma) * u) for gi in g) # @line L12
if nll < best_nll: # @line L13
best, best_nll, best_gamma = theta, nll, gamma # @line L14
k = min(max_trials, ransac_trials(p, gamma, s)) # @line L15
if best is None: # @line L16
return None, 0.0, math.inf, t
g = [gauss(residual(best, x), sigma) for x in data] # @line L17
z = [best_gamma * gi / (best_gamma * gi + (1.0 - best_gamma) * u) for gi in g]
model = refit(data, z) if refit is not None else None
return (model if model is not None else best), best_gamma, best_nll, t # @line L18
test_mlesac.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mlesac/. The authors are listed in prov/3GWPBP.jsonl.
import math
import random
from mlesac import (em_mixing, fit_line_weighted, line_through, mixture_nll, mlesac,
point_line_distance, ransac_trials)
EXAMPLE = [(0, 0), (1, 0.1), (2, 0), (3, 0.1), (4, 0), (1, 2), (3, -2)]
def residuals(line, data):
return [point_line_distance(line, x) for x in data]
def planted(rng, n_in, n_out, a=0.5, b=2.0, sigma=0.0, gap=1.0):
pts = []
for _ in range(n_in):
x = rng.uniform(0.0, 10.0)
pts.append((x, a * x + b + (rng.gauss(0.0, sigma) if sigma else 0.0)))
true_line = line_through([(0.0, b), (1.0, a + b)])
while len(pts) < n_in + n_out:
q = (rng.uniform(0.0, 10.0), rng.uniform(-5.0, 12.0))
if point_line_distance(true_line, q) > gap:
pts.append(q)
return pts, true_line
def line_angle(l1, l2):
return math.atan2(abs(l1[0] * l2[1] - l1[1] * l2[0]), abs(l1[0] * l2[0] + l1[1] * l2[1]))
def best_gamma(e, sigma, v):
"""Ternary search; the log-likelihood is concave in gamma."""
lo, hi = 0.0, 1.0
for _ in range(200):
a, b = lo + (hi - lo) / 3, hi - (hi - lo) / 3
if mixture_nll(e, a, sigma, v) < mixture_nll(e, b, sigma, v):
hi = b
else:
lo = a
return lo
def test_example_values():
y01 = residuals(line_through([(1, 0.1), (3, 0.1)]), EXAMPLE)
slanted = residuals(line_through([(2, 0), (1, 2)]), EXAMPLE)
y0 = residuals(line_through([(0, 0), (4, 0)]), EXAMPLE)
expect = [(y01, 0.6903, 0.704, 3.304), (slanted, 0.4181, 0.4139, 9.7382), (y0, 0.6925, 0.705, 2.8107)]
for e, g1, g5, nll in expect:
assert abs(em_mixing(e, 0.1, 10.0, steps=1) - g1) < 5e-5
g = em_mixing(e, 0.1, 10.0)
assert abs(g - g5) < 5e-5
assert abs(mixture_nll(e, g, 0.1, 10.0) - nll) < 5e-5
assert ransac_trials(0.99, 0.705, 2) == 7
def test_example_run():
model, gamma, nll, t = mlesac(EXAMPLE, 0.1, 10.0, random.Random(1))
assert abs(nll - 2.8107) < 5e-5 and abs(gamma - 0.705) < 5e-5 and t == 7
assert abs(model[0]) < 1e-12 and abs(model[2] + 0.0398) < 5e-5
def test_em_ascent_and_limit():
data, line = planted(random.Random(4), 30, 20, sigma=0.1, gap=0.5)
e = residuals(line, data)
g, prev = 0.5, mixture_nll(e, 0.5, 0.1, 20.0)
for _ in range(50):
g = em_mixing(e, 0.1, 20.0, steps=1, gamma=g)
cur = mixture_nll(e, g, 0.1, 20.0)
assert cur <= prev + 1e-12
prev = cur
assert abs(g - best_gamma(e, 0.1, 20.0)) < 1e-6
def test_nll_is_least_among_sampled_models():
for seed in range(3):
data, _ = planted(random.Random(seed), 30, 30, sigma=0.05, gap=0.5)
seen = []
def solver(sample):
line = line_through(sample)
if line is not None:
seen.append(mixture_nll(residuals(line, data), em_mixing(residuals(line, data), 0.05, 20.0),
0.05, 20.0))
return line
_, _, nll, t = mlesac(data, 0.05, 20.0, random.Random(70 + seed), fit_minimal=solver)
assert len(seen) == t
assert abs(nll - min(seen)) < 1e-9
def test_planted_line():
data, true_line = planted(random.Random(3), 50, 50, sigma=0.05, gap=0.5)
model, gamma, _, _ = mlesac(data, 0.05, 20.0, random.Random(5))
assert line_angle(model, true_line) < math.radians(1.0)
assert abs(gamma - 0.5) < 0.1
def test_degenerate():
assert mlesac([(1.0, 1.0)] * 4, 0.1, 10.0, random.Random(0), max_trials=10)[:3] == (None, 0.0, math.inf)
assert mlesac([(0.0, 0.0)], 0.1, 10.0, random.Random(0)) == (None, 0.0, math.inf, 0)
assert fit_line_weighted([(0.0, 0.0), (1.0, 1.0)], [0.0, 0.0]) is None
History
Torr and Zisserman published MLESAC in 2000 in Computer Vision and Image Understanding, for the estimation of the fundamental matrix and other image relations. They gave the mixture of a Gaussian and a uniform distribution for the errors, the EM estimate of the mixing weight and the MSAC cost as a cheaper alternative. Tordoff and Murray (2002) added guided sampling with prior inlier probabilities from the match scores. The likelihood view led to the marginalization over in MAGSAC (2019).
References
- Philip H. S. Torr and Andrew Zisserman, MLESAC: a new robust estimator with application to estimating image geometry, Computer Vision and Image Understanding 78(1), 2000, 138-156, The definition of MLESAC: the mixture model of the errors, the estimation of the mixing parameter by EM and the comparison with RANSAC and MSAC
- Ben J. Tordoff and David W. Murray, Guided sampling and consensus for motion estimation, European Conference on Computer Vision 2002, Lecture Notes in Computer Science 2350, 82-96, Guided MLESAC: match scores as prior inlier probabilities in the sampling and in the mixture
- Rahul Raguram, Ondrej Chum, Marc Pollefeys, Jiri Matas and Jan-Michael Frahm, USAC: a universal framework for random sample consensus, IEEE Transactions on Pattern Analysis and Machine Intelligence 35(8), 2013, 2022-2038, The part of the survey on model verification and the choice of the cost function
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 3GWPBP Edit this page History Report an error Markdown