Chapter 6
Probabilistic, profile-based and state segmentation
Not every segmentation problem fits the cost-and-search form of chapter 4. This chapter collects the other families: Bayesian on-line detection, which tracks the posterior of the time since the last change; hidden Markov and sparse Gaussian state models, which give recurring segments the same label; segment-then-cluster state detection; profile methods, which find changes of shape from nearest-neighbour structure; predictive homogeneity, which lets any scikit-learn model judge whether two segments differ; consensus, which combines segmenters; and stream processing. Benchmarks find no segmenter that dominates on all data [31, 32], so knowing when each family works is as important as the algorithms themselves.
6.1 Bayesian on-line change point detection
Adams and MacKay track the posterior distribution of the run length , the number of samples since the last change, with an exact recursion [25]. Within a run the samples are independent draws from a model with a conjugate prior; with a constant hazard (the prior expected run length is ),
where is the posterior predictive density given the last samples – a multivariate Student for the Normal–inverse-Wishart model of the package (model="full"), or a product of univariate Student densities for independent Normal–Gamma models ("diag"). The run-length posterior is truncated at max_run. With a constant hazard the probability of equals at every step, so the evidence for a change at is read a few samples later: change_probability_[t] is the posterior probability, after delay more samples, that a new run started at , and its peaks above a threshold are the change points. The prior covariance is set from a robust estimate of the noise level (the median absolute first difference), which makes the detector usable without tuning on standardized data.
bo = sg.BOCPD(hazard=150, model="full") seg = bo.segment(X) print("detected:", seg.change_points, "\ntrue: ", cps) print(evaluate_segmentation(cps, seg, len(X), margin=10)["f1"])
6.2 States: segments that recur
A process that switches among a few operating regimes produces segments that recur. State detection gives recurring segments the same label, which is what an operator wants to know: not only that the process changed, but into which known regime. Three detectors are implemented.
A Gaussian HMM [91] with full or diagonal covariances is fitted by expectation–maximization with a scaled forward–backward recursion, restarted from several -means initializations. A pseudo-count added to the self-transitions in every M-step (the sticky prior, after [92]) discourages implausibly short visits; after Viterbi decoding, runs shorter than min_duration are absorbed by their neighbours. The number of states can be selected by BIC (n_states="bic").
Segment, then cluster. Any segmenter cuts the series; every segment is described by a local model – a Gaussian , a PCA model or its mean – and the segment models are clustered hierarchically (StateSegmenter). This is the clustering of multivariate windows by the similarity of their PCA models of Singhal and Seborg [93], generalized to any segmenter, descriptor and distance. The default distance is the 2-Wasserstein distance of the Gaussians,
| (6.3) |
which compares level and covariance in one number [94]. Short segments – typically transitions – give unreliable models; they are left out of the clustering and assigned afterwards to the nearest state.
Sparse Gaussian states. Every state is a Gaussian on short stacked windows with a sparse precision matrix, estimated by the graphical lasso, and the state sequence is decoded by dynamic programming with a penalty per switch (SparseGaussianStateSegmenter). This is the Toeplitz inverse covariance-based clustering of Hallac et al. [95] without its block-Toeplitz constraint: the sparse precision matrix shows which variables interact in each state.
models = { "sticky HMM": sg.GaussianHMMSegmenter( n_states=3, sticky=10, min_duration=10 ), "segment + cluster": sg.StateSegmenter(n_states=3), "sparse Gaussian": sg.SparseGaussianStateSegmenter( n_states=3, window=2, beta=40 ), } rows = [] for name, m in models.items(): s = m.segment(R) rows.append( { "method": name, **evaluate_segmentation( cps, s, len(R), margin=10, true_states=states ), } ) print(pd.DataFrame(rows)[["method", "f1", "covering", "state_ari"]].round(3))
The BIC of the HMM on these data asks for four states rather than three: the fourth state collects the few samples of the smooth transitions, which none of the regime models explains. Information criteria count such systematic deviations as structure – a reminder that a selected number of states is a property of the model as much as of the process.
6.3 Changes of shape: ClaSP and FLUSS
When segments differ in the shape of repeating patterns rather than in their statistics – a gait changing from walking to running, a machine cycle changing its profile – subsequence methods work best. FLUSS [27] draws an arc from every subsequence to its nearest neighbour (the matrix-profile index, section 3.6) and counts the arcs crossing every position; few crossings, relative to the count expected without regimes, mark a boundary. ClaSP [28] labels the subsequences left of a candidate split 0 and those right of it 1, and scores the split by the cross-validated accuracy of a -nearest-neighbour classifier; the split with the highest score is accepted if the score is high enough, and the halves are segmented recursively. The package computes the classification profile of all splits in from a single -NN profile, by counting for every subsequence the largest split at which the majority of its neighbours lies to its right.
Both profiles score splits between subsequences: a subsequence that starts at index covers , so the index of the best split lies about half a window before the change in sample time. mvtsa moves the reported change point and the profile by by default (center=True), which removes this systematic bias; the original convention is available with center=False. The z-normalized profiles see only shape; normalize=False makes them sensitive to level and amplitude as well.
clasp = sg.ClaSPSegmenter(width=40, n_segments=3) seg = clasp.segment(x) print("ClaSP:", seg.change_points, "| width", clasp.width_)
6.4 Predictive homogeneity
Two adjacent segments belong together if no learning machine can tell their samples apart. This is the classifier two-sample test of Lopez-Paz and Oquab [96]: train a classifier to predict from which segment a sample comes; if its cross-validated accuracy is at chance level, the segments come from the same distribution. mvtsa turns the test into a merging criterion: the dissimilarity of two adjacent segments is the balanced accuracy rescaled to , , and bottom-up merging (NeighborMergeSegmenter) joins the least distinguishable pair first. The classifier is any scikit-learn estimator: a linear model sees level shifts, quadratic discriminant analysis also covariance changes, a random forest nonlinear differences; stacking short windows instead of single samples (window) lets it see dynamics. A regression variant measures cross-prediction: a model fitted on one segment is applied to the other, and the loss relative to its cross-validated loss on its own segment is the dissimilarity – for chosen targets from chosen inputs, or for every variable from all the others. The batch, merging counterpart of the self-supervised idea of ClaSP, predictive homogeneity is the most flexible criterion of the package: whatever a model can learn, it can segment.
rows = [] for name, est in [ ("logistic", LogisticRegression(max_iter=500)), ("QDA", QuadraticDiscriminantAnalysis()), ("random forest", RandomForestClassifier(n_estimators=60, random_state=0)), ]: s = sg.PredictiveSegmenter( "classifier", estimator=est, n_segments=4, initial_size=30 ).segment(X) rows.append( {"estimator": name, **evaluate_segmentation(cps, s, len(X), margin=15)} ) print(pd.DataFrame(rows)[["estimator", "f1", "covering"]].round(3))
6.5 Consensus segmentation
Different costs, searches and parameters make different mistakes. A consensus of several segmenters is more robust than any of them, and it quantifies the uncertainty of every boundary. Every member with change points and weight votes with a Gaussian kernel of bandwidth ; the boundary agreement
| (6.4) |
is the weighted fraction of members that place a change point near , and its peaks above a threshold (one half by default) are the consensus change points (ConsensusSegmenter, fig. 6.5). The same profile, computed over perturbed copies of the data instead of over different methods, measures stability (section 10.4).
members = [ sg.BottomUp("normal", n_segments=5, initial_size=10), sg.PELT("normal", penalty=200, jump=5, min_size=20), sg.TopDown("kernel", n_segments=5, jump=5), sg.BOCPD(hazard=150), sg.WindowDiscrepancy("normal", width=40, n_segments=5), ] cons = sg.ConsensusSegmenter(members, threshold=0.5) seg = cons.segment(X) for m, s in zip( ["bottom-up", "PELT", "top-down", "BOCPD", "window"], cons.members_, strict=True, ): print(f"{m:9s} {s.change_points}") print("consensus", seg.change_points, "| true", cps) print(evaluate_segmentation(cps, seg, len(X), margin=10)["f1"])
6.6 Streams
Three detectors process data sample by sample. Recursive PCA (section 5.3) and BOCPD have their own on-line recursions. A multivariate CUSUM chart [97] accumulates the excess of the squared Mahalanobis distance of new samples from a reference distribution, , signals when exceeds , and re-estimates the reference from the next samples (CUSUMDetector). Finally, StreamSegmenter applies any batch segmenter to a sliding buffer and reports a change point once it lies far enough from the end of the buffer to be stable; the reporting delay is the price of using a batch method on line.
stream = sg.StreamSegmenter( sg.PELT("l2", jump=5), window=300, step=25, guard=20 ) reported = [] for t, x in enumerate(X): for c in stream.partial_fit(x): reported.append((t, c)) for t, c in reported: print(f"at sample {t:5d}: change point {c} (delay {t - c})")
In a nutshell: Probabilistic, profile-based and state segmentation
BOCPD tracks the run-length posterior exactly with conjugate Gaussian models and reads the change evidence with a short delay. Sticky HMMs, segment-then-cluster with Wasserstein distances and sparse Gaussian states label recurring regimes. ClaSP and FLUSS find changes of shape from nearest-neighbour structure; centring their profiles removes a half-window bias. Predictive homogeneity turns any scikit-learn classifier or regressor into a bottom-up merging criterion. Consensus combines segmenters by boundary agreement. CUSUM, recursive PCA, BOCPD and a buffered wrapper of batch methods handle streams. In mvtsa: BOCPD, GaussianHMMSegmenter, StateSegmenter, SparseGaussianStateSegmenter, ClaSPSegmenter, FLUSSSegmenter, PredictiveSegmenter, ConsensusSegmenter, CUSUMDetector, StreamSegmenter.