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

Chapter 1
Introduction

This chapter states the three questions the book is about – where a multivariate time series changes, how similar two series are when their time axes do not agree, and which series belong together – and explains why the answers have to look at how the variables move together. It then traces the methods of the book back to their origins, introduces the structure of the mvtsa package, and walks through a first session.

1.1 Three questions about multivariate time series

A multivariate time series is a matrix 𝐗 ∈ℝT×n whose row 𝐱t holds the values of n variables at time t. Process historians, sensor networks, wearable devices and pen tablets produce such matrices in large numbers. Whatever the domain, three tasks recur (fig. 1.1).

Segmentation. Where does the behaviour change? A segmentation cuts 𝐗 into contiguous pieces that are internally homogeneous: an operating regime, a product grade, an activity, a stroke of a signature. Segmentation compresses a long record into a short sequence of interpretable episodes, localizes faults and transitions, and selects the parts of a record that are worth modelling.

Warping. How similar are two series whose time axes do not agree? Two batches of the same recipe, two signatures of the same writer or two utterances of the same word follow the same pattern at different speeds. An elastic measure aligns them before comparing them; the alignment itself – the warping path – tells which phases correspond.

Clustering. Which series, segments or objects belong together? Grouping records reveals recurring operating modes, typical batch trajectories, classes of motion and groups of units that behave alike.

The three tasks support each other. Segments are the natural units of comparison, so segmentation makes warping faster and more robust; warping distances are the input of clustering; clustering the segments of many series yields a vocabulary of recurring regimes, which in turn labels new data. The methods of this book therefore form one toolbox rather than three.

Figure 1.1
Figure 1.1. The three questions of the book. (a) A segmentation cuts a series into homogeneous pieces; here the correlation of the three variables changes in the middle segment while their levels stay the same. (b) An elastic measure aligns two series that follow the same pattern at different speeds before comparing them. (c) Clustering groups series (or segments) by a distance.

1.2 Why the variables have to be analysed together

The most common way to segment, compare or cluster multivariate series is to treat the variables one by one, or to stack them into a long vector and use the Euclidean distance. Both ignore what is often the most informative property of process data: the correlation of the variables. A heat exchanger whose fouling changes, a reactor that switches between product grades, a control loop whose tuning changes – all of these alter how the variables move together, sometimes without moving any of their means or variances. Principal component analysis (PCA) is the classical tool to describe this structure: a PCA model of a segment is a low-dimensional subspace in which the samples live, and two segments differ if their subspaces differ [21, 22, 23].

Figure 1.4 shows the simplest example. Three variables share one latent factor whose loadings change three times; the levels and the variances stay the same. A segmentation by the means sees nothing but noise, while a segmentation by the reconstruction error of local PCA models finds the four regimes exactly. This observation is the starting point of the latent-variable methods of chapter 5 and of correlation-based warping in chapter 8. It does not make the other methods obsolete: when the information lies in levels, shapes or recurring patterns, the costs of chapter 4, the subsequence methods of chapter 6 and the elastic measures of chapter 7 are the better tools, and the package treats all of them alike.

1.3 Two decades of methods

Figure 1.2 places the methods developed by the group (right) among milestones of the literature (left). The first line of work, fuzzy and PCA-based segmentation of process data [1, 2, 3], produced two branches: correlation-based warping and its extensions in the doctoral work of Zoltán Bankó [4, 5, 6, 7, 8], and on-line and information-driven segmentation in the work of László Dobos [11, 12, 13, 14]. Qualitative episodes [9], decision-tree descriptions of operating regimes [17], model-based segmentation for energy monitoring [16], trajectory clustering [19] and zone-labelled visibility graphs [20] complete the picture. Over the same period, the literature brought exact penalized segmentation [24], Bayesian on-line change point detection [25], the matrix profile and self-supervised segmentation [26, 27, 28], differentiable alignment [29] and shape-based clustering [30]. Recent benchmarks agree that no segmenter dominates on all kinds of data [31, 32]; a toolbox therefore has to offer several, and the means to choose among them.

Figure 1.2

Figure 1.2. Methods developed by the group (blue, right) and milestones of the literature (vermilion, left). All are implemented in mvtsa; chapter C lists them with their references.

1.4 The package

mvtsa is organized by task (fig. 1.3). The core objects are deliberately few: a series is a NumPy array of shape (T,n), a collection is a list of such arrays of possibly different lengths, and every segmenter returns a Segmentation – the change points, optionally state labels, memberships and scores, with conversions to labels, tables and the formats of other libraries. Segmenters, warping models and clusterers follow the conventions of scikit-learn [34]: parameters are set in the constructor, fit learns, fitted attributes end with an underscore, and get_params/set_params make every object configurable. A segmentation cost can be combined with any search strategy, a distance registry makes every elastic measure available to every clusterer, and every object can be written to a configuration file and rebuilt from it. The compute-heavy dynamic programs run as compiled kernels when Numba [35] is installed and fall back to identical pure-Python code otherwise.

Figure 1.3
Figure 1.3. Structure of the package. Data are preprocessed and represented; segmentation, warping and clustering use each other (segment models are the units of correlation-based warping, distances feed every clusterer); evaluation, explanation, simplification and visualization act on their results; the model-operations layer makes analyses reproducible and deployable.

1.5 A first session

The example behind fig. 1.4 generates a series whose correlation structure switches three times, segments it with PCA models and evaluates the result against the known change points:

X, true_cps, states = mv.datasets.make_correlation_switching( 
    n_segments=4, length=150, random_state=0 
) 
seg = mv.segment( 
    X, "pca", n_segments=4, n_components=1 
)  # Q-statistic cost, bottom-up search 
print(seg) 
print(evaluate_segmentation(true_cps, seg, len(X), margin=5))
   

The one-line function segment looks the method up in a registry; the same result comes from PCASegmenter(n_segments=4, n_components=1).segment(X). evaluate_segmentation returns the metrics of chapter 10: the F1 score of the detected change points within a margin, the covering of the true segments, the Hausdorff distance of the boundaries and others. A segmentation by the means, in contrast, misses the changes:

seg_l2 = mv.segment(X, "bottomup", cost="l2", n_segments=4) 
print( 
    "L2 change points:", 
    seg_l2.change_points, 
    " PCA change points:", 
    seg.change_points, 
)
   

Figure 1.4

Figure 1.4. A first segmentation. Three variables share one latent factor whose loadings switch three times while the levels and variances stay the same. The PCA segmentation (blue lines, shaded segments) finds the true change points (orange marks at the top) exactly. Produced by examples/01_basics/plot_01_first_steps.py.

Open in ColabExample plot_01_first_steps.py in the gallery

The figures of the book, like fig. 1.4, come from such scripts; each ends with a short study of its main parameter, so that the reader sees not only that a method works but also when it stops working.

Several Python libraries cover parts of the field. ruptures implements the cost-and-search framework of offline change point detection reviewed by Truong, Oudre and Vayatis [36]; tslearn [37] and aeon [38] provide elastic distances, barycenters and clustering; stumpy [39] computes matrix profiles. mvtsa differs in three ways: it implements the latent-variable segmentation and correlation-based warping methods that are not available elsewhere, it treats segmentation, warping and clustering as one connected toolbox with a shared segmentation object and distance registry, and it adds the evaluation, explanation and operation layers that turn an analysis into a maintained model. Segmentations convert to and from the formats of ruptures, and the optional interop extra installs these libraries for comparison.

In a nutshell: The book in one paragraph

Multivariate time series carry their information in how the variables move together. The book answers three questions about them – where they change (segmentation), how similar they are under time distortions (warping) and which belong together (clustering) – with methods developed at the University of Pannonia and the best methods of the literature, all implemented in mvtsa with a shared Segmentation object, interchangeable costs and searches, a distance registry, and layers for evaluation, explanation and model operations.