Algorithm Search⌘K

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.

Time
Θ(n²) worst
Space
Θ(n) extra
Where
n = the number of observations read, with O(1) work per conjugate update; step t costs Θ(t)
Properties
deterministicexactonlineiterative
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 rtr_t: the number of observations since the last change, the new one included. The model is a renewal process: a segment that has lasted rr points ends with probability H(r)H(r), 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 rr points costs O(1)O(1), and the posterior at time tt follows from the one at time t−1t - 1 by one growth step and one change step. Each step costs O(t)O(t) time and memory, or O(1)O(1) when small posterior values are dropped. A sharp rise of P(rt=1)P(r_t = 1), 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 x1,x2,…x_1, x_2, \ldots arrive one at a time. The model is:

  1. Segments. The series is cut into segments by a renewal process. A segment that has run for rr points ends after its rr-th point with probability H(r)H(r). The first segment starts at t=1t = 1. A constant hazard H(r)=1/λH(r) = 1/\lambda gives geometric segment lengths with mean λ\lambda.
  2. Parameters. Each segment has its own parameter θ\theta, drawn from a prior π\pi, independently of the other segments and of the segmentation.
  3. Data. Given the segments and their parameters, the points are independent, and a point of a segment with parameter θ\theta has density p(x∣θ)p(x \mid \theta).

The run length rt∈{1,…,t}r_t \in \{1, \ldots, t\} is the number of points of the current segment up to and including xtx_t. The task is to compute P(rt=r∣x1..t)P(r_t = r \mid x_{1..t}) for each tt as xtx_t arrives, and the evidence p(x1..t)p(x_{1..t}). The predictive density of a point given the rr points before it in its segment is

πt(r)=p(xt∣xt−r..t−1)=∫p(xt∣θ) π(θ∣xt−r..t−1) dθ,\pi_t^{(r)} = p(x_t \mid x_{t-r..t-1}) = \int p(x_t \mid \theta)\,\pi(\theta \mid x_{t-r..t-1})\,d\theta,

and πt(0)=∫p(xt∣θ) π(θ) dθ\pi_t^{(0)} = \int p(x_t \mid \theta)\,\pi(\theta)\,d\theta. See change-point detection for the other formulations.

The algorithm

  1. BOCPD(x_1, x_2, ..., H, prior)
  2. 1P ← empty map; stats ← empty map; Z_all ← 1 ▷ P(r) = P(r_{t-1} = r | x_{1..t-1})
  3. 2for t ← 1, 2, ... as x_t arrives do
  4. 3π(r) ← predictive of x_t from stats(r), for each r in P; π_0 ← predictive of x_t from the prior
  5. 4J(r + 1) ← P(r) π(r) (1 - H(r)), for each r in P ▷ the segment goes on
  6. 5J(1) ← π_0 Σ_r P(r) H(r), and J(1) ← π_0 when t = 1 ▷ a new segment starts at x_t
  7. 6stats(r + 1) ← update(stats(r), x_t) for each r in P; stats(1) ← update(empty, x_t)
  8. 7Z ← Σ_r J(r); Z_all ← Z_all · Z; P ← J / Z ▷ P(r) = P(r_t = r | x_{1..t})
  9. 8return the posteriors P after each step and the evidence Z_all

Line L3 uses the sufficient statistics of the last rr points, so it costs O(1)O(1) per run length for a conjugate model. For a normal mean with known variance σ2\sigma^2 and prior N(μ0,σ02)N(\mu_0, \sigma_0^2), the statistics are the count rr and the sum SS, and the predictive is normal with precision-weighted mean (μ0/σ02+S/σ2)/(1/σ02+r/σ2)(\mu_0/\sigma_0^2 + S/\sigma^2)/(1/\sigma_0^2 + r/\sigma^2) and variance 1/(1/σ02+r/σ2)+σ21/(1/\sigma_0^2 + r/\sigma^2) + \sigma^2. Lines L4 and L5 are the growth and change steps. Line L7 normalizes and keeps the evidence p(x1..t)=∏sZsp(x_{1..t}) = \prod_s Z_s.

Example

Let σ=1\sigma = 1, the prior be N(0,32)N(0, 3^2), the hazard H=1/10H = 1/10, and the data 0.2,−0.5,0.4,3.9,4.3,3.60.2, -0.5, 0.4, 3.9, 4.3, 3.6. The run-length posteriors, rounded to 4 decimals, are:

tt xtx_t r=1r = 1 r=2r = 2 r=3r = 3 r=4r = 4 r=5r = 5 r=6r = 6 most probable rr
1 0.2 1 1
2 −0.5-0.5 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 t=4t = 4 the predictive density of 3.93.9 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 P(r4=1)≈0.80P(r_4 = 1) \approx 0.80. After that the run length grows again from the change at t=4t = 4. The most probable run lengths 1,2,3,1,2,31, 2, 3, 1, 2, 3 give one change point, before x4x_4. The evidence is p(x1..6)≈3.39×10−6p(x_{1..6}) \approx 3.39 \times 10^{-6}.

Correctness

The recursion is exact for the model. The proof is in full below. In outline, let Jt(r)=p(rt=r,x1..t)J_t(r) = p(r_t = r, x_{1..t}).

  1. The run length is a Markov chain. Given rt−1=rr_{t-1} = r, the next run length is 11 with probability H(r)H(r) and r+1r + 1 with probability 1−H(r)1 - H(r), 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.
  2. The predictive depends only on the current segment. Given the whole segmentation up to tt, xtx_t is independent of all points outside the current segment, because the parameters of different segments are independent. So p(xt∣x1..t−1,rt=r)=πt(r−1)p(x_t \mid x_{1..t-1}, r_t = r) = \pi_t^{(r-1)}.
  3. The recursion. By the chain rule and facts 1 and 2,
Jt(r+1)=Jt−1(r) (1−H(r)) πt(r),Jt(1)=πt(0)∑rJt−1(r) H(r),J_t(r + 1) = J_{t-1}(r)\,(1 - H(r))\,\pi_t^{(r)}, \qquad J_t(1) = \pi_t^{(0)}\sum_r J_{t-1}(r)\,H(r),

with J1(1)=π1(0)J_1(1) = \pi_1^{(0)}. Dividing by p(x1..t−1)p(x_{1..t-1}) gives lines L4 and L5, the normalizer of line L7 is p(xt∣x1..t−1)p(x_t \mid x_{1..t-1}), 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 r1=1r_1 = 1, and given r1,…,rt−1r_1, \ldots, r_{t-1}, the run length rtr_t equals 1 with probability H(rt−1)H(r_{t-1}) and rt−1+1r_{t-1} + 1 otherwise. (ii) Each segment jj has a parameter θj\theta_j, and θ1,θ2,…\theta_1, \theta_2, \ldots are i.i.d. from the prior π\pi and independent of the segmentation. (iii) Given the segmentation and the parameters, x1,x2,…x_1, x_2, \ldots are independent, and a point of segment jj has density p(⋅∣θj)p(\cdot \mid \theta_j). All densities are with respect to a fixed measure, and πt(r)=p(xt∣xt−r..t−1)\pi_t^{(r)} = p(x_t \mid x_{t-r..t-1}) is the predictive density of the page, computed under the model of one segment, with πt(0)\pi_t^{(0)} the prior predictive. Write rt=(r1,…,rt)\mathbf r_t = (r_1, \ldots, r_t) and Jt(r)=p(rt=r,x1..t)J_t(r) = p(r_t = r, x_{1..t}).

The sequence rt\mathbf r_t determines the segmentation of 1,…,t1, \ldots, t, and rt=rr_t = r means that the current segment is {t−r+1,…,t}\{t - r + 1, \ldots, t\}.

Lemma 1 (transition). P(rt=⋅∣rt−1,x1..t−1)=P(rt=⋅∣rt−1)P(r_t = \cdot \mid \mathbf r_{t-1}, x_{1..t-1}) = P(r_t = \cdot \mid r_{t-1}), given by H(rt−1)H(r_{t-1}) for the value 1 and 1−H(rt−1)1 - H(r_{t-1}) for the value rt−1+1r_{t-1} + 1.

Proof. By (i), rtr_t is a function of rt−1r_{t-1} and a fresh coin with success probability H(rt−1)H(r_{t-1}), independent of everything else before time tt. The data x1..t−1x_{1..t-1} are, by (ii) and (iii), functions of rt−1\mathbf r_{t-1}, the parameters and independent noise, all independent of that coin given rt−1\mathbf r_{t-1}. So conditioning on x1..t−1x_{1..t-1} as well as on rt−1\mathbf r_{t-1} does not change the law of the coin. □\square

Lemma 2 (predictive). For r∈{1,…,t}r \in \{1, \ldots, t\}, p(xt∣rt,x1..t−1)=πt(rt−1)p(x_t \mid \mathbf r_t, x_{1..t-1}) = \pi_t^{(r_t - 1)} on the event rt=rr_t = r. In particular this conditional density depends on rt\mathbf r_t only through rtr_t.

Proof. Fix rt\mathbf r_t with rt=rr_t = r. The segmentation of 1,…,t1, \ldots, t is then fixed, and the current segment jj is {t−r+1,…,t}\{t - r + 1, \ldots, t\}. By (ii) and (iii), the points of segments other than jj are functions of parameters θi\theta_i, i≠ji \ne j, and noise, all independent of (θj,xt−r+1,…,xt)(\theta_j, x_{t-r+1}, \ldots, x_t). So, given rt\mathbf r_t, the vector (xt−r+1,…,xt)(x_{t-r+1}, \ldots, x_t) is independent of the other earlier points, and

p(xt∣rt,x1..t−1)=p(xt∣rt,xt−r+1..t−1).p(x_t \mid \mathbf r_t, x_{1..t-1}) = p(x_t \mid \mathbf r_t, x_{t-r+1..t-1}).

Given rt\mathbf r_t, the points xt−r+1,…,xtx_{t-r+1}, \ldots, x_t are i.i.d. given θj\theta_j with θj∼π\theta_j \sim \pi, which is the model of one segment, so the right side is ∫p(xt∣θ)π(θ∣xt−r+1..t−1) dθ=πt(r−1)\int p(x_t \mid \theta)\pi(\theta \mid x_{t-r+1..t-1})\,d\theta = \pi_t^{(r-1)}. □\square

Lemma 3 (the joint recursion). J1(1)=π1(0)J_1(1) = \pi_1^{(0)}, and for t≥2t \ge 2,

Jt(r+1)=Jt−1(r) (1−H(r)) πt(r)(1≤r≤t−1),Jt(1)=πt(0)∑r=1t−1Jt−1(r) H(r).J_t(r + 1) = J_{t-1}(r)\,(1 - H(r))\,\pi_t^{(r)} \quad (1 \le r \le t - 1), \qquad J_t(1) = \pi_t^{(0)}\sum_{r=1}^{t-1}J_{t-1}(r)\,H(r).

Proof. For t=1t = 1, r1=1r_1 = 1 and x1x_1 has the prior predictive density. For t≥2t \ge 2, by the chain rule,

p(rt,x1..t)=p(rt−1,x1..t−1) P(rt∣rt−1,x1..t−1) p(xt∣rt,x1..t−1).p(\mathbf r_t, x_{1..t}) = p(\mathbf r_{t-1}, x_{1..t-1})\,P(r_t \mid \mathbf r_{t-1}, x_{1..t-1})\,p(x_t \mid \mathbf r_t, x_{1..t-1}).

By Lemmas 1 and 2 the last two factors are P(rt∣rt−1)P(r_t \mid r_{t-1}) and πt(rt−1)\pi_t^{(r_t - 1)}, which depend on rt−1\mathbf r_{t-1} only through rt−1r_{t-1}. Sum over r1,…,rt−2r_1, \ldots, r_{t-2} with rt−1r_{t-1} and rtr_t fixed:

p(rt−1,rt,x1..t)=Jt−1(rt−1) P(rt∣rt−1) πt(rt−1).p(r_{t-1}, r_t, x_{1..t}) = J_{t-1}(r_{t-1})\,P(r_t \mid r_{t-1})\,\pi_t^{(r_t - 1)}.

If rt=r+1≥2r_t = r + 1 \ge 2, the only rt−1r_{t-1} with positive transition probability is rr, with probability 1−H(r)1 - H(r), which gives the first formula. If rt=1r_t = 1, every rt−1r_{t-1} contributes with probability H(rt−1)H(r_{t-1}), which gives the second. □\square

Theorem. After line L7 at step tt, P(r)=P(rt=r∣x1..t)P(r) = P(r_t = r \mid x_{1..t}) for every r∈{1,…,t}r \in \{1, \ldots, t\}, the stored statistics stats(r)(r) summarize xt−r+1..tx_{t-r+1..t}, and Zall=p(x1..t)Z_{\mathrm{all}} = p(x_{1..t}). The step costs O(t)O(t) predictive evaluations and updates.

Proof. By induction on tt. Before step 1, PP is empty and Zall=1=p(no data)Z_{\mathrm{all}} = 1 = p(\text{no data}). Suppose the claim holds after step t−1t - 1, so P(r)=Jt−1(r)/p(x1..t−1)P(r) = J_{t-1}(r)/p(x_{1..t-1}) and stats(r)(r) summarizes the last rr points. Then line L3 computes π(r)=πt(r)\pi(r) = \pi_t^{(r)} and π0=πt(0)\pi_0 = \pi_t^{(0)}. Lines L4 and L5 compute J(⋅)=Jt(⋅)/p(x1..t−1)J(\cdot) = J_t(\cdot)/p(x_{1..t-1}) by Lemma 3; for t=1t = 1, line L5 gives J(1)=π1(0)=J1(1)J(1) = \pi_1^{(0)} = J_1(1) directly. Line L6 moves each statistic up by one run length and adds xtx_t, so stats(r+1)(r + 1) summarizes xt−r..tx_{t-r..t}, and stats(1)(1) summarizes xtx_t alone. At line L7, Z=∑rJt(r)/p(x1..t−1)=p(x1..t)/p(x1..t−1)=p(xt∣x1..t−1)Z = \sum_r J_t(r)/p(x_{1..t-1}) = p(x_{1..t})/p(x_{1..t-1}) = p(x_t \mid x_{1..t-1}), so ZallZ_{\mathrm{all}} becomes p(x1..t)p(x_{1..t}), and P=J/Z=Jt/p(x1..t)P = J/Z = J_t/p(x_{1..t}), which is the posterior by Bayes' theorem. Each step loops over at most t−1t - 1 stored run lengths. ■\blacksquare

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 tt there are tt run lengths, so lines L3 to L7 cost Θ(t)\Theta(t) time with O(1)O(1) conjugate updates, and Θ(n2)\Theta(n^2) for nn observations. The memory is Θ(t)\Theta(t): 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 O(1)O(1) 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 tt, 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 rt=0r_t = 0 mean that a change happened at tt, so their rtr_t 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 t=4t = 4 in the example. Use a decision rule, such as P(rt≤w)>1/2P(r_t \le w) > 1/2 for a small window ww, and state it.
  • Unbounded cost. Without pruning, the cost grows with tt, 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.

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

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

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