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

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 S with covariance eigenvalues λ1 ≥⋯ ≥λn and a local PCA model of p components,

ℓQ(S) = ∑ t∈SQt = |S|∑ i=p+1nλ i,ℓT2(S) = ∑ t∈ST~t2 = |S|∑ i=1pλ i, (5.1)

where T~t2 = ∥𝐲t∥2 is the unscaled Hotelling statistic used by Bankó, the variation inside the model. The Q cost reacts to changes of the correlation structure, the T2 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 O(n2) 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.

Figure 5.1

Figure 5.1. The two PCA costs of a segment are sums of the eigenvalues of its covariance: those outside the p-dimensional model (ℓQ) and those inside (ℓT2). Their sum is the L2 cost.
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 1 −sPCA 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, Q finds every change and T2 none, as expected. The loadings of the segment models (fig. 5.2) explain the segmentation: every segment has its own first principal direction.

Figure 5.2

Figure 5.2. First principal direction of the PCA model of every segment found by the Q cost. The segments differ in how the four variables load on the common latent factor. Produced by examples/03_latent_segmentation/plot_01_pca_t2_q.py.

Open in ColabExample plot_01_pca_t2_q.py in the gallery

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 yk = a1yk−1 + a2yk−2 + buk−1 becomes a static relation among the columns of 𝐗L, 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 n(L + 1) variables; the package enforces at least 5n(L + 1) 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 L 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 λmin∕λmax 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"), 
)
   

Figure 5.3

Figure 5.3. A second-order system whose damping changes twice while its static gain stays one. Static PCA misses the changes; dynamic PCA with two lags finds both exactly. Produced by examples/03_latent_segmentation/plot_02_dynamic_pca.py.

Open in ColabExample plot_02_dynamic_pca.py in the gallery

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.

Figure 5.4

Figure 5.4. Dynamic PCA segmentation of the simulated pH neutralization process (base flow and pH). The segments follow the operating ranges of the titration curve. Produced by examples/03_latent_segmentation/plot_02_dynamic_pca.py.

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

𝛍t = 𝛍t−1 + (1 −λt)𝐝t,Σt = λt(Σt−1 + (1 −λt)𝐝t𝐝t𝖳),𝐝 t = 𝐱t −𝛍t−1. (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 mt the Mahalanobis distance of 𝐝t under Σt−1,

λt = clip(1 −(1 −λ0)mt∕n,λmin,λmax). (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.

Algorithm\special {t4ht^+}

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]}")
   

Figure 5.5

Figure 5.5. On-line segmentation with recursive PCA. Top: detected (lines) and true (marks) change points; middle: Krzanowski similarity of the running model to the segment model with the threshold; bottom: the variable forgetting factor, which drops after every change. Produced by examples/03_latent_segmentation/plot_03_recursive_pca.py.

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 𝐳t = [t,𝐱t𝖳]𝖳 [1, 2, 83]. Every cluster i 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:

p(𝐳t∣ηi) = 𝒩(t∣vit,σ i2)𝒩(𝐱 t∣𝛍i,𝐖i𝐖i𝖳 + σ x,i2𝐈). (5.4)

The memberships follow the Gath–Geva (fuzzy maximum likelihood) iteration with distances Dit2 = 1∕(αip(𝐳t∣ηi)), where αi 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.

Algorithm\special {t4ht^+}

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"])
   

Figure 5.6

Figure 5.6. Fuzzy segmentation with the modified Gath–Geva algorithm, started with six clusters. Top: the series with the crisp segments; bottom: the fuzzy memberships, which overlap at the transitions. Compatible cluster merging reduces the six initial clusters to the four true segments. Produced by examples/03_latent_segmentation/plot_04_fuzzy_segmentation.py.

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 𝐒t = ∂𝐲t∕∂𝜃 computed along the measured inputs, the information of a segment is

𝐅(a,b) = 1 b −a∑ t=ab−1𝐒 t𝖳𝐐𝐒 t, (5.5)

where 𝐐 is the inverse covariance of the measurement errors. Scalar OED criteria summarize it: log⁡det𝐅 (D-criterion), the trace of 𝐅−1 (A), the smallest eigenvalue, and the condition number λmax∕λmin, 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))
   

Figure 5.7

Figure 5.7. Segmentation of an operating record of the methyl methacrylate polymerization reactor [90] by Fisher information. From top: initiator flow, number-average molecular weight, and the windowed log⁡det𝐅 of the kinetic parameters kp,kI,kfm. The excitation period and the grade transition carry the information; constant operation adds almost nothing. Produced by examples/03_latent_segmentation/plot_05_fisher_mma.py.

Open in ColabExample plot_05_fisher_mma.py in the gallery

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" 
    )
   

Figure 5.8

Figure 5.8. Model-based segmentation of energy monitoring data: the key energy indicator (top) depends linearly on the load and the feed temperature with coefficients that change between operating ranges; the regression cost recovers the ranges. Produced by examples/03_latent_segmentation/plot_06_energy_regression.py.

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 (Q, correlation structure) or inside (T2, drift) a p-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.