Algorithmresearch
Bayesian online change-point detection
Also called BOCPD, Adams-MacKay algorithm.
Adams and MacKay's recursion for the posterior of the run length since the last change, from a hazard rate and a conjugate model for each segment.
- Solves
- Change-point detection
- Time
- Θ(n²) worst
- Space
- Θ(n) extra
- Where
- n = the number of observations read, with O(1) work per conjugate update; step t costs Θ(t)
- Model
- Real RAM
- Properties
- deterministicexactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ryan P. Adams, David J. C. MacKay, 2007
Bayesian online change-point detection keeps, after each new observation, the posterior distribution of the run length : the number of observations since the last change, the new one included. The model is a renewal process: a segment that has lasted points ends with probability , the hazard, and each segment draws a new parameter from a prior. With a conjugate prior, the predictive density of the next point given the last points costs , and the posterior at time follows from the one at time by one growth step and one change step. Each step costs time and memory, or when small posterior values are dropped. A sharp rise of , or a fall of the most probable run length, signals a change.
In plain words
At each moment you ask: how long ago did the current regime start? You keep a probability for every possible answer. When a new value arrives, every answer either grows by one, if the regime goes on, or resets to "it started just now", if a new regime begins. You compare how well the new value fits each regime. If it fits the old regime well, the long answers keep their weight. If it fits only a fresh start, the weight moves to the short answer. The probability of each answer is updated with the rules of chance, so you also get a measure of how sure you are.
The problem
Observations arrive one at a time. The model is:
- Segments. The series is cut into segments by a renewal process. A segment that has run for points ends after its -th point with probability . The first segment starts at . A constant hazard gives geometric segment lengths with mean .
- Parameters. Each segment has its own parameter , drawn from a prior , independently of the other segments and of the segmentation.
- Data. Given the segments and their parameters, the points are independent, and a point of a segment with parameter has density .
The run length is the number of points of the current segment up to and including . The task is to compute for each as arrives, and the evidence . The predictive density of a point given the points before it in its segment is
and . See change-point detection for the other formulations.
The algorithm
BOCPD(x_1, x_2, ..., H, prior)- 1
P ← empty map; stats ← empty map; Z_all ← 1 ▷ P(r) = P(r_{t-1} = r | x_{1..t-1}) - 2
for t ← 1, 2, ... as x_t arrives do - 3
π(r) ← predictive of x_t from stats(r), for each r in P; π_0 ← predictive of x_t from the prior - 4
J(r + 1) ← P(r) π(r) (1 - H(r)), for each r in P ▷ the segment goes on - 5
J(1) ← π_0 Σ_r P(r) H(r), and J(1) ← π_0 when t = 1 ▷ a new segment starts at x_t - 6
stats(r + 1) ← update(stats(r), x_t) for each r in P; stats(1) ← update(empty, x_t) - 7
Z ← Σ_r J(r); Z_all ← Z_all · Z; P ← J / Z ▷ P(r) = P(r_t = r | x_{1..t}) - 8
return the posteriors P after each step and the evidence Z_all
Line L3 uses the sufficient statistics of the last points, so it costs per run length for a conjugate model. For a normal mean with known variance and prior , the statistics are the count and the sum , and the predictive is normal with precision-weighted mean and variance . Lines L4 and L5 are the growth and change steps. Line L7 normalizes and keeps the evidence .
Example
Let , the prior be , the hazard , and the data . The run-length posteriors, rounded to 4 decimals, are:
| most probable | ||||||||
|---|---|---|---|---|---|---|---|---|
| 1 | 0.2 | 1 | 1 | |||||
| 2 | 0.0513 | 0.9487 | 2 | |||||
| 3 | 0.4 | 0.0451 | 0.0398 | 0.9151 | 3 | |||
| 4 | 3.9 | 0.7985 | 0.0588 | 0.0081 | 0.1347 | 1 | ||
| 5 | 4.3 | 0.0270 | 0.9533 | 0.0165 | 0.0004 | 0.0027 | 2 | |
| 6 | 3.6 | 0.0226 | 0.0237 | 0.9394 | 0.0136 | 0.0001 | 0.0006 | 3 |
At the predictive density of under the old segment, after 3 points with sum 0.1, is about 0.0012. Under a fresh segment it is about 0.059, because the prior is wide. Weighted by the hazard, the change step wins, and . After that the run length grows again from the change at . The most probable run lengths give one change point, before . The evidence is .
Correctness
The recursion is exact for the model. The proof is in full below. In outline, let .
- The run length is a Markov chain. Given , the next run length is with probability and with probability , whatever the earlier data. This holds because the end of a segment is decided by the renewal process, which is independent of the parameters and of the data given the segmentation.
- The predictive depends only on the current segment. Given the whole segmentation up to , is independent of all points outside the current segment, because the parameters of different segments are independent. So .
- The recursion. By the chain rule and facts 1 and 2,
with . Dividing by gives lines L4 and L5, the normalizer of line L7 is , and the product of the normalizers is the evidence by Bayes' theorem.
Proof: The BOCPD recursion computes the exact run-length posterior and the evidence of the renewal change-point modelfull
Notation is that of the page. The model has three parts. (i) The segmentation is a renewal process: with , and given , the run length equals 1 with probability and otherwise. (ii) Each segment has a parameter , and are i.i.d. from the prior and independent of the segmentation. (iii) Given the segmentation and the parameters, are independent, and a point of segment has density . All densities are with respect to a fixed measure, and is the predictive density of the page, computed under the model of one segment, with the prior predictive. Write and .
The sequence determines the segmentation of , and means that the current segment is .
Lemma 1 (transition). , given by for the value 1 and for the value .
Proof. By (i), is a function of and a fresh coin with success probability , independent of everything else before time . The data are, by (ii) and (iii), functions of , the parameters and independent noise, all independent of that coin given . So conditioning on as well as on does not change the law of the coin.
Lemma 2 (predictive). For , on the event . In particular this conditional density depends on only through .
Proof. Fix with . The segmentation of is then fixed, and the current segment is . By (ii) and (iii), the points of segments other than are functions of parameters , , and noise, all independent of . So, given , the vector is independent of the other earlier points, and
Given , the points are i.i.d. given with , which is the model of one segment, so the right side is .
Lemma 3 (the joint recursion). , and for ,
Proof. For , and has the prior predictive density. For , by the chain rule,
By Lemmas 1 and 2 the last two factors are and , which depend on only through . Sum over with and fixed:
If , the only with positive transition probability is , with probability , which gives the first formula. If , every contributes with probability , which gives the second.
Theorem. After line L7 at step , for every , the stored statistics stats summarize , and . The step costs predictive evaluations and updates.
Proof. By induction on . Before step 1, is empty and . Suppose the claim holds after step , so and stats summarizes the last points. Then line L3 computes and . Lines L4 and L5 compute by Lemma 3; for , line L5 gives directly. Line L6 moves each statistic up by one run length and adds , so stats summarizes , and stats summarizes alone. At line L7, , so becomes , and , which is the posterior by Bayes' theorem. Each step loops over at most stored run lengths.
Pruning. If run lengths with small posterior are dropped and the rest renormalized, the recursion is applied to a truncated distribution, and the result is an approximation. Its error is not bounded here.
Complexity
At time there are run lengths, so lines L3 to L7 cost time with conjugate updates, and for observations. The memory is : one probability and one set of sufficient statistics per run length. Dropping run lengths whose posterior is below a small threshold, or keeping only a fixed number of them, makes each step at the price of an approximation.
Properties
- Exact Bayesian filter. Without pruning, the posteriors are exact for the model, including the uncertainty about the change times.
- A hidden Markov model. The run length is the hidden state of a hidden Markov model whose state space grows with , and the recursion is its forward algorithm.
- Evidence for free. The product of normalizers is the marginal likelihood, so the hazard and the prior can be tuned or compared by evidence.
- Unknown parameters handled. Unlike the CUSUM, it needs no known pre-change or post-change density, only a prior.
- Model dependent. The answer is only as good as the segment model and the hazard. Outliers under a light-tailed model look like changes.
Variants and improvements
- Pruning and resampling. Fearnhead and Liu (2007) keep a bounded number of values with a resampling step from particle filtering, so the cost of each step stays bounded and the error is controlled. The simplest form drops run lengths with small posterior probability.
- Hazard learning. A hazard with unknown parameters can be learned from the evidence, or by placing a prior on it.
- Non-conjugate models. When no conjugate prior exists, the predictive can be approximated per run length by sequential Monte Carlo or by Gaussian approximations; linear Gaussian state-space segments use a Kalman filter per run length.
- Robust segments. Student-t or mixture likelihoods reduce false alarms from outliers.
- Offline exact segmentation. When the whole series is available and only a point estimate is wanted, PELT gives the penalized optimum.
When to use it
Use BOCPD for streams where the parameters of each regime are unknown, changes may be many, and a probability of a change is more useful than a yes or no answer, for example in monitoring of sensors or of financial series. Use the CUSUM when the pre-change and post-change densities are known and a guaranteed false alarm rate matters, and an offline method when the whole series is at hand.
Pitfalls
- Run-length convention. Some texts let mean that a change happened at , so their is one smaller. Mixing the two shifts all change estimates by one.
- Underflow. The joint probabilities and the evidence shrink geometrically. Normalize at each step, as in line L7, and keep the log evidence.
- Prior too wide or too narrow. A very wide prior makes the predictive under a fresh segment small, so changes are found late. A very narrow prior makes every point look like a change.
- Reading the most probable run length as a decision. The posterior can split its mass, as at in the example. Use a decision rule, such as for a small window , and state it.
- Unbounded cost. Without pruning, the cost grows with , so a long stream needs pruning or resampling.
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/bayesian-online-changepoint-detection/. The authors are listed in prov/KJZYAX.jsonl.
"""Bayesian online changepoint detection (Adams and MacKay 2007).
Model: the series is cut into segments by a renewal process. A segment that
has run for r points ends after its r-th point with probability H(r) (the
hazard). Each segment draws its own parameter from a prior, independently of
the other segments, and the points of a segment are i.i.d. given the
parameter. The run length r_t is the number of points in the current segment,
x_t included, so r_t is in 1..t.
The joint J_t(r) = P(r_t = r, x_1..x_t) obeys
J_1(1) = p(x_1 | no data),
J_t(1) = p(x_t | no data) * sum_r J_(t-1)(r) H(r),
J_t(r + 1) = p(x_t | the last r points) * J_(t-1)(r) (1 - H(r)).
The code keeps the normalized posterior P(r_t = r | x_1..x_t) and the
evidence. Cost O(t) at step t, O(n^2) in total, O(n) memory per step; the
optional pruning drops run lengths with posterior below a threshold.
"""
import math
from collections.abc import Callable, Iterable
from fractions import Fraction
from typing import Any
class BetaBernoulli:
"""Coin flips with a Beta(a, b) prior on the head probability. Exact with Fraction a, b."""
def __init__(self, a: Fraction | int = 1, b: Fraction | int = 1) -> None:
self.a, self.b = Fraction(a), Fraction(b)
def empty(self) -> tuple[int, int]:
return (0, 0)
def predictive(self, stats: tuple[int, int], x: int) -> Fraction:
h, t = stats
p1 = (self.a + h) / (self.a + self.b + h + t)
return p1 if x else 1 - p1
def update(self, stats: tuple[int, int], x: int) -> tuple[int, int]:
h, t = stats
return (h + 1, t) if x else (h, t + 1)
class GaussianKnownVariance:
"""N(mu, sigma^2) points with sigma known and the prior mu ~ N(mu0, sigma0^2)."""
def __init__(self, mu0: float, sigma0: float, sigma: float) -> None:
self.mu0, self.v0, self.v = mu0, sigma0 * sigma0, sigma * sigma
def empty(self) -> tuple[int, float]:
return (0, 0.0)
def predictive(self, stats: tuple[int, float], x: float) -> float:
n, s = stats
prec = 1.0 / self.v0 + n / self.v
mean = (self.mu0 / self.v0 + s / self.v) / prec
var = 1.0 / prec + self.v
return math.exp(-0.5 * (x - mean) ** 2 / var) / math.sqrt(2.0 * math.pi * var)
def update(self, stats: tuple[int, float], x: float) -> tuple[int, float]:
return (stats[0] + 1, stats[1] + x)
def constant_hazard(lam: Any) -> Callable[[int], Any]:
"""H(r) = 1 / lam for every r: geometric segment lengths with mean lam."""
return lambda r: 1 / lam
def bocpd(xs: Iterable[Any], model: Any, hazard: Callable[[int], Any],
prune: float = 0.0) -> tuple[list[dict[int, Any]], Any]:
"""Run-length posteriors P(r_t = r | x_1..x_t) for t = 1..n, and the evidence p(x_1..x_n).
Each posterior is a dict from run length r to probability. With prune > 0,
run lengths whose posterior falls below prune are dropped (an
approximation); prune = 0 gives the exact recursion.
"""
post: dict[int, Any] = {} # @line L1
stats: dict[int, Any] = {} # @line L1
evidence: Any = 1
out = []
for t, x in enumerate(xs, 1): # @line L2
pred = {r: model.predictive(stats[r], x) for r in post} # @line L3
pred0 = model.predictive(model.empty(), x) # @line L3
joint = {r + 1: post[r] * pred[r] * (1 - hazard(r)) for r in post} # @line L4
joint[1] = pred0 * (sum(post[r] * hazard(r) for r in post) if t > 1 else 1) # @line L5
stats = {r + 1: model.update(stats[r], x) for r in post} # @line L6
stats[1] = model.update(model.empty(), x) # @line L6
z = sum(joint.values()) # @line L7
evidence = evidence * z # @line L7
post = {r: v / z for r, v in joint.items()} # @line L7
if prune > 0:
keep = {r: v for r, v in post.items() if v >= prune}
total = sum(keep.values())
post = {r: v / total for r, v in keep.items()}
stats = {r: stats[r] for r in post}
out.append(dict(sorted(post.items())))
return out, evidence # @line L8
def map_run_lengths(posteriors: list[dict[int, Any]]) -> list[int]:
"""The most probable run length at each step (ties go to the smaller r)."""
return [min(p, key=lambda r: (-p[r], r)) for p in posteriors]
test_bayesian_online_changepoint_detection.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bayesian-online-changepoint-detection/. The authors are listed in prov/KJZYAX.jsonl.
import math
import random
from fractions import Fraction
from bayesian_online_changepoint_detection import (
BetaBernoulli,
GaussianKnownVariance,
bocpd,
constant_hazard,
map_run_lengths,
)
def compositions(n):
"""All ordered lists of positive segment lengths that add up to n (2^(n-1) of them)."""
if n == 0:
yield []
return
for first in range(1, n + 1):
for rest in compositions(n - first):
yield [first] + rest
def beta_bernoulli_marginal(seg, a, b):
h = sum(seg)
k = len(seg) - h
num = math.prod((a + i for i in range(h)), start=Fraction(1)) * math.prod((b + j for j in range(k)), start=Fraction(1))
den = math.prod((a + b + i for i in range(h + k)), start=Fraction(1))
return num / den
def gaussian_marginal(seg, mu0, s0, s):
"""Density of a segment under x ~ N(mu0 1, s^2 I + s0^2 1 1^T), by Sherman-Morrison."""
m = len(seg)
d = [x - mu0 for x in seg]
q = (sum(v * v for v in d) - s0 * s0 * sum(d) ** 2 / (s * s + m * s0 * s0)) / (s * s)
log_det = 2 * m * math.log(s) + math.log(1 + m * s0 * s0 / (s * s))
return math.exp(-0.5 * q - 0.5 * log_det - 0.5 * m * math.log(2 * math.pi))
def enumerate_posterior(xs, marginal, hazard, one=1):
"""P(r_n = r | x) and p(x) by summing over every segmentation of x_1..x_n."""
n = len(xs)
joint = {}
for lengths in compositions(n):
w = one
for j, length in enumerate(lengths):
for r in range(1, length):
w = w * (1 - hazard(r))
if j < len(lengths) - 1:
w = w * hazard(length)
pos = 0
for length in lengths:
w = w * marginal(xs[pos:pos + length])
pos += length
joint[lengths[-1]] = joint.get(lengths[-1], 0) + w
z = sum(joint.values())
return {r: v / z for r, v in sorted(joint.items())}, z
def test_worked_example():
xs = [0.2, -0.5, 0.4, 3.9, 4.3, 3.6]
post, _ = bocpd(xs, GaussianKnownVariance(0.0, 3.0, 1.0), constant_hazard(10))
assert map_run_lengths(post) == [1, 2, 3, 1, 2, 3]
assert abs(post[3][1] - 0.7985) < 1e-4
assert abs(post[5][3] - 0.9394) < 1e-4
def test_edge_cases():
post, ev = bocpd([], BetaBernoulli(), constant_hazard(5))
assert post == [] and ev == 1
post, ev = bocpd([1], BetaBernoulli(), constant_hazard(5))
assert post == [{1: 1}] and ev == Fraction(1, 2)
def test_beta_bernoulli_matches_enumeration_exact():
rng = random.Random(2007)
hazards = [constant_hazard(Fraction(3)), constant_hazard(Fraction(7, 2)), lambda r: Fraction(1, r + 1)]
for trial in range(120):
n = rng.randint(1, 8)
xs = [rng.randint(0, 1) for _ in range(n)]
a, b = Fraction(rng.randint(1, 4)), Fraction(rng.randint(1, 4), rng.randint(1, 2))
hz = hazards[trial % 3]
post, ev = bocpd(xs, BetaBernoulli(a, b), hz)
for t in range(1, n + 1):
want, z = enumerate_posterior(xs[:t], lambda seg: beta_bernoulli_marginal(seg, a, b), hz, Fraction(1))
assert post[t - 1] == want
assert ev == z
def test_gaussian_matches_enumeration():
rng = random.Random(1)
for trial in range(500):
n = rng.randint(1, 7)
xs = [rng.gauss(rng.choice([0.0, 3.0]), 1.0) for _ in range(n)]
mu0, s0, s = rng.uniform(-1, 1), rng.uniform(0.5, 3), rng.uniform(0.5, 2)
lam = rng.uniform(2, 20)
post, ev = bocpd(xs, GaussianKnownVariance(mu0, s0, s), constant_hazard(lam))
want, z = enumerate_posterior(xs, lambda seg: gaussian_marginal(seg, mu0, s0, s), constant_hazard(lam))
assert set(post[-1]) == set(want)
assert all(abs(post[-1][r] - want[r]) < 1e-12 for r in want)
assert abs(ev - z) <= 1e-12 * z
def test_pruning_is_close_and_keeps_few_run_lengths():
rng = random.Random(3)
xs = []
for k in range(10):
mu = rng.choice([-3.0, 0.0, 3.0])
xs += [rng.gauss(mu, 1.0) for _ in range(30)]
model = GaussianKnownVariance(0.0, 3.0, 1.0)
exact, _ = bocpd(xs, model, constant_hazard(30))
pruned, _ = bocpd(xs, model, constant_hazard(30), prune=1e-6)
assert map_run_lengths(exact) == map_run_lengths(pruned)
assert max(len(p) for p in pruned) <= 100
assert len(exact[-1]) == len(xs)
gap = max(abs(e[r] - p.get(r, 0.0)) for e, p in zip(exact, pruned) for r in e)
assert gap < 1e-4
History
Adams and MacKay (2007) published the run-length recursion with a hazard function and conjugate exponential family models. In the same year, Fearnhead and Liu (2007) gave an online filter for the time of the most recent change point, which is the same quantity, and added resampling to bound the cost. Both build on earlier Bayesian work on the exact posterior of multiple change points in offline data.
References
- Ryan Prescott Adams and David J. C. MacKay, Bayesian online changepoint detection, arXiv preprint 0710.3742 (2007), the run-length model with a hazard function, the recursion for the joint of the run length and the data, and the conjugate exponential family updates
- Paul Fearnhead and Zhen Liu, On-line inference for multiple changepoint problems, Journal of the Royal Statistical Society Series B 69(4) (2007), the online recursion for the time of the most recent change point and the resampling step that bounds the number of stored values
- Charles Truong, Laurent Oudre and Nicolas Vayatis, Selective review of offline change point detection methods, Signal Processing 167 (2020), the parts on the Bayesian formulation and on the comparison of online and offline methods
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 KJZYAX Edit this page History Report an error Markdown