Algorithmcore
Binary segmentation
Also called binary segmentation for change points, wild binary segmentation.
Cuts a series at its single best change point, then repeats on each part while the split statistic exceeds a threshold. Cost O(n(m+1)) for m changes, O(n²) in the worst case.
- Solves
- Change-point detection
- Time
- Θ(n(m+1)) worst
- Space
- Θ(n) extra
- Where
- m = the number of change points found; n = the length of the series
- Model
- Real RAM
- Properties
- deterministicnot exactofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- A. J. Scott, M. Knott, L. Yu. Vostrikova, 1974
Binary segmentation finds several changes in the mean of a series by repeated single splits. It looks at the whole series, finds the one split point that best separates it into two parts with different means, and keeps the split if a test statistic exceeds a threshold . Then it does the same on each part, and stops on a part when no split is strong enough. With prefix sums each split statistic costs , so a part of length costs and the whole run costs for change points: when the splits are balanced and in the worst case. It is a greedy method. It does not minimize a global cost, and it can miss short segments that the first split hides. Wild binary segmentation repairs this by also searching random sub-intervals.
In plain words
You have a long record of a measurement and you suspect its average level changed a few times. First you ask: if I could cut the record in exactly one place, where would the two parts differ most? If the difference there is clearly larger than noise, you make the cut. Then you treat each part as a new record and ask the same question. You stop cutting a part when no cut in it gives a clear difference. The method is fast and simple. Its weakness is that it judges each cut alone, so a short burst in the middle of a long flat record can look too small to cut at first, and then it is never found.
The problem
Given , modelled as a piecewise constant mean plus noise of variance , find the change points , where is the last index of segment . See change-point detection for the problem and the exact methods.
For a segment and a split , the CUSUM contrast is
where is the mean of . Its square is the drop in the residual sum of squares when the segment is cut at . Under no change and Gaussian noise, is the absolute value of a standard normal variable for each fixed .
The algorithm
BINARY-SEGMENTATION(x_1, ..., x_n, ζ)- 1
P ← prefix sums of x; stack ← [(0, n)]; CP ← ∅ - 2
while stack is not empty do - 3
pop (s, e); if e - s < 2 then continue ▷ the segment is x_{s+1..e} - 4
b ← the smallest maximizer of C(s, b, e) over s < b < e; c ← C(s, b, e) - 5
if c ≤ ζ then continue ▷ no change in this segment - 6
add b to CP; push (s, b) and (b, e) - 7
return CP in increasing order
Line L4 uses , so each contrast costs and the scan costs . The stack replaces the recursion; the order in which segments are processed does not change the result. Usual thresholds are with a constant a little above 1, for example as in Fryzlewicz (2014), with estimated robustly from the differences . An alternative is to grow the full tree with a very small and choose the number of changes by a criterion such as the BIC.
Example
Take , and
The contrasts on the whole series, , rounded to 3 decimals, are:
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0.783 | 1.472 | 1.700 | 2.082 | 1.259 | 0.693 | 0.088 | 0.735 | 1.567 | 1.084 | 0.783 |
The best split is , and , so 4 is a change point. On the right part the contrasts for are 0.882, 1.102, 1.661, 2.051, 2.647, 1.837 and 1.256, so 9 is a change point. The remaining parts have best contrasts 0.200 on at , 0.112 on and 0.204 on , all below . The result is : means about 0, 2 and 0.
Note that the whole-series contrast at the true change 9 is only 1.567, because the two outer low parts pull the mean of the right side down. The method finds 9 only after the first cut has removed the left part.
Correctness
Binary segmentation is a heuristic: it does not compute an optimal segmentation, and what it returns is defined by the procedure itself. Two facts are proved in full below.
- The contrast is the gain of a cut. For every , , where is the residual sum of squares of about their mean. So line L4 chooses the single cut that best fits a two-mean model to the segment by least squares.
- The stack version computes the recursive definition. Define if or if the best contrast is at most , and otherwise . Each push makes the segment strictly shorter, so the loop ends after at most pops, and it returns exactly .
Fryzlewicz (2014) gives conditions under which binary segmentation is consistent: the segments must not be too short compared to , and the jumps not too small. When these fail, as in the burst example under Variants, it can miss changes.
Proof: The squared CUSUM contrast is the gain in fit of a cut, and the stack procedure computes the recursive binary segmentationfull
Notation is that of the page. For , write for the mean of and , with .
Lemma 1 (the contrast is the gain of a cut). For ,
Proof. Let , , , , and . For any numbers with mean and any , , because the cross term is 0. Apply this to the two parts and add:
Now and , so
Corollary. Line L4 returns a cut that minimizes over , that is, the least squares fit of a model with one change in the segment. The contrast is nonnegative, so maximizing and maximizing give the same .
Lemma 2 (prefix sums). With and , . So each contrast costs after preprocessing, and line L4 costs .
Proof. .
The recursive definition. For let be the smallest maximizer of over , and define
The definition is well founded, because both segments on the right are strictly shorter than .
Theorem. The procedure stops after at most pops and returns in increasing order.
Proof. Consider the multiset of segments on the stack together with the set CP. We claim that the following holds before each test of line L2:
and that the sets on the right are pairwise disjoint. Also the segments in are pairwise disjoint, they lie in , and no element of CP lies strictly inside one of them.
Line L1 makes the claim true with and . Suppose it holds and the loop pops . If , or if at line L5, then by definition and line L4 computed , so removing keeps the identity. Otherwise line L6 adds to CP and pushes and , which replaces by , which is the same set. The point lies strictly inside , while lies strictly inside and strictly inside , so disjointness is kept. The two new segments are disjoint and lie in the old one, so the segment facts are kept.
Termination: each split adds a new point of to CP, and by disjointness no point is added twice, so there are at most splits. Every pop either splits or not, and every segment except is pushed by a split, so the number of pops is at most . When the stack is empty the claim gives , and line L7 sorts it.
Running time. The pops form a binary tree rooted at in which the children of a split segment are its two parts. The segments at one depth are disjoint, so by Lemma 2 the work at one depth is . A path from the root passes through split nodes only, except at its last node, so the depth is at most when change points are found, and the total time is .
Complexity
The segments popped from the stack form a binary tree. Segments at the same depth are disjoint, so the scans of line L4 at one depth cost together. Each internal node of the tree is a change point, so the depth is at most , and the total time is . When the splits are balanced the depth is and the time is . When every split cuts off one point, the depth is and the time is . This happens for with : on every prefix the best cut is . The extra space is for the prefix sums and the stack.
Properties
- Greedy. Each cut is chosen without regard to later cuts, and a cut is never moved.
- Nested results. Lowering only adds change points, so a single run with a small threshold gives the whole sequence of nested segmentations.
- Simple and fast. It needs only prefix sums and one scan per segment.
- Not optimal. For a given number of changes, the segmentation can have a larger residual sum of squares than the best one found by dynamic programming in segmented least squares or PELT.
- Weak on short segments. A short segment far from the ends of a long parent gives a small contrast, because the contrast compares long averages.
Variants and improvements
- Wild binary segmentation (WBS). Fryzlewicz (2014) draws random intervals once. On each segment, line L4 is replaced by a search over the segment itself and every drawn interval inside it, and the largest contrast decides the cut. When is large enough, with high probability some interval contains only one change with enough room on both sides, so short segments are found. The cost is per level of the tree. Example: let be 50 zeros, then 4 values equal to 3, then 50 zeros, so and . The best contrast on the whole series is 1.132 at , below , so binary segmentation finds nothing. WBS with 100 random intervals finds , and so does PELT with penalty .
- Circular binary segmentation. Olshen et al. (2004) look for a pair of cuts at once, the best segment that differs from the rest of the circle. It finds a short middle segment in one step and is standard for DNA copy number data.
- Other costs. The contrast can be replaced by any likelihood ratio for a single change, for example for a change in variance or in a Poisson rate.
- Exact alternatives. PELT and optimal partitioning minimize the penalized cost exactly; their expected cost can be linear when changes are frequent.
- Online detection. For data that arrive one at a time, use the CUSUM or Bayesian online changepoint detection.
When to use it
Use binary segmentation as a fast first pass on long series with a few well separated changes, or to produce the nested set of candidate segmentations for a model selection step. Use WBS or circular binary segmentation when short segments matter, and an exact penalized method when the best segmentation for a given cost is required.
Pitfalls
- Masking. Two changes close together with opposite jumps can cancel in the whole-series contrast, so neither is found. WBS and exact methods are much less affected.
- Threshold on the wrong scale. The threshold must scale with the noise level . Estimate robustly, for example from the median absolute difference of neighbours, because the plain standard deviation of the series includes the jumps.
- Dependent noise. Positive autocorrelation makes contrasts larger under no change, so the method finds false changes. Inflate or model the dependence.
- Reading the order of the cuts as importance. The first cut is the strongest single cut of the whole series, not necessarily the largest jump.
- Off-by-one in the output. Here a change point is the last index of a segment. Other software reports the first index of the new segment.
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/binary-segmentation/. The authors are listed in prov/PQ8R7K.jsonl.
"""Binary segmentation and wild binary segmentation for changes in the mean.
For the segment x_(s+1)..x_e and a split point b with s < b < e, the CUSUM
contrast is
C(s, b, e) = sqrt((b - s)(e - b) / (e - s)) * |mean(x_(s+1..b)) - mean(x_(b+1..e))|.
C(s, b, e)^2 equals the drop in the residual sum of squares when the segment
is cut at b. Binary segmentation cuts at the best b when the contrast exceeds
a threshold zeta and recurses on both halves. With prefix sums each contrast
costs O(1), so one segment of length L costs O(L), each level of the
recursion tree costs O(n), and the whole run costs O(n (m + 1)) for m
change points found: O(n log n) for balanced splits and O(n^2) in the worst case.
"""
import math
import random
from collections.abc import Sequence
def prefix_sums(xs: Sequence[float]) -> list[float]:
out = [0]
for x in xs:
out.append(out[-1] + x)
return out
def contrast(p: Sequence[float], s: int, b: int, e: int) -> float:
"""C(s, b, e) from prefix sums p. Precondition: s < b < e. O(1)."""
left = (p[b] - p[s]) / (b - s)
right = (p[e] - p[b]) / (e - b)
return math.sqrt((b - s) * (e - b) / (e - s)) * abs(left - right)
def contrast_squared(p: Sequence, s: int, b: int, e: int):
"""C(s, b, e)^2 in the arithmetic of p (exact for Fractions)."""
left = (p[b] - p[s]) / (b - s)
right = (p[e] - p[b]) / (e - b)
return (b - s) * (e - b) * (left - right) ** 2 / (e - s)
def best_split(p: Sequence[float], s: int, e: int) -> tuple[int, float]:
"""The smallest b in (s, e) that maximizes C(s, b, e), and the maximum. O(e - s)."""
best_b, best_c = s + 1, -1.0
for b in range(s + 1, e):
c = contrast(p, s, b, e)
if c > best_c:
best_b, best_c = b, c
return best_b, best_c
def binary_segmentation(xs: Sequence[float], zeta: float) -> list[int]:
"""Change points (as last indices of segments, 1-based) found by binary segmentation."""
p = prefix_sums(xs) # @line L1
stack = [(0, len(xs))] # @line L1
cps = [] # @line L1
while stack: # @line L2
s, e = stack.pop() # @line L3
if e - s < 2: # @line L3
continue
b, c = best_split(p, s, e) # @line L4
if c <= zeta: # @line L5
continue
cps.append(b) # @line L6
stack.append((s, b)) # @line L6
stack.append((b, e)) # @line L6
return sorted(cps) # @line L7
def random_intervals(n: int, m: int, rng: random.Random) -> list[tuple[int, int]]:
"""m random intervals (s, e) with 0 <= s < e - 1 < n, drawn uniformly over pairs."""
out = []
while len(out) < m:
s, e = sorted(rng.sample(range(n + 1), 2))
if e - s >= 2:
out.append((s, e))
return out
def wild_binary_segmentation(xs: Sequence[float], zeta: float, intervals: Sequence[tuple[int, int]]) -> list[int]:
"""Fryzlewicz's WBS: on each segment, search the full segment and every drawn interval inside it.
Cost O(sum of interval lengths) per segment visited, so O(M n) per level
for M intervals.
"""
p = prefix_sums(xs)
stack = [(0, len(xs))]
cps = []
while stack:
s, e = stack.pop()
if e - s < 2:
continue
cands = [(s, e)] + [(a, b) for a, b in intervals if s <= a and b <= e]
best = (-1.0, 0)
for a, b in cands:
split, c = best_split(p, a, b)
if c > best[0]:
best = (c, split)
c, split = best
if c <= zeta:
continue
cps.append(split)
stack.append((s, split))
stack.append((split, e))
return sorted(cps)
def default_threshold(n: int, sigma: float = 1.0, factor: float = 1.3) -> float:
"""zeta = factor * sigma * sqrt(2 log n), the form used by Fryzlewicz (2014) for WBS."""
return factor * sigma * math.sqrt(2.0 * math.log(n))
test_binary_segmentation.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/binary-segmentation/. The authors are listed in prov/PQ8R7K.jsonl.
import math
import random
from fractions import Fraction
from binary_segmentation import (
best_split,
binary_segmentation,
contrast,
contrast_squared,
default_threshold,
prefix_sums,
random_intervals,
wild_binary_segmentation,
)
EXAMPLE = [0.1, -0.3, 0.2, 0.0, 2.1, 1.8, 2.2, 1.9, 2.0, -0.1, 0.2, 0.1]
def rss(xs):
if not xs:
return 0
m = sum(xs) / len(xs)
return sum((x - m) ** 2 for x in xs)
def naive_contrast(xs, s, b, e):
left = xs[s:b]
right = xs[b:e]
d = sum(left) / len(left) - sum(right) / len(right)
return math.sqrt(len(left) * len(right) / (e - s)) * abs(d)
def naive_binseg(xs, zeta, s=0, e=None):
"""Plain recursion with O(L) contrasts: the reference for the stack version."""
if e is None:
e = len(xs)
if e - s < 2:
return []
vals = [(naive_contrast(xs, s, b, e), -b) for b in range(s + 1, e)]
c, nb = max(vals)
if c <= zeta:
return []
b = -nb
return sorted(naive_binseg(xs, zeta, s, b) + [b] + naive_binseg(xs, zeta, b, e))
def test_worked_example():
p = prefix_sums(EXAMPLE)
b, c = best_split(p, 0, 12)
assert b == 4 and abs(c - 2.082) < 1e-3
b, c = best_split(p, 4, 12)
assert b == 9 and abs(c - 2.647) < 1e-3
assert binary_segmentation(EXAMPLE, 1.5) == [4, 9]
def test_edge_cases():
assert binary_segmentation([], 1.0) == []
assert binary_segmentation([5.0], 1.0) == []
assert binary_segmentation([0.0, 10.0], 1.0) == [1]
assert binary_segmentation([1.0] * 20, 0.0) == []
def test_contrast_squared_is_rss_drop_exact():
rng = random.Random(1974)
for _ in range(500):
n = rng.randint(2, 15)
xs = [Fraction(rng.randint(-9, 9), rng.randint(1, 3)) for _ in range(n)]
p = prefix_sums(xs)
s = rng.randint(0, n - 2)
e = rng.randint(s + 2, n)
b = rng.randint(s + 1, e - 1)
assert contrast_squared(p, s, b, e) == rss(xs[s:e]) - rss(xs[s:b]) - rss(xs[b:e])
def test_matches_naive_recursion():
rng = random.Random(1981)
for _ in range(500):
n = rng.randint(0, 25)
mu = 0.0
xs = []
for _ in range(n):
if rng.random() < 0.15:
mu = rng.choice([-3.0, 0.0, 3.0])
xs.append(mu + rng.gauss(0.0, 0.5))
zeta = rng.uniform(0.5, 3.0)
assert binary_segmentation(xs, zeta) == naive_binseg(xs, zeta)
def test_argmax_against_brute_force():
rng = random.Random(6)
for _ in range(500):
n = rng.randint(2, 20)
xs = [rng.gauss(0.0, 1.0) for _ in range(n)]
p = prefix_sums(xs)
b, c = best_split(p, 0, n)
vals = [naive_contrast(xs, 0, k, n) for k in range(1, n)]
assert abs(c - max(vals)) < 1e-9
assert abs(contrast(p, 0, b, n) - max(vals)) < 1e-9
def test_misses_a_short_burst_that_wbs_finds():
xs = [0.0] * 50 + [3.0] * 4 + [0.0] * 50
zeta = default_threshold(len(xs))
assert abs(zeta - 3.962) < 1e-3
assert abs(best_split(prefix_sums(xs), 0, len(xs))[1] - 1.1323) < 1e-4
assert binary_segmentation(xs, zeta) == []
intervals = random_intervals(len(xs), 100, random.Random(1))
assert wild_binary_segmentation(xs, zeta, intervals) == [50, 54]
def test_noisy_burst():
rng = random.Random(2014)
xs = [rng.gauss(0, 1) for _ in range(150)] + [rng.gauss(4, 1) for _ in range(6)] + [rng.gauss(0, 1) for _ in range(150)]
zeta = default_threshold(len(xs))
assert binary_segmentation(xs, zeta) == []
found = wild_binary_segmentation(xs, zeta, random_intervals(len(xs), 300, random.Random(2)))
assert any(abs(c - 150) <= 2 for c in found) and any(abs(c - 156) <= 2 for c in found)
def test_wbs_with_no_intervals_is_binary_segmentation():
rng = random.Random(8)
for _ in range(100):
xs = [rng.choice([0.0, 2.0]) + rng.gauss(0, 0.3) for _ in range(rng.randint(0, 30))]
assert wild_binary_segmentation(xs, 1.2, []) == binary_segmentation(xs, 1.2)
History
Scott and Knott (1974) proposed splitting a set of ordered group means into two groups by the largest between-group sum of squares, and then splitting each group again, which is binary segmentation applied to means. Vostrikova (1981, Soviet Mathematics Doklady 24) studied the method for change points in a multivariate process and proved its consistency. Olshen et al. (2004) introduced circular binary segmentation for DNA copy number arrays. Fryzlewicz (2014) introduced wild binary segmentation and analysed both methods.
References
- A. J. Scott and M. Knott, A cluster analysis method for grouping means in the analysis of variance, Biometrics 30(3) (1974), the method of splitting ordered group means into two groups by the largest between-group sum of squares, applied again to each group
- Piotr Fryzlewicz, Wild binary segmentation for multiple change-point detection, Annals of Statistics 42(6) (2014), the CUSUM statistic, the description and consistency conditions of binary segmentation, the wild binary segmentation algorithm, and the threshold of the form C sqrt(2 log n)
- Adam B. Olshen, E. S. Venkatraman, Robert Lucito and Michael Wigler, Circular binary segmentation for the analysis of array-based DNA copy number data, Biostatistics 5(4) (2004), the circular binary segmentation algorithm and its application to copy number data
- R. Killick, P. Fearnhead and I. A. Eckley, Optimal detection of changepoints with a linear computational cost, Journal of the American Statistical Association 107(500) (2012), the discussion of binary segmentation as an approximate search and its comparison with exact penalized segmentation
- Charles Truong, Laurent Oudre and Nicolas Vayatis, Selective review of offline change point detection methods, Signal Processing 167 (2020), the section on search methods, including binary segmentation and its variants
Where this leads
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 PQ8R7K Edit this page History Report an error Markdown