Segmentation, Warping and Clustering of Multivariate Time Series in PythonThe mvtsa toolbox

Chapter 4
Cost-based segmentation

Most segmentation methods minimize a sum of segment costs, eq. (2.1). This chapter takes the three ingredients apart. The cost decides which changes are seen: shifts of the level, the variance, the correlation, the trend, the dynamics or the relation between variables. The search decides how the minimum is found: exactly by dynamic programming, or greedily by merging or splitting segments. The selection decides how many segments there are. Bottom-up merging receives special attention: one run produces a whole hierarchy of segmentations, which the package exposes as a merge tree with a segmentogram, merge persistence and the relative reduction rate of the cost.

4.1 Segment costs

A cost ℓ(a,b) measures how badly one model fits the samples of the segment [a,b). Table 4.1 lists the costs of the package. Every cost precomputes what it can on the whole series in fit, so that error(a, b) is cheap: the L2 and linear costs need only cumulative sums of the samples and of their products with time, the Gaussian and PCA costs cumulative sums of the outer products 𝐱t𝐱t𝖳, from which the covariance of any segment, and hence its eigenvalues, follows in O(n2) plus an eigendecomposition.

Table 4.1. Segment costs. 𝐱¯ab and Σ^ab are the mean and covariance of the segment, λi its eigenvalues in decreasing order, k a kernel.
Cost

ℓ(a,b)

detects
"l2"

∑ t=ab−1∥𝐱t −𝐱¯ab∥2

level
"l1"

∑ t∥𝐱t −medab∥1

level, robustly
"normal"

(b −a)log⁡detΣ^ab

level, variance, correlation
"linear"

residual sum of squares of a line in t per variable

trend
"ar"

residual sum of squares of an AR(q) model per variable

dynamics (univariate)
"kernel"

∑ tk(𝐱t,𝐱t)− 1 b−a ∑ s,tk(𝐱s,𝐱t)

distribution
"pca"

(b −a)∑ i>pλi (Q), (b −a)∑ i≤pλi (T2)

correlation structure
"regression"

residual of regressing the targets on the other variables

relation between variables

The kernel cost with a Gaussian kernel compares segment distributions in a reproducing kernel Hilbert space [72, 73]; for long series it can use random Fourier features. The PCA cost, which sums the Q or the (unscaled) T2 statistics of the samples under the local PCA model of the segment, is the subject of chapter 5; its two parts add up to the L2 cost. The regression cost is the model-based cost of the energy-targeting segmentation of Abonyi, Kulcsár, Balaton and Nagy [16]: a segment is homogeneous if one linear model predicts the key indicator from the operating variables. The example below compares five costs on a series with changes of the level, the variance and the correlation: the Gaussian and kernel costs see every change, the L2 and linear costs only the level shifts; the PCA cost reacts to the correlation changes and finds every boundary, because each of them changes the correlations as well.

rows = [] 
for cost in ("l2", "normal", "linear", "kernel", "pca"): 
    seg = sg.BottomUp(cost, n_segments=5, initial_size=10).segment(X) 
    rows.append( 
        {"cost": cost, **evaluate_segmentation(cps, seg, len(X), margin=10)} 
    ) 
print(pd.DataFrame(rows)[["cost", "f1", "covering", "hausdorff"]])
   

4.2 Search strategies

Exact search. For a fixed number of segments, (2.1) is solved exactly by the dynamic program of segment neighbourhoods [74]: with Fk(t) the minimal cost of [0,t) in k segments, Fk(t) = min s<t{Fk−1(s) + ℓ(s,t)}, which costs O(cT2) evaluations of ℓ (OptimalPartition). With a penalty instead of a fixed c, optimal partitioning computes F(t) = min s<t{F(s) + ℓ(s,t) + β}; PELT prunes every candidate s that can never become optimal again, F(s) + ℓ(s,t) > F(t), and runs in linear expected time when the number of change points grows with T [24] (PELT). The default penalty is of BIC type, the number of segment parameters times log⁡T (scaled by a robust noise variance for least-squares costs); penalty_path traces the number of change points over a range of penalties, in the spirit of CROPS [75].

Greedy searches. Top-down or binary segmentation splits recursively at the point that decreases the cost most [76] (TopDown). Bottom-up segmentation starts from many small segments and repeatedly merges the adjacent pair whose union increases the cost least [77, 78] (BottomUp, algorithm 4.1). The sliding window grows a segment until its cost exceeds a threshold (SlidingWindow); SWAB combines a sliding buffer with bottom-up merging inside it for on-line use [77] (SWAB). The window discrepancy method scores every position by the cost reduction of splitting a window centred on it and picks the peaks (WindowDiscrepancy). Figure 4.1 compares the strategies with the Gaussian cost.

Algorithm\special {t4ht^+}

searches = { 
    "bottom-up": sg.BottomUp("normal", n_segments=5, initial_size=10), 
    "top-down": sg.TopDown("normal", n_segments=5, jump=5), 
    "optimal": sg.OptimalPartition("normal", n_segments=5, jump=10), 
    "PELT": sg.PELT("normal", penalty=250, jump=5, min_size=20), 
    "window": sg.WindowDiscrepancy("normal", width=40, n_segments=5), 
} 
for name, s in searches.items(): 
    seg = s.segment(X) 
    print( 
        f"{name:10s}", 
        seg.change_points, 
        round(evaluate_segmentation(cps, seg, len(X), 10)["covering"], 3), 
    )
   

Figure 4.1

Figure 4.1. A series with changes of the level, the variance and the correlation, segmented by PELT with the Gaussian cost; true change points as orange marks at the top. Produced by examples/02_cost_segmentation/plot_01_costs_and_search.py.

Open in ColabExample plot_01_costs_and_search.py in the gallery

Bottom-up merging is the workhorse of this book. It is simple, fast with a heap of merge costs, and it works with any cost, including costs that have no cumulative-sum shortcut and dissimilarities between adjacent segments that are not costs at all (section 6.4). Its initial segment length matters: segments must hold enough samples for the model of the cost – for a PCA model of n variables with L lags, at least a few times n(L + 1).

4.3 The merge hierarchy

A bottom-up run that continues to a single segment produces every segmentation from the finest to the coarsest, each obtained from the previous one by removing one change point. The package keeps this hierarchy as a MergeTree: the initial change points, the change point removed by every merge, the merge criteria and the total cost after every merge. cut(c) returns the change points of the level with c segments, cost_curve the total cost as a function of c, levels all segmentations. Two new tools make the hierarchy readable (fig. 4.2).

Segmentogram. The segmentogram draws the levels of the hierarchy as rows – the finest at the bottom, the coarsest at the top – with the change points of every level as ticks. A change point that survives many merges forms a long vertical line; spurious boundaries disappear after a few merges.

Merge persistence. In analogy with topological persistence, every initial change point is born at level zero and dies when it is removed. Measuring the death on the scale of the merge criterion – the running maximum of the merge costs, so that the levels form a filtration – makes the persistence comparable across change points: a boundary between genuinely different segments is removed only at a high merge cost. The change points ranked by persistence give the most important boundaries first, and a large gap in the logarithmic persistences suggests the number of segments.

bu = sg.BottomUp("pca", initial_size=10, cost_params={"n_components": 1}) 
tree = bu.full_tree(X) 
print("levels:", tree.n_levels, "| 5 segments:", tree.cut(5), "| true:", cps) 
pers = tree.persistence() 
print( 
    "most persistent change points:", 
    sorted(pers, key=pers.get, reverse=True)[:4], 
)
   

Figure 4.2

Figure 4.2. Segmentogram of a bottom-up run with the PCA cost on a series with five correlation regimes (rows: levels with 2 to 12 segments) and the persistence of the change points (right). The four true boundaries survive to the top; the others vanish within a few merges. Produced by examples/02_cost_segmentation/plot_02_segmentogram.py.

Open in ColabExample plot_02_segmentogram.py in the gallery

4.4 How many segments?

The total cost decreases monotonically with the number of segments, so it cannot choose c by itself. The package offers five rules (select_n_segments):

They agree when the segments are clearly different and disagree otherwise, which is itself informative; the stability analysis of section 10.4 provides an independent check.

for method, kw in [ 
    ("knee", {}), 
    ("rr", {"rr_threshold": 0.05}), 
    ("bic", {}), 
    ("persistence", {}), 
    ("permutation", {"n_permutations": 19, "random_state": 0}), 
]: 
    n, info = sg.select_n_segments( 
        X, "l2", method, max_segments=12, initial_size=5, **kw 
    ) 
    print(f"{method:12s} -> {n} segments") 
print("true number of segments:", len(cps) + 1)
   

Figure 4.3

Figure 4.3. Total cost (line) and relative reduction rate RR(c) (bars) of the hierarchy of fig. 4.2. The reduction rate collapses after c = 5, the true number of segments. Produced by examples/02_cost_segmentation/plot_02_segmentogram.py.

In a nutshell: Cost-based segmentation

A segmentation method combines a cost, a search and a selection rule. Costs decide what is homogeneous: levels (L2, L1), distributions (Gaussian, kernel), trends (linear), dynamics (AR), correlation structure (PCA), relations between variables (regression). Exact searches (optimal partitioning, PELT) minimize (2.1); greedy ones (top-down, bottom-up, sliding window, SWAB) approximate it quickly and work with any cost. A full bottom-up run yields a merge tree: its segmentogram, the persistence of its change points and the relative reduction rate of its cost curve support the choice of the number of segments, together with the knee, BIC and permutation-test rules. In mvtsa: get_cost, BottomUp, TopDown, OptimalPartition, PELT, SWAB, MergeTree, select_n_segments, penalty_path.