Chapter 5
Latent-variable segmentation
This chapter is the core of the group’s contribution to segmentation. A segment is homogeneous if one latent-variable model – a PCA model, a dynamic PCA model of the lagged variables, or a probabilistic PCA model inside a fuzzy cluster – describes all of its samples. We start with the PCA costs of bottom-up segmentation, extend them to dynamics with dynamic PCA, run them on line with recursive PCA and a variable forgetting factor, make the segments fuzzy with the modified Gath–Geva algorithm, and finally segment historical data by the information they carry for parameter estimation. Each method answers a question that the costs of chapter 4 cannot.
5.1 PCA segmentation
Abonyi, Feil, Németh and Árva observed that the homogeneity of a segment of process data is best measured by the hidden structure of the variables rather than by their means [1, 2]: a segment is homogeneous if a PCA model with few components reconstructs its samples well. Bankó made this the cost of bottom-up segmentation [8]. For a segment with covariance eigenvalues and a local PCA model of components,
| (5.1) |
where is the unscaled Hotelling statistic used by Bankó, the variation inside the model. The cost reacts to changes of the correlation structure, the cost to drifts within it, and their sum is the L2 cost (fig. 5.1). The aggregate can be the sum (long segments weigh more) or the mean (segments compete on equal terms). With cumulative outer-product sums, the covariance of any segment is available in and the cost of a merge in one eigendecomposition. The number of components is a fixed integer or a fraction of explained variance, resolved once on the whole series and then kept fixed, so that all segments are compared with models of equal size.
rows = [] for stat in ("Q", "T2", "both"): seg = sg.PCASegmenter( n_segments=5, n_components=1, statistic=stat ).segment(X) rows.append( { "statistic": stat, **evaluate_segmentation(cps, seg, len(X), margin=6), } ) print(pd.DataFrame(rows)[["statistic", "f1", "covering", "hausdorff"]])
A closely related criterion compares adjacent segments directly instead of costing them one by one: KrzanowskiSegmenter merges neighbouring segments in the order of the dissimilarity of their PCA models, optionally adding a term for the distance of their means – the bottom-up form of the similarity-driven merging that Dobos and Abonyi used for Fisher matrices (section 5.5). On a series whose correlation structure switches while the variances stay equal, finds every change and none, as expected. The loadings of the segment models (fig. 5.2) explain the segmentation: every segment has its own first principal direction.
5.2 Dynamic PCA segmentation
When segments differ in their dynamics – a time constant, a damping, a dead time – while their static correlations stay similar, a static PCA model sees little. Dynamic PCA [46] fits the PCA model to the lag matrix (2.5): an exact dynamic relation such as becomes a static relation among the columns of , i.e. a direction of (near-)zero variance, and a change of the parameters rotates this direction. Segmenting with the PCA costs of the lag matrix detects changes of the dynamics [6, 13]. Two details matter in practice. First, the initial segments must be long enough for a model of variables; the package enforces at least samples. Second, the number of lags must be chosen. Ku, Storer and Georgakis count the near-zero eigenvalues of the lag-matrix covariance and increase until no new linear relation appears; slow dynamics and step-like inputs create approximate relations to which this count is sensitive. The package therefore also offers a criterion based on the smallest eigenvalue: the ratio drops by orders of magnitude at the lag that completes a dynamic relation and only slightly at superfluous lags, and the selected lag is the last drop larger than a factor (select_dpca_lag; default factor 8).
static = sg.PCASegmenter(n_segments=3, n_components=1).segment(Y) dynamic = sg.DPCASegmenter(n_segments=3, lags=2, n_components=5).segment(Y) for name, s in [("PCA", static), ("DPCA", dynamic)]: print( f"{name:5s}", s.change_points, evaluate_segmentation(cps, s, len(Y), margin=15)["f1"], )
Y1, _, _ = mv.datasets.make_dynamic_switching( order=1, n_segments=3, length=300, random_state=0 ) print("selected lag, first-order system: ", select_dpca_lag(Y1)) print("selected lag, second-order system:", select_dpca_lag(Y)) print( "Ku et al. (1995) count of relations:", select_dpca_lag(Y1, method="ku"), select_dpca_lag(Y, method="ku"), )
The pH neutralization process [80] is the classical test of this idea, used by Bankó, Dobos and Abonyi [6]: the titration curve makes the process gain change by orders of magnitude around neutrality, so the local dynamics differ between operating ranges (fig. 5.4). Section 13.2 uses the same segmentation to identify local models.
5.3 On-line segmentation with recursive PCA
Batch segmentation needs the whole record. Dobos and Abonyi developed an on-line version for monitoring [13]: a recursive (dynamic) PCA model is updated with every sample, and the Krzanowski similarity between the running model and the model of the current segment signals a change. The recursive update of the mean and the covariance with a forgetting factor [81] is
| (5.2) |
A constant trades tracking speed against noise. A variable forgetting factor in the spirit of Fortescue, Kershenbaum and Ydstie [82] shortens the memory when a sample is poorly explained: with the Mahalanobis distance of under ,
| (5.3) |
Algorithm 5.1 states the detector. Because the recursive model needs some samples to follow a change, the detection comes with a delay; the package optionally removes it by a retrospective search for the best two-segment split of the samples of the closing segment, which places the reported change point where the change happened rather than where it was noticed.
stream = sg.RecursivePCASegmenter( threshold=0.7, n_components=1, forgetting=0.97, warmup=60, patience=8, scale=(X[:200].mean(0), X[:200].std(0)), ) for t, x in enumerate(X): if stream.partial_fit(x): print(f"sample {t}: change declared at {stream.change_points_[-1]}")
Open in ColabExample plot_03_recursive_pca.py in the gallery
5.4 Fuzzy segmentation
Transitions between operating regimes are rarely abrupt. The modified Gath–Geva algorithm of Abonyi, Feil, Németh and Árva treats segmentation as fuzzy clustering of the time-extended samples [1, 2, 83]. Every cluster is the product of a Gaussian in time, which keeps the cluster contiguous and defines a fuzzy set of the segment on the time axis, and a probabilistic PCA model of the variables [84, 85], which measures the homogeneity of the segment by its latent structure:
| (5.4) |
The memberships follow the Gath–Geva (fuzzy maximum likelihood) iteration with distances , where are the cluster priors. The number of segments is chosen by compatible cluster merging: adjacent clusters with similar PPCA subspaces and overlapping time fuzzy sets are merged (algorithm 5.2). The package adds two safeguards learned from practice: clusters with negligible total membership are pruned before merging, and the crisp segmentation is read off the memberships by a dynamic program that enforces a monotone sequence of labels, which removes the flicker of the raw maximum-membership labels at the boundaries. With lags > 0 the PPCA models use lag-extended samples, which combines the fuzzy segmentation with dynamic PCA.
gg = sg.GGSegmenter( n_segments=6, n_components=1 ) # start with more clusters than needed seg = gg.segment(X) print( "clusters after merging:", seg.n_segments, "| change points:", seg.change_points, "| true:", cps, ) print(evaluate_segmentation(cps, seg, len(X), margin=10)["f1"])
Open in ColabExample plot_04_fuzzy_segmentation.py in the gallery
5.5 Segmentation by Fisher information
When the purpose of an analysis is to identify a process model, the useful parts of a historical record are those that carry information on the model parameters. Optimal experiment design measures this information by the Fisher information matrix [86]; Dobos, Bankó and Abonyi turned it into a segmentation criterion [11, 12, 14, 87, 88]. With the output sensitivities computed along the measured inputs, the information of a segment is
| (5.5) |
where is the inverse covariance of the measurement errors. Scalar OED criteria summarize it: (D-criterion), the trace of (A), the smallest eigenvalue, and the condition number , the modified E-criterion of Bernaerts et al. [89]. Two segmentation principles are implemented (FisherSegmenter). The criterion method computes a criterion in a moving window – the “evaluating time series” of Dobos et al. – and segments it with a univariate method (bottom-up L2 or PAA); the segments are then ranked by their information content. The eigen method compares the directions of the information: neighbouring segments are merged in the order of the Krzanowski similarity of the leading eigenvectors of their Fisher matrices, so that the final segments are informative about different parameter combinations [14]. Sensitivities come from the model by finite differences (finite_difference_sensitivities) or, for ARX models, analytically (arx_sensitivities).
names = ["kp", "kI", "kfm"] p0 = np.array([MMA_PARAMETERS[k] for k in names]) def simulate(p): return simulate_mma_cstr(FI, params=dict(zip(names, p, strict=True))) S = sg.finite_difference_sensitivities( simulate, p0, rel_step=1e-4 ) # (T, 1, 3), scaled fs = sg.FisherSegmenter( n_segments=5, criterion="logD", window=20, initial_size=10 ).fit(S) print(fs.segmentation_.change_points) print(fs.ranking_[["segment", "start", "stop", "logD", "E"]].round(2))
5.6 Model-based segmentation of energy indicators
The last latent-variable cost is a plain regression: a segment is homogeneous if one linear model predicts the target from the other variables. Abonyi, Kulcsár, Balaton and Nagy used it to segment energy monitoring data, so that every segment yields a targeting model of the key energy indicator for one operating range [16] (CostRegression). On data whose coefficients change while every variable moves smoothly, the segments coincide with the operating ranges, and the local models are the targets (fig. 5.8). Kalman filtering of noisy measurements before segmentation [3] combines with any of the costs of this chapter through preprocessing.kalman_smoother.
for a, b in reg.segments: A = np.c_[np.ones(b - a), X[a:b, 1:]] coef = np.linalg.lstsq(A, X[a:b, 0], rcond=None)[0] print( f"[{a:4d},{b:4d}) KEI = {coef[0]:6.2f} {coef[1]:+.3f}*load {coef[2]:+.3f}*feed" )
Open in ColabExample plot_06_energy_regression.py in the gallery
In a nutshell: Latent-variable segmentation
A segment is homogeneous if one latent-variable model describes it. The PCA costs sum the eigenvalues outside (, correlation structure) or inside (, drift) a -component model; on the lag matrix they detect changes of the dynamics, with the lag chosen from the smallest eigenvalue. Recursive PCA with a variable forgetting factor and the Krzanowski similarity segments a stream on line, and a retrospective split removes the detection delay. The modified Gath–Geva algorithm makes segments fuzzy by combining Gaussian memberships in time with PPCA models and merges compatible clusters. Fisher information segments historical data by what they say about model parameters; a regression cost by the validity of one input–output model. In mvtsa: PCASegmenter, DPCASegmenter, select_dpca_lag, RecursivePCASegmenter, GGSegmenter, FisherSegmenter, CostRegression, KrzanowskiSegmenter.