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

Chapter 8
Correlation-based and segment-level warping

Sample-level DTW compares multivariate series sample by sample with the Euclidean distance, so it sees levels and ignores how the variables move together. This chapter warps sequences of segments instead. Correlation-based DTW segments every series into pieces of homogeneous correlation structure and aligns the segment sequences with a PCA similarity as local cost; dynamic PCA makes it aware of process dynamics; Riemannian and mixed local distances extend it to segment models that differ in level, scale or trend. For univariate series, the MPLA, SPLA and MDPLA measures warp piecewise linear approximations, and episode alignment compares qualitative trends. Warping a few dozen segments instead of hundreds of samples is also fast.

8.1 Correlation-based dynamic time warping

Bankó and Abonyi combined the two lines of the group’s work, PCA segmentation and DTW, into correlation-based dynamic time warping (CBDTW) [4, 5, 121]. The idea is that in many industrial data sets the correlation of the variables carries the real information, so two series should be compared by the sequence of their correlation structures. PCA similarity factors compare whole series by one correlation structure each [21, 45, 93] and cannot follow changes of the structure within a series; DTW follows the changes but ignores the structure. CBDTW does both (fig. 8.1, algorithm 8.1): every series of a database is segmented bottom-up with the PCA cost of section 5.1; a PCA model is fitted to every segment; and DTW aligns the segment sequences of two series with the local cost 1 −sPCA between their segment models. A query is segmented “according to the database”, with the same settings and scaling. Without warping, comparing segment k with segment k gives the SEGPCA baseline [5] (segpca_distance, CBDTW(warping=False)).

Figure8.1

Figure 8.1. Correlation-based dynamic time warping. Both series are segmented by their correlation structure (the arrows sketch the principal directions of the segment models); DTW then aligns the segment sequences with the dissimilarity 1 −sPCA of the segment models as local cost. Segments of different lengths are matched.
Algorithm\special {t4ht^+}

The number of segments is a parameter of the method. Bankó selected it with the relative reduction rate of the cost curve (section 4.4) on a sample of the database [8]; the precision–recall analysis of retrieval (section 10.3) is the external check. On synthetic on-line signatures – pen position, pressure and angles of several writers, warped and perturbed – CBDTW retrieves the signatures of the same writer as reliably as DTW at a small fraction of the cost (fig. 8.2).

cb = wp.CBDTW(n_segments=10, n_components=2).fit(data) 
path = cb.path(0, 1) 
print( 
    "segments:", 
    len(cb.models_[0]), 
    len(cb.models_[1]), 
    "| CBDTW distance:", 
    round(cb.distance(0, 1), 3), 
)
   

Figure8.2

Figure 8.2. Segment-level alignment of two signatures of the same writer by CBDTW: the coloured bands are the segments of the two series, the lines connect aligned segments. Produced by examples/06_correlation_warping/plot_01_cbdtw_signatures.py.

Open in ColabExample plot_01_cbdtw_signatures.py in the gallery

When the information is in the correlation. The advantage of CBDTW is largest when classes differ in the order of correlation structures rather than in levels or shapes. In the collection of fig. 8.3, four classes share one pool of correlation structures of eight variables and differ only in their sequence, and strong noise covers the variables; sample-level DTW reaches a 1-NN accuracy of 0.80 and a mean average precision of 0.68, CBDTW 1.0 and 0.999.

measures = { 
    "CBDTW": wp.CBDTW(n_segments=8, n_components=2).fit(C), 
    "CBDTW, Grassmann": wp.CBDTW( 
        n_segments=8, n_components=2, local="grassmann" 
    ).fit(C), 
    "DTW": "dtw", 
    "DTW_I": "dtw_i", 
} 
rows, curves = [], {} 
for name, m in measures.items(): 
    D = pairwise_distances(C, metric=m) 
    curves[name] = precision_recall_curve_knn(D, y, r_items=9) 
    rows.append( 
        { 
            "measure": name, 
            "1-NN": knn_accuracy(D, y), 
            "mAP": mean_average_precision(D, y), 
        } 
    ) 
print(pd.DataFrame(rows).round(3).to_string(index=False))
   

Figure8.3

Figure 8.3. Precision–recall curves of retrieval (Bankó’s Algorithm 3.1, section 10.3) on a collection whose classes differ only in the order of their correlation structures. Produced by examples/06_correlation_warping/plot_02_correlation_sequences.py.

Open in ColabExample plot_02_correlation_sequences.py in the gallery

8.2 Process-dynamics-aware warping

In the second thesis of his dissertation, Bankó extended CBDTW with dynamic PCA [6, 8]: the segmentation cost and the segment models are computed on the lag matrix (2.5), so that two series are compared by the sequence of their input–output dynamics (CBDTW(lags=L)). In the collection of fig. 8.4, the classes differ only in the order in which the time constant of a first-order system changes. The static correlation of input and output already reflects the time constant – a slow system follows its input less closely – so static CBDTW is a strong baseline (mAP 0.88); the dynamic segment models capture the input–output relation itself and separate the classes perfectly, while sample-level DTW reaches 0.59. The number of retained components matters: the dynamic relations live in the smallest directions of the lag-matrix covariance, so the best models keep all but the last one to three components.

rows = [] 
for name, m in [ 
    ( 
        "DPCA-CBDTW (2 lags, 4 PCs)", 
        wp.CBDTW(n_segments=3, n_components=4, lags=2).fit(C), 
    ), 
    ("CBDTW (1 PC)", wp.CBDTW(n_segments=3, n_components=1).fit(C)), 
    ("DTW", "dtw"), 
]: 
    D = pairwise_distances(C, metric=m) 
    rows.append( 
        { 
            "measure": name, 
            "1-NN": knn_accuracy(D, y), 
            "mAP": mean_average_precision(D, y), 
        } 
    ) 
print(pd.DataFrame(rows).round(3).to_string(index=False))
   

Figure8.4

Figure 8.4. A series of the collection used in section 8.2: input u and output y of a first-order system whose time constant changes twice. Produced by examples/06_correlation_warping/plot_03_dynamic_cbdtw.py.

Open in ColabExample plot_03_dynamic_cbdtw.py in the gallery

8.3 Riemannian and mixed segment distances

The Krzanowski similarity compares the principal subspaces of two segments and nothing else. When segments also differ in level, scale or covariance shape, other local distances are better. A segment model is a Gaussian (μ,Σ), and symmetric positive definite matrices form a Riemannian manifold with several natural distances (LOCAL_DISTANCES): the log-Euclidean distance ∥log⁡Σ1 −log⁡Σ2∥F [122], the affine-invariant distance ∥log⁡(Σ1−1∕2Σ2Σ1−1∕2)∥F [123], the Bures–Wasserstein distance (trΣ1 + trΣ2 −2tr(Σ11∕2Σ2Σ11∕2)1∕2)1∕2 [94], the 2-Wasserstein distance of the Gaussians (6.3), which adds the means, and the Jeffreys divergence (symmetric Kullback–Leibler). Principal angles give the Grassmann and chordal distances of subspaces, and the λ and Eros similarities weight the angles by the eigenvalues [43, 45].

On real speech data the difference is large. The JapaneseVowels collection [124] holds twelve LPC cepstrum coefficients of nine speakers; the utterances are short (7 to 29 frames), so a segment carries few samples. The correlation structure alone separates the speakers poorly (1-NN accuracy 0.74), while the Gaussian Wasserstein distance between whole-utterance models matches the independent multivariate DTW (0.97) at a fraction of its cost (fig. 8.5).

rows = [] 
for name, m in [ 
    ("DTW", "dtw"), 
    ("DTW_I", "dtw_i"), 
    ("CBDTW, Krzanowski", wp.CBDTW(n_segments=1, n_components=2)), 
    ( 
        "CBDTW, log-Euclidean", 
        wp.CBDTW(n_segments=1, n_components=3, local="log_euclidean"), 
    ), 
    ( 
        "CBDTW, Jeffreys", 
        wp.CBDTW(n_segments=1, n_components=3, local="jeffreys"), 
    ), 
    ( 
        "CBDTW, Gaussian W2", 
        wp.CBDTW(n_segments=1, n_components=3, local="gaussian_w2"), 
    ), 
    ( 
        "CBDTW, Gaussian W2, 2 segments", 
        wp.CBDTW( 
            n_segments=2, n_components=3, local="gaussian_w2", initial_size=6 
        ), 
    ), 
]: 
    t0 = time.perf_counter() 
    D = pairwise_distances(C, metric=m if isinstance(m, str) else m.fit(C)) 
    rows.append( 
        { 
            "measure": name, 
            "1-NN": knn_accuracy(D, y), 
            "mAP": mean_average_precision(D, y), 
            "seconds": time.perf_counter() - t0, 
        } 
    ) 
print(pd.DataFrame(rows).round(3).to_string(index=False))
   

Figure8.5

Figure 8.5. Leave-one-out 1-NN accuracy of sample-level DTW (grey) and of CBDTW with different local distances (blue) on 180 utterances of JapaneseVowels. Produced by examples/06_correlation_warping/plot_04_japanese_vowels.py.

Open in ColabExample plot_04_japanese_vowels.py in the gallery

A mixed segment distance. MixedSegmentDistance combines several aspects of two segment models in a weighted sum: the difference of their levels (in units of the collection standard deviation), of their slope angles, of their principal subspaces (1 −sPCA), of their scales (|log⁡(trΣa∕trΣb)|) and of their durations. It generalizes the MDPLA measure of the next section to multivariate segment models. The weights are learned by leave-one-out accuracy on a simplex grid (learn_segment_weights); the segmentations are computed once, so the search is cheap. On the BasicMotions recordings [125], the learned weighting puts most weight on the correlation structure and the scale and classifies every recording correctly.

model = wp.CBDTW( 
    n_segments=6, 
    n_components=2, 
    local=wp.MixedSegmentDistance( 
        {"level": 1, "trend": 1, "structure": 1, "scale": 1} 
    ), 
) 
best, scores = wp.learn_segment_weights(model, C, y) 
print("learned weights:", best) 
top = sorted(scores.items(), key=lambda kv: -kv[1])[:5] 
print( 
    pd.DataFrame( 
        [{**dict(zip(best, w, strict=True)), "accuracy": a} for w, a in top] 
    ).round(3) 
)
   

8.4 Warping piecewise linear approximations

For univariate series, Bankó and Abonyi defined segment-level dissimilarities of piecewise linear approximations [7]. Every series is approximated by c linear segments (bottom-up PLA, section 3.1); a segment is described by its mean x¯, scaled to [−1,1] by the largest absolute segment mean of the collection, and by the angle of its slope s, arctan⁡(s) scaled by 2∕π. The local dissimilarities of two segments are

dMPLA = |x¯i −ȳj|,dSPLA = 2 π|arctan⁡si −arctan⁡sj|, (8.1) dMDPLA = wMdMPLA + wSdSPLA, (8.2)

and DTW aligns the segment sequences with one of them (PLADistance). MPLA compares levels, SPLA trends, and the mixed MDPLA both. Bankó and Abonyi also introduced the tightness of warping to measure how much a measure warps: the average length of the warping paths relative to the number of segments [7]. A measure that warps less produces more natural alignments, and mixing the level and the trend reduces warping. The right weighting depends on the data, which is why the package learns it (fig. 8.6).

rows = [] 
for dname, (C, y) in datasets.items(): 
    for kind in ("mpla", "spla", "mdpla"): 
        p = wp.PLADistance(n_segments=12, kind=kind).fit(C) 
        tow = wp.tightness_of_warping( 
            list(range(len(C))), p.path, max_pairs=200, random_state=0 
        ) 
        rows.append( 
            { 
                "data": dname, 
                "measure": kind.upper(), 
                "1-NN": knn_accuracy(p.pairwise(), y), 
                "ToW": tow, 
            } 
        ) 
    rows.append( 
        { 
            "data": dname, 
            "measure": "DTW", 
            "1-NN": knn_accuracy(pairwise_distances(C, metric="dtw"), y), 
            "ToW": np.nan, 
        } 
    ) 
print(pd.DataFrame(rows).round(3).to_string(index=False))
   

Figure8.6

Figure 8.6. Leave-one-out 1-NN accuracy of MDPLA on Cylinder–Bell–Funnel as a function of the weight of the mean (wS = 1 −wM). On these data the level carries most of the information. Produced by examples/06_correlation_warping/plot_05_pla_mdpla.py.

Open in ColabExample plot_05_pla_mdpla.py in the gallery

8.5 Aligning qualitative episodes

Balaskó, Bankó and Abonyi compared process trends by their qualitative episodes (section 3.3) [9, 10]. The episode strings of two signals are aligned with the Needleman–Wunsch algorithm [126] (or locally with Smith–Waterman [127]): the score of aligning two episodes comes from a substitution table of the seven primitives – identical primitives score highest, similar ones (a concave and a convex increase) less, opposite ones are penalized – and gaps cost a constant. The score is normalized so that a perfect alignment gives 10. Weighting the substitution scores by the size of the episodes – one third for small, two thirds for medium episodes, by the terciles of their durations and magnitudes – makes small wiggles count less (align_episodes). Because the alignment works on a handful of symbols, it is fast and insensitive to the time scale: a slower and rescaled copy of a signal scores almost 10, a noisy one less, an inverted one much less (fig. 8.7). As an extension, episode_dtw warps episode sequences with a local cost that combines the primitive dissimilarity with the log-ratio of the durations and the relative difference of the magnitudes.

for k in ("slower and scaled", "noisy", "different"): 
    score, pairs = wp.align_episodes(eps["reference"], eps[k]) 
    print( 
        f"reference vs {k:18s}: score {score:5.2f} / 10, " 
        f"episode DTW {wp.episode_dtw(eps[’reference’], eps[k]):.3f}" 
    )
   

Figure8.7

Figure 8.7. Qualitative episodes of the noisy copy of the reference signal used in section 8.5. Produced by examples/06_correlation_warping/plot_07_episodes.py.

Open in ColabExample plot_07_episodes.py in the gallery

In a nutshell: Correlation-based and segment-level warping

CBDTW segments every series by its correlation structure and warps the segment sequences with 1 −sPCA as local cost; without warping it is SEGPCA. Dynamic PCA makes it compare input–output dynamics; Riemannian distances (log-Euclidean, affine-invariant, Bures–Wasserstein, Gaussian W2, Jeffreys) and a learned mixed distance compare richer segment models. MPLA, SPLA and MDPLA warp piecewise linear approximations by level, trend or both, and the tightness of warping measures how much a measure warps. Episode alignment compares qualitative trends with a substitution table and size weights. In mvtsa: CBDTW, segpca_distance, LOCAL_DISTANCES, MixedSegmentDistance, learn_segment_weights, PLADistance, tightness_of_warping, align_episodes, episode_dtw.