Algorithmadvanced
KLD-sampling
Also called adaptive particle filter.
A particle filter that draws particles until their number reaches a bound from the count of occupied bins. The bound limits the KL error of the histogram only asymptotically.
- Time
- O(N + n log N + n D) per_step
- Space
- O(N + n + k) extra
- Where
- D = the cost of one evaluation of the measurement model; N = the number of particles of the previous step; epsilon = the error bound; k = the number of occupied bins; n = the number of particles drawn in one step
- Model
- Real RAM
- Properties
- adaptiverandomizednot exactonlinerandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Dieter Fox, 2003
KLD-sampling is a variant of Monte Carlo localization that chooses the number of particles at each step. It draws the new particles one at a time and puts each in a bin of a fixed grid over the pose space. It stops when the number of particles reaches a bound that grows with the number of bins that hold at least one particle. When the belief is spread out, as at the start of global localization, many bins are occupied and the filter uses many particles. When the belief is concentrated, few bins are occupied and the filter uses few. Fox (2003) derived the bound from the distribution of the Kullback-Leibler divergence between a sample histogram and the true distribution: with samples, the divergence is at most with probability about . This holds only asymptotically, and only for the histogram of independent samples of a fixed distribution.
In plain words
A robot that does not know where it is needs many guesses, because the guesses must cover the whole building. Once it knows where it is, a few guesses near the right place are enough. KLD-sampling counts how many different areas the guesses fall in while it makes them. Each new area means that more guesses are needed. It stops when it has enough guesses for the number of areas it has seen. So the robot spends its computation where it helps, and runs fast when it is sure of its pose.
The problem
The setting is Monte Carlo localization: a map, a motion model that can be sampled, a measurement model that can be evaluated, and a weighted particle set for the previous belief. In addition, there is a grid of bins over the pose space, an error bound and a probability . The output is a weighted particle set for the new belief, with a number of particles that depends on the belief.
The goal behind the bound is this. Let a distribution over bins be sampled times independently, and let be the histogram of the samples. Choose so that , where .
The algorithm
The bound. By the likelihood ratio test theory (Wilks' theorem), converges in distribution to the chi-square distribution with degrees of freedom as . So the probability that is about for
(Fox, equation (13)), where is the quantile. The Wilson-Hilferty approximation of the quantile gives
(Fox, equation (14)), where is the quantile of the standard normal distribution. For large , is about : linear in the number of occupied bins.
The sampler. is not known in advance. KLD-sampling counts the bins that the new particles occupy and updates the bound after each new bin.
KLD-MCL(X_{t-1}, u_t, z_t, m, ε, δ, n_min, n_max)- 1
X_t ← ∅; n ← 0; k ← 0; n_χ ← 0; all bins empty - 2
repeat - 3
draw an index i with probability w_{t-1}^[i] / Σ w_{t-1} - 4
x ← sample of p(x_t | u_t, x_{t-1}^[i], m) - 5
w ← p(z_t | x, m); add (x, w) to X_t - 6
if the bin of x is empty then - 7
mark it nonempty; k ← k + 1 - 8
if k > 1 then n_χ ← (k-1)/(2ε) · (1 - 2/(9(k-1)) + √(2/(9(k-1))) z_{1-δ})³ - 9
n ← n + 1 - 10
until (n ≥ n_χ and n ≥ n_min) or n ≥ n_max - 11
return X_t
Unlike the MCL of Thrun et al., which moves and then resamples a set of fixed size, KLD-sampling draws each new particle independently from the previous weighted set (line L3), so the number of draws can be chosen while sampling. The new set stays weighted. Fox uses a lower limit (typically 10). The code adds so that the loop always ends.
The loop condition. The listing of the algorithm in Fox (2003), Table 2, prints the loop condition as "while ( and )". With at the start, this would stop after one particle. The text and the version of Thrun et al. (Section 8.3.7) mean that the loop continues while either bound is not reached, which is line L10 here.
Example
The bound for . The table gives by the Wilson-Hilferty form, and in brackets by the exact chi-square quantile where they differ.
| , | |||
|---|---|---|---|
| 2 | 66 (67) | 38 | 33 |
| 3 | 93 | 60 | 47 |
| 5 | 134 (133) | 95 | 67 |
| 10 | 217 | 170 | 109 |
| 20 | 363 (362) | 302 | 182 |
| 50 | 750 | 664 | 375 |
| 100 | 1347 | 1233 | 674 |
| 1000 | 11060 | 10737 | 5530 |
The Wilson-Hilferty form is worst for , with 1 degree of freedom, where it is up to 2.5 percent low for and . For it is within 0.5 percent of the exact value in the tests.
Coverage. The test draws samples, the bound for , and , from a fixed distribution over 10 bins, 1500 times. The divergence of the histogram is at most in 89.1 percent of the trials, against the asymptotic percent. This is a measurement for one distribution and one seed.
Localization on a ring. A robot moves 1 m per step on a ring of 30 m with a color in each 1 m cell, and the bins are 0.5 m long, 60 bins in all. The start is 5000 particles spread over the ring. With and , the numbers of particles in the first 10 steps are 872, 836, 688, 444, 444, 263, 248, 169, 134 and 114, and in the last 7 of 25 steps they are 93 or 114, which is the bound for 3 or 4 bins. The first step occupies all 60 bins, and the bound for is 872. This is a measurement for one seed.
Correctness
The correctness proof shows three things. The loop ends after at most draws. When it ends before , for the number of occupied bins. And, for independent samples of a fixed distribution with bins of positive mass and set by equation (13), as .
Each of these is a theorem with its assumptions. The use of the bound for a particle filter is a heuristic, for these reasons.
- The bound is asymptotic. For small the true probability can differ from .
- It is about the histogram of the samples, not about the continuous belief, and the grid size sets what it measures.
- The particles are drawn from the predicted belief and weighted afterwards, so the histogram that the bound controls is that of the proposal, not that of the posterior.
- is counted from the samples themselves, and it grows while they are drawn.
- A bound on the error of one step does not bound the error over many steps. Fox (2003) states that the approach is not guaranteed not to diverge.
Proof: KLD-sampling stops at its bound, and the bound gives the coverage 1 - delta asymptoticallyfull
Setting. One call of KLD-MCL with , and integers . After draws, is the number of occupied bins and is the value of line L8, with for . For Part 3, is a distribution over bins with all , are independent draws of , is the number of the first draws in bin , and , with . Let and .
Assumptions.
- (A1) The previous weights are with a positive sum, so line L3 is defined.
- (A2) For Part 3 only: the draws are independent and identically distributed with the distribution over the bins. This is an assumption about the samples, not something that the particle filter guarantees.
Claim.
- The loop ends after at most iterations.
- If it ends with draws, then , , and the loop did not end after any earlier draw , that is, or .
- Under (A2), converges in distribution to the chi-square distribution with degrees of freedom as , and as .
Proof.
Claim 1. Each iteration increases by 1 (line L9), starting from 0. The test of line L10 is true when , so the loop ends at the latest after iteration .
Claim 2. The loop tests line L10 after each draw, with the current values of and . Line L8 sets to each time grows past 1, and stays while , so at each test . The loop ends at draw for the first where and or . If , the first part holds; the condition was false at each earlier , which gives the last statement.
Claim 3. Let , so .
Step 1: Pearson's statistic. The vector is a normalized sum of independent copies of , where is the unit vector of the bin of . Its mean is 0 and its covariance is . By the multivariate central limit theorem, in distribution. Pearson's statistic is with . The map is continuous, so in distribution. The vector has the same distribution as with and : indeed , because makes a projection and . Then , the squared length of the projection of a standard normal vector onto a subspace of dimension . This has the chi-square distribution with degrees of freedom.
Step 2: in probability. For , Taylor's theorem gives with . (The third derivative of is , of absolute value at most 4 on , so .) With ,
on the event . On , . Since converges in distribution, it is bounded in probability, so this tends to 0 in probability. By the law of large numbers almost surely, so . Hence in probability, and by Slutsky's theorem in distribution.
Step 3: the coverage. Let be the distribution function of and that of . is continuous, so by Pólya's theorem . As , , and lies in , so . Then
since by the definition of and is continuous.
What this does not show. Claim 3 is a limit; it gives no error bound for a fixed . The code uses the Wilson-Hilferty approximation of , which the tests compare with the exact quantile. In the particle filter, the samples are drawn from the predicted belief and weighted afterwards, the number of bins is counted from the samples, and the errors of successive steps add up, so the claim does not bound the error of the filter. That use is a heuristic.
Complexity
Let be the size of the previous set and the number of new particles.
- Building the cumulative weights: .
- Each draw in line L3 by binary search: . Each motion sample: . Each weight: .
- Each bin test: expected time with a hash set.
- Total per step: . Space: .
The point is that adapts: it is about for large , and in general. During tracking, is small and can be one or two orders of magnitude below the needed for global localization.
Properties
- Adaptive. The number of particles follows the spread of the belief, as measured by the number of occupied bins.
- Two parameters with meaning. and replace the number of particles, which is hard to choose. The grid size is a third parameter, and it matters as much.
- No guarantee to find the pose. Like plain MCL, it can lose the true pose. When the belief is concentrated at a wrong pose, is small and so is , which makes recovery harder. Random particles, as in augmented MCL, help.
- Monotone bound. increases with and with , and for is half of that for .
Variants and improvements
- Exact quantile. Compute exactly, for example by bisection on the regularized incomplete gamma function, as the test does. For the gain is under 0.5 percent.
- Bins by tree. Instead of a fixed grid, count leaves of a kd-tree or of a multi-resolution grid to adapt the bin size.
- Adaptive resampling. Combine KLD-sampling with resampling only when the effective sample size is low.
- Random particles. Add a few random poses at each step, as in augmented MCL, so that a wrong concentrated belief can still recover.
When to use it
Use KLD-sampling in Monte Carlo localization when the robot has phases with very different uncertainty, such as a global start and long tracking, and computation is limited. The gain is large when the map is large compared with the bin size. When the belief always stays concentrated, a fixed small number of particles is as good and simpler.
Pitfalls
- Bins too large. With large bins, a tracked belief occupies one or two bins, drops to , and the filter can lose the true pose. With bins too small, grows with and the loop can run to .
- Heading bins. The grid must include the heading. A 2D position grid alone hides spread in the heading.
- The printed loop condition. Copying the "and" of Table 2 in Fox (2003) gives a sampler that stops after one particle. Use "or" for the continue condition, or "and" for the stop condition as in line L10.
- Reading the bound as a guarantee. The probability is asymptotic and about the histogram of the proposal. It does not mean that the filter keeps the error of the belief below .
- No upper limit. Without , a belief spread over a very large map can make the loop draw more particles than fit in memory.
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/kld-sampling/. The authors are listed in prov/ZKY15F.jsonl.
"""KLD-sampling: Monte Carlo localization with an adaptive number of particles.
The notation follows Fox (2003) and Thrun, Burgard and Fox (2005), Section 8.3.7.
A belief is a list of (pose, weight) pairs; the weights need not sum to 1.
The models are callables:
sample_motion(rng, x, u) one draw of x_t from p(x_t | u_t, x_{t-1} = x, m)
likelihood(z, x) p(z_t | x_t = x, m), a number >= 0
bin_of(x) a hashable key of the grid bin that holds x
rng is a random.Random.
"""
import bisect
import math
from statistics import NormalDist
def kld_bound(k, epsilon, delta):
"""Return the number of samples of the KLD bound for k occupied bins.
n = chi^2_{k-1, 1-delta} / (2 epsilon), with the quantile of the
chi-square distribution approximated by Wilson and Hilferty:
n = (k-1) / (2 epsilon) * (1 - 2/(9(k-1)) + sqrt(2/(9(k-1))) z_{1-delta})^3.
For k <= 1 the bound is 0. The value is a real number; the sampler
stops at the first integer count that reaches it.
"""
if not (epsilon > 0.0 and 0.0 < delta < 1.0):
raise ValueError("need epsilon > 0 and 0 < delta < 1")
if k <= 1:
return 0.0
z = NormalDist().inv_cdf(1.0 - delta)
a = 2.0 / (9.0 * (k - 1))
return (k - 1) / (2.0 * epsilon) * (1.0 - a + math.sqrt(a) * z) ** 3
def kld_mcl(belief, u, z, sample_motion, likelihood, bin_of, rng, epsilon=0.05, delta=0.01, n_min=10, n_max=100000):
"""One step of KLD-sampling MCL.
Draw particles from the previous weighted belief one at a time, move
them, weight them and count the occupied bins, until the number of
particles reaches both the KLD bound for the current number of bins
and n_min, or reaches n_max. Return the new list of (pose, weight).
"""
if not belief:
raise ValueError("empty belief")
if not 1 <= n_min <= n_max:
raise ValueError("need 1 <= n_min <= n_max")
cum, total = [], 0.0
for _, w in belief:
if w < 0.0:
raise ValueError("negative weight")
total += w
cum.append(total)
if total <= 0.0:
raise ValueError("every particle has weight 0")
new, bins = [], set() # @line L1
n, n_chi, k = 0, 0.0, 0
while True: # @line L2
i = bisect.bisect_right(cum, rng.random() * total) # @line L3
i = min(i, len(belief) - 1)
x = sample_motion(rng, belief[i][0], u) # @line L4
new.append((x, likelihood(z, x))) # @line L5
b = bin_of(x)
if b not in bins: # @line L6
bins.add(b) # @line L7
k += 1
if k > 1:
n_chi = kld_bound(k, epsilon, delta) # @line L8
n += 1 # @line L9
if (n >= n_chi and n >= n_min) or n >= n_max: # @line L10
return new # @line L11
test_kld_sampling.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kld-sampling/. The authors are listed in prov/ZKY15F.jsonl.
import bisect
import math
import random
import pytest
from kld_sampling import kld_bound, kld_mcl
def gamma_p(a, x):
"""The regularized lower incomplete gamma function P(a, x), by its series."""
if x <= 0.0:
return 0.0
term = 1.0 / a
s = term
n = 0
while abs(term) > 1e-17 * abs(s):
n += 1
term *= x / (a + n)
s += term
return s * math.exp(-x + a * math.log(x) - math.lgamma(a))
def chi2_quantile(dof, p):
"""The p quantile of the chi-square distribution, by bisection on its CDF."""
lo, hi = 0.0, dof + 20.0 * math.sqrt(dof) + 50.0
for _ in range(60):
mid = (lo + hi) / 2.0
if gamma_p(dof / 2.0, mid / 2.0) < p:
lo = mid
else:
hi = mid
return (lo + hi) / 2.0
def test_chi2_quantile_helper_matches_known_values():
assert chi2_quantile(1, 0.99) == pytest.approx(6.635, abs=1e-3)
assert chi2_quantile(2, 0.99) == pytest.approx(9.210, abs=1e-3)
assert chi2_quantile(3, 0.95) == pytest.approx(7.815, abs=1e-3)
def test_wilson_hilferty_is_close_to_the_exact_bound():
eps = 0.05
for delta in (0.01, 0.05, 0.1):
for k in list(range(2, 12)) + [20, 50, 100, 300, 1000]:
exact = chi2_quantile(k - 1, 1.0 - delta) / (2.0 * eps)
# the approximation is worst for 1 degree of freedom
rel = 0.03 if k == 2 else (0.015 if k <= 4 else 0.005)
assert kld_bound(k, eps, delta) == pytest.approx(exact, rel=rel)
def test_bound_grows_with_k_and_shrinks_with_epsilon():
values = [kld_bound(k, 0.05, 0.01) for k in range(1, 200)]
assert values[0] == 0.0
assert all(a < b for a, b in zip(values, values[1:]))
assert kld_bound(20, 0.1, 0.01) == pytest.approx(kld_bound(20, 0.05, 0.01) / 2.0)
# for large k, the bound is about (k - 1) / (2 epsilon)
assert kld_bound(5001, 0.05, 0.01) / (5000 / 0.1) == pytest.approx(1.0, abs=0.05)
with pytest.raises(ValueError):
kld_bound(5, 0.0, 0.01)
def kl(p_hat, p):
return sum(a * math.log(a / b) for a, b in zip(p_hat, p) if a > 0.0)
def test_bound_gives_the_coverage_asymptotically():
# Draw n = the bound samples from a fixed distribution over k bins.
# The KL divergence from the histogram to the true distribution is at
# most epsilon in about 1 - delta of the trials (a large-n result).
rng = random.Random(4)
p = [0.05, 0.05, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.2]
k, eps, delta = len(p), 0.05, 0.1
n = math.ceil(kld_bound(k, eps, delta))
cum = [sum(p[: i + 1]) for i in range(k)]
trials, good = 1500, 0
for _ in range(trials):
c = [0] * k
for _ in range(n):
c[min(bisect.bisect_left(cum, rng.random()), k - 1)] += 1
if kl([v / n for v in c], p) <= eps:
good += 1
assert 0.86 <= good / trials <= 0.94
# A ring of 30 m with a color in each 1 m cell; the bins are the cells.
C = 30
_R = random.Random(3)
COLORS = [_R.randrange(4) for _ in range(C)]
def color(x):
return COLORS[int(x) % C]
def likelihood(z, x):
return 0.85 if color(x) == z else 0.05
def motion(rng, x, u):
return (x + u + rng.gauss(0.0, 0.1)) % C
def sense(rng, x):
if rng.random() < 0.85:
return color(x)
return rng.choice([c for c in range(4) if c != color(x)])
def bin_of(x):
return int(x * 2.0) # bins of 0.5 m
def test_particles_shrink_when_the_belief_concentrates():
rng = random.Random(2)
belief = [(rng.uniform(0, C), 1.0) for _ in range(5000)]
truth = 0.3
sizes = []
for _ in range(25):
truth = motion(rng, truth, 1.0)
belief = kld_mcl(belief, 1.0, sense(rng, truth), motion, likelihood, bin_of, rng)
sizes.append(len(belief))
assert sizes[0] > 800 # the global phase occupies all 60 bins: the bound is 872
assert max(sizes[-5:]) < 200 # tracking occupies a few bins
mean = sum(x * w for x, w in belief) / sum(w for _, w in belief)
assert abs(mean - truth) < 0.5
def test_n_min_and_n_max():
rng = random.Random(0)
belief = [(5.2, 1.0)]
# a still robot with no noise keeps one bin, so n_min particles are drawn
out = kld_mcl(belief, 0.0, 0, lambda r, x, u: x, likelihood, bin_of, rng, n_min=10)
assert len(out) == 10
belief = [(rng.uniform(0, C), 1.0) for _ in range(100)]
out = kld_mcl(belief, 0.0, 0, lambda r, x, u: r.uniform(0, 1000), likelihood, lambda x: int(x), rng, n_max=500)
assert len(out) == 500
with pytest.raises(ValueError):
kld_mcl([(0.0, 0.0)], 0.0, 0, motion, likelihood, bin_of, rng)
def test_the_count_stops_at_the_bound():
# The samples fill 20 bins in turn, so k reaches 20 after 20 samples and
# the sampler stops at the first count that reaches the bound for k = 20.
rng = random.Random(1)
counter = iter(range(10 ** 6))
out = kld_mcl([(0.0, 1.0)], 0.0, 0, lambda r, x, u: next(counter), lambda z, x: 1.0, lambda x: x % 20, rng, epsilon=0.05, delta=0.05)
assert len(out) == math.ceil(kld_bound(20, 0.05, 0.05))
History
Fox presented KLD-sampling at a conference in 2001 and in a journal article in 2003, with experiments in Monte Carlo localization where, in his measurements, the adaptive filter needed far fewer particles than a filter of fixed size for the same accuracy. Thrun, Burgard and Fox (2005) include it in Chapter 8 as a standard part of MCL. Its form of the bound, a chi-square quantile in the number of occupied bins, comes from the classical asymptotic theory of the likelihood ratio and of Pearson's chi-square statistic.
References
- Dieter Fox, Adapting the sample size in particle filters through KLD-sampling, The International Journal of Robotics Research 22(12), 2003, pages 985 to 1003, the bound of equation (13), the Wilson-Hilferty form of equation (14), the KLD-sampling algorithm of Table 2 and the localization experiments
- Sebastian Thrun, Wolfram Burgard and Dieter Fox, Probabilistic Robotics, MIT Press, 2005, Chapter 8, Section 8.3.7 (KLD-sampling)
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 ZKY15F Edit this page History Report an error Markdown