Algorithmadvanced
PELT
Also called pruned exact linear time, PELT change-point algorithm.
Finds the change points that minimize a penalized cost exactly. It runs the optimal partitioning recursion and prunes start points that can never be optimal again.
- Solves
- Change-point detection
- Time
- Θ(n²) worst
- Space
- Θ(n) extra
- Where
- n = the length of the series, with each segment cost computed in O(1)
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Rebecca Killick, Paul Fearnhead, Idris A. Eckley, 2012
PELT finds the exact minimizer of a penalized segmentation cost: the sum over segments of a cost of each segment, plus a penalty for each change point. It runs the optimal partitioning recursion, a dynamic programme like the one for segmented least squares, , which costs segment costs, and adds one rule: a start point is removed for good when . If the cost satisfies , a removed point can never be the best last change again, so the result is still exactly optimal. The worst case stays quadratic, but when the number of changes grows in proportion to , the expected cost is linear (Killick, Fearnhead and Eckley 2012).
In plain words
You want to cut a series into pieces so that each piece is well described by a simple model, and each cut costs a fixed fee so that you do not cut everywhere. For each position, you work out the cheapest way to cut the series up to that position, by trying every place where the last piece could start. That is exact but slow, because the list of possible starts grows. The trick is that some starts are already so bad that no future data can make them the best choice. When a clear change has happened, all starts before it become hopeless, and you cross them off. Then the list stays short and the work stays close to one pass.
The problem
Given , a segment cost , written , and a penalty , find change points that minimize
Here is the last index of segment . A usual cost is the residual sum of squares for a change in mean, , which is twice the Gaussian negative log likelihood with unit variance up to a constant per point. Usual penalties are , close to the BIC, and times the number of parameters added per change, the AIC. See change-point detection for the other formulations.
The algorithm
PELT(n, C, β, K) ▷ C(s, t) is the cost of x_{s+1..t}; K satisfies the pruning condition- 1
F(0) ← -β; R ← {0} - 2
for t ← 1 to n do - 3
F(t) ← min over s in R of [F(s) + C(s, t) + β] - 4
last(t) ← the smallest s in R that attains the minimum - 5
R ← {s in R : F(s) + C(s, t) + K ≤ F(t)} ∪ {t} - 6
follow last from n back to 0 and return F(n) and the change points last(n), last(last(n)), ... that are positive
is the optimal penalized cost of . The start value makes the first segment free of the penalty. Line L3 is the optimal partitioning recursion of Jackson et al. (2005), restricted to the set of candidate last change points. Line L5 is the pruning step. Without it, at time and the method is plain optimal partitioning. For the residual sum of squares, prefix sums of and make each cost .
Example
Take , the residual sum of squares, and :
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 1/2 | 2/3 | 14/3 | 31/6 | 16/3 | 17/3 | 29/3 | 61/6 | |
| last | 0 | 0 | 0 | 3 | 3 | 3 | 3 | 7 | 7 |
| at line L3 | 1 | 2 | 3 | 4 | 2 | 3 | 4 | 5 | 2 |
At the candidates are , and the values are , , and . Only is at most , so becomes : the points before the first jump are gone for good. The same happens at , where shrinks from to . Back-tracking from gives last and last, so the change points are with segments , and , and .
The penalty picks the number of changes. The smallest residual sums of squares for change points are , , , and . Adding gives about 55.56, 39.50, 10.17, 13.67 and 17.33, so wins.
Correctness
The proof is in full below. In outline:
- Optimal partitioning. Every segmentation of has a last segment , and the rest is a segmentation of . So , and back-tracking the minimizers gives an optimal segmentation.
- Pruning lemma. Suppose that for all . If at some , then for every ,
so is strictly worse than as the last change point before , and it is never a minimizer again. 3. Exactness. A minimizer of the full recursion is never pruned, so the minimum over equals the minimum over all , and the smallest minimizer is the same. PELT returns the same and the same change points as optimal partitioning.
For the residual sum of squares the condition holds with , because cutting a segment can only lower its residual sum of squares. The same is true for any cost that is minus a maximized log likelihood. A smaller prunes less and stays exact; a larger breaks the condition and can remove the optimum.
Proof: The pruning rule of PELT never removes an optimal last change point, so PELT returns the exact optimal partitioningfull
Notation is that of the page. For , is the cost of the segment . A segmentation of is a set of change points , and its penalized cost is with and . Let be the smallest penalized cost over all segmentations of , and . We assume that there is a constant with
For write .
Lemma 1 (optimal partitioning). For , . If attains the minimum, then an optimal segmentation of followed by the segment is an optimal segmentation of .
Proof. Group the segmentations of by their last change point , with when there is none. For , the segmentations with last change point are exactly the segmentations of followed by the segment , and the penalized cost is the cost of the first part plus , since one change point is added. The smallest such cost is . For the only segmentation is one segment, of cost . Taking the minimum over gives the recursion, and the second claim follows from the same grouping.
Lemma 2 (pruning). Let . If , then .
Proof. By (P) with , split point and , . Hence
Lemma 3 (the invariant). For every , when line L3 runs: (a) for every ; (b) and ; (c) every has for some .
Proof. By induction on . For , line L1 gives and , and (c) is empty.
Assume the invariant at . We first show that line L3 sets . By (a), the values computed at line L3 are for , so by Lemma 1. Let be a minimizer of over . By (c), is not outside , since a point outside is strictly beaten by some point and so is not a minimizer. So and . This gives (a) at .
Line L5 keeps , so (b) holds at . For (c) at , let with after line L5. Either was outside before step , or it was removed at line L5 of step . In the second case , so Lemma 2 gives . In the first case, was removed at line L5 of some step , and the same argument at that step gives , so Lemma 2 with gives . In both cases is strictly beaten.
Theorem. If (P) holds, PELT returns and an optimal segmentation. Moreover, at every the minimizers of over are exactly the minimizers of over , so last is the smallest minimizer of the full recursion and PELT returns the same change points as optimal partitioning without pruning.
Proof. By Lemma 3, for every . Every minimizer over the full set lies in , as shown in the proof of Lemma 3, and the minimum values over and over the full set agree, so the two sets of minimizers are equal. Then last attains the minimum in Lemma 1. Back-tracking at line L6 builds, from the end, a segmentation whose last segment is in front of an optimal segmentation of . By Lemma 1 and induction on , the result is optimal. The loop at line L6 stops because last.
The condition for the usual costs. If for some loss , for example the residual sum of squares or minus a maximized log likelihood, then (P) holds with : using one parameter for both parts gives
If (P) holds for some , it holds for every smaller , and then line L5 removes fewer points, so the result stays exact.
Cost. Step evaluates segment costs, so the total is at most . The expected linear cost under conditions on the data is a theorem of Killick, Fearnhead and Eckley (2012) and is not proved here.
Complexity
Each step costs segment costs. In the worst case nothing is pruned, , and the total is , the same as optimal partitioning. Series without changes come close to this case. Killick, Fearnhead and Eckley (2012) proved that the expected cost is when the number of changes grows linearly with and some further conditions hold; this is cited, not proved here. Measured average and largest sizes of per step, with , Gaussian noise of variance 1, and one random generator with seed 3 (as in the tests), used for the rows in order, the series with changes before the series without:
| changes every 100 points: mean | largest | total cost evaluations | no change: mean | largest | total cost evaluations | |
|---|---|---|---|---|---|---|
| 1000 | 86.6 | 222 | 86617 | 319.3 | 703 | 319330 |
| 2000 | 82.8 | 206 | 165506 | 1000.5 | 2000 | 2001000 |
| 4000 | 91.5 | 317 | 365879 | 1751.9 | 3701 | 7007526 |
| 8000 | 90.1 | 340 | 720453 | 2940.7 | 5423 | 23525670 |
With a change every 100 points (a new mean drawn from ), the mean size of stays near 90 and the total grows in proportion to . Without changes the total grows by a factor between 3.4 and 6.3 each time doubles, much faster than ; at nothing was pruned at all. The extra space is for , last and .
Properties
- Exact. For a cost with the pruning property, the output is a global minimizer of the penalized cost, not an approximation.
- Same tie rule as the full recursion. Pruned points are strictly worse, so the choice of the smallest minimizer is not changed.
- Fast when changes are frequent. The cost is close to linear exactly in the case where binary segmentation is slowest.
- Penalized, not constrained. It finds the best segmentation for a given , not for a given number of changes. For a fixed number of changes use the segment neighbourhood recursion of Auger and Lawrence (1989).
- Any additive cost. Mean, variance, mean and variance, Poisson rate and regression costs all work when they satisfy the condition.
Variants and improvements
- Optimal partitioning. The same recursion without line L5, always (Jackson et al. 2005).
- Segment neighbourhood. A recursion over the number of segments that gives the best segmentation for every up to a bound, in (Auger and Lawrence 1989). Segmented least squares is a close relative for line fits.
- Functional pruning (FPOP). Maidstone et al. (2017) keep, for each candidate, the set of segment parameters for which it is still optimal, and drop it when that set is empty. This prunes more than PELT, also when there are few changes.
- CROPS. Haynes, Eckley and Fearnhead (2017) find the optimal segmentations for all penalties in an interval with a small number of PELT runs, which helps to choose .
- Approximate search. Binary segmentation is faster when there are few changes but is not exact.
- Online methods. For a stream, use the CUSUM or Bayesian online changepoint detection.
When to use it
Use PELT when the whole series is available, the segment cost is additive and has the pruning property, and the exact penalized optimum is wanted. If there are few changes in a very long series, PELT can be close to quadratic; use FPOP or binary segmentation then.
Pitfalls
- Wrong . The constant must satisfy for every split. For the residual sum of squares . A positive there can prune the optimal last change, and then the result is not optimal.
- Penalty on the wrong scale. The residual sum of squares must be divided by the noise variance before is meaningful. With the raw sum and a large variance, PELT finds many false changes.
- Dependent or heavy-tailed noise. The Gaussian cost then finds too many changes. Use a robust cost, or estimate the dependence and inflate the penalty.
- Expecting linear time always. Without changes nothing is pruned and the cost is quadratic, as the table shows.
- Minimum segment length. Costs such as the variance cost are on segments of length 1. Enforce a minimum length; the recursion and the pruning rule extend directly.
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/pelt-algorithm/. The authors are listed in prov/8P0SSC.jsonl.
"""PELT: pruned exact linear time search for multiple change points.
Minimize sum over segments of C(segment) + beta * (number of change points)
over all partitions of x_1..x_n into contiguous segments. The optimal
partitioning recursion is F(0) = -beta and
F(t) = min over 0 <= s < t of F(s) + C(s+1..t) + beta. PELT keeps only the
candidates s that can still be optimal: s is dropped at time t when
F(s) + C(s+1..t) + K > F(t). With a cost that satisfies
C(a..b) + K <= C(a..s) + C(s+1..b) for all a <= s < b, a dropped candidate is
never optimal later, so PELT returns the same optimum as the full O(n^2)
recursion. Worst case O(n^2) cost evaluations; the expected linear cost holds
only under conditions on the data (Killick, Fearnhead and Eckley 2012).
"""
from collections.abc import Callable, Sequence
from fractions import Fraction
from typing import TypeVar
Num = TypeVar("Num", float, Fraction)
def rss_cost(xs: Sequence[Num]) -> Callable[[int, int], Num]:
"""C(s+1..t) = sum of (x_i - segment mean)^2 for i in s+1..t, via prefix sums. O(1) per call.
This is twice the Gaussian negative log likelihood with unit variance, up
to a constant per point, and it satisfies the PELT condition with K = 0.
"""
zero = xs[0] - xs[0] if xs else 0
s1 = [zero]
s2 = [zero]
for x in xs:
s1.append(s1[-1] + x)
s2.append(s2[-1] + x * x)
def cost(s: int, t: int) -> Num:
tot = s1[t] - s1[s]
return s2[t] - s2[s] - tot * tot / (t - s)
return cost
def pelt(n: int, cost: Callable[[int, int], Num], beta: Num, k: Num = 0,
sizes: list[int] | None = None) -> tuple[Num, list[int]]:
"""Optimal penalized partition of 1..n. Returns (F(n), sorted change points).
cost(s, t) is the cost of the segment x_(s+1)..x_t. A change point tau
means a new segment starts at tau + 1. Ties choose the smallest s. If
sizes is a list, the candidate set size at each t is appended to it.
"""
f = [-beta] + [None] * n # @line L1
last = [0] * (n + 1) # @line L1
cand = [0] # @line L1
for t in range(1, n + 1): # @line L2
vals = [(f[s] + cost(s, t) + beta, s) for s in cand] # @line L3
best, arg = min(vals)
f[t] = best # @line L3
last[t] = arg # @line L4
if sizes is not None:
sizes.append(len(cand))
cand = [s for v, s in vals if v - beta + k <= best] + [t] # @line L5
cps = []
t = n
while t > 0: # @line L6
t = last[t]
if t > 0:
cps.append(t)
return f[n], sorted(cps) # @line L6
def optimal_partitioning(n: int, cost: Callable[[int, int], Num], beta: Num) -> tuple[Num, list[int]]:
"""The full O(n^2) recursion of Jackson et al. (2005), with the same tie rule."""
f = [-beta] + [None] * n
last = [0] * (n + 1)
for t in range(1, n + 1):
f[t], last[t] = min((f[s] + cost(s, t) + beta, s) for s in range(t))
cps = []
t = n
while t > 0:
t = last[t]
if t > 0:
cps.append(t)
return f[n], sorted(cps)
test_pelt_algorithm.py 107 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pelt-algorithm/. The authors are listed in prov/8P0SSC.jsonl.
import itertools
import math
import random
from fractions import Fraction
from pelt_algorithm import optimal_partitioning, pelt, rss_cost
def l1_cost(xs):
"""Sum of |x_i - median| over the segment: another cost with the PELT property for K = 0."""
def cost(s, t):
seg = sorted(xs[s:t])
med = seg[(len(seg) - 1) // 2]
return sum(abs(x - med) for x in seg)
return cost
def penalized(cost, n, beta, cps):
bounds = [0] + list(cps) + [n]
return sum(cost(a, b) for a, b in zip(bounds, bounds[1:])) + beta * len(cps)
def brute_force(n, cost, beta):
best = None
for m in range(n):
for cps in itertools.combinations(range(1, n), m):
v = penalized(cost, n, beta, cps)
if best is None or v < best:
best = v
return best
def test_worked_example():
xs = [Fraction(v) for v in [1, 0, 1, 5, 6, 5, 6, 1, 0]]
sizes = []
value, cps = pelt(len(xs), rss_cost(xs), Fraction(4), sizes=sizes)
assert value == Fraction(61, 6)
assert cps == [3, 7]
assert sizes == [1, 2, 3, 4, 2, 3, 4, 5, 2]
def test_edge_cases():
xs = [Fraction(3)]
assert pelt(1, rss_cost(xs), Fraction(1)) == (Fraction(0), [])
xs = [Fraction(v) for v in [0, 0, 10, 10]]
assert pelt(4, rss_cost(xs), Fraction(1))[1] == [2]
assert pelt(4, rss_cost(xs), Fraction(1000))[1] == []
# A zero penalty and a constant series: one segment still wins on ties.
assert pelt(5, rss_cost([Fraction(2)] * 5), Fraction(0))[1] == []
def test_equals_optimal_partitioning_exact():
rng = random.Random(2012)
for trial in range(500):
n = rng.randint(1, 30)
xs = [Fraction(rng.randint(-5, 5)) + (Fraction(rng.randint(0, 3)) * 3 if (i // 7) % 2 else 0)
for i in range(n)]
beta = Fraction(rng.randint(0, 40), rng.randint(1, 4))
cost = rss_cost(xs) if trial % 2 else l1_cost(xs)
assert pelt(n, cost, beta) == optimal_partitioning(n, cost, beta)
def test_equals_brute_force_over_all_partitions():
rng = random.Random(1989)
for trial in range(200):
n = rng.randint(1, 10)
xs = [Fraction(rng.randint(-4, 4)) for _ in range(n)]
beta = Fraction(rng.randint(0, 20), rng.randint(1, 3))
cost = rss_cost(xs) if trial % 2 else l1_cost(xs)
value, cps = pelt(n, cost, beta)
assert value == brute_force(n, cost, beta)
assert penalized(cost, n, beta, cps) == value
def test_smaller_k_is_exact_and_too_large_k_is_not():
rng = random.Random(5)
broken = 0
for _ in range(100):
n = rng.randint(1, 20)
xs = [Fraction(rng.randint(-3, 3)) for _ in range(n)]
beta = Fraction(rng.randint(1, 10))
ref = optimal_partitioning(n, rss_cost(xs), beta)
# K = -2 prunes less than the valid K = 0, so the answer stays exact.
assert pelt(n, rss_cost(xs), beta, k=Fraction(-2)) == ref
# K = 2 violates C(a..s) + C(s+1..b) + K <= C(a..b) for the RSS cost; it may prune the optimum.
value = pelt(n, rss_cost(xs), beta, k=Fraction(2))[0]
assert value >= ref[0]
broken += value > ref[0]
assert broken > 0
def test_pruning_keeps_candidate_sets_small_with_regular_changes():
rng = random.Random(3)
n = 2000
xs = []
mu = 0
for i in range(n):
if i % 100 == 0:
mu = rng.choice([-2, -1, 0, 1, 2])
xs.append(rng.gauss(mu, 1.0))
sizes = []
value, cps = pelt(n, rss_cost(xs), 2 * math.log(n), sizes=sizes)
assert sum(sizes) / n < 150
ref = optimal_partitioning(300, rss_cost(xs[:300]), 2 * math.log(n))
assert abs(pelt(300, rss_cost(xs[:300]), 2 * math.log(n))[0] - ref[0]) < 1e-9
History
Auger and Lawrence (1989) gave the segment neighbourhood dynamic programme for a fixed number of segments. Jackson et al. (2005) gave the optimal partitioning recursion for a penalized number of segments. Killick, Fearnhead and Eckley (2012) added the pruning step, proved that it keeps the exact optimum, and proved the expected linear cost under conditions on the data. Maidstone et al. (2017) compared inequality pruning with functional pruning, and Haynes, Eckley and Fearnhead (2017) gave CROPS for a range of penalties.
References
- 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 optimal partitioning recursion, the pruning condition on the cost with the constant K, the proof that pruning keeps the optimum, and the conditions for an expected linear cost
- Brad Jackson, Jeffrey D. Scargle and others, An algorithm for optimal partitioning of data on an interval, IEEE Signal Processing Letters 12(2) (2005), the optimal partitioning recursion over the position of the last change point
- I. E. Auger and C. E. Lawrence, Algorithms for the optimal identification of segment neighborhoods, Bulletin of Mathematical Biology 51(1) (1989), the segment neighbourhood recursion for a fixed number of segments
- Robert Maidstone, Toby Hocking, Guillem Rigaill and Paul Fearnhead, On optimal multiple changepoint algorithms for large data, Statistics and Computing 27(2) (2017), functional pruning (FPOP and pDPA) and its comparison with the inequality pruning of PELT
- Kaylea Haynes, Idris A. Eckley and Paul Fearnhead, Computationally efficient changepoint detection for a range of penalties, Journal of Computational and Graphical Statistics 26(1) (2017), the CROPS algorithm that finds the optimal segmentations for all penalties in an interval
- Charles Truong, Laurent Oudre and Nicolas Vayatis, Selective review of offline change point detection methods, Signal Processing 167 (2020), the sections on cost functions, penalties and exact search 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 8P0SSC Edit this page History Report an error Markdown