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

Chapter 2
Foundations

This chapter fixes the notation and the three objects that the rest of the book builds on. A segmentation is a partition of the time axis into contiguous segments, found by minimizing a sum of segment costs; a warping path is a monotone alignment of two time axes, found by dynamic programming; a PCA model describes the correlation structure of a set of samples and measures, by the T2 and Q statistics, how well a sample fits it. The chapter closes with the preprocessing steps and the conventions of the API.

2.1 Series, collections and notation

A multivariate time series is a matrix 𝐗 = [𝐱1,…,𝐱T ]𝖳 ∈ℝT×n; row 𝐱t is the sample at time t, column j the trajectory of variable j. In the package a series is a NumPy array of shape (T,n); a one-dimensional array is a univariate series and is treated as (T,1). A collection 𝒞 = {𝐗(1),…,𝐗(N)} is a list of series with the same variables and possibly different lengths Ti. Table 2.1 summarizes the notation, which is the same in the docstrings, the documentation and this book.

Table 2.1. Notation of the book and the package.
Symbol

Meaning

Code
𝐗 ∈ℝT×n, 𝐱t

series, sample at time t

X, X[t]
T, n

length, number of variables

n_samples, n_variables
𝒞, N

collection, number of series

list of arrays
τ1 < ⋯ < τc−1

change points (first sample of a new segment)

change_points
c, [τk−1,τk)

number of segments, segment k (τ0 = 0, τc = T)

n_segments, segments
ℓ(a,b), β

cost of segment [a,b), penalty per change point

cost.error(a, b), penalty
p

number of principal components

n_components
𝐔p, Λp

loadings and eigenvalues of a PCA model

components_, explained_variance_
T2t, Qt

Hotelling statistic, reconstruction error of 𝐱t

t2_statistic, q_statistic
sPCA

Krzanowski similarity of two PCA models

krzanowski_similarity
L, λ

lags of dynamic PCA, forgetting factor

lags, forgetting
𝐂, π, D(i,j)

local cost matrix, warping path, accumulated cost

cost_matrix, path, accumulated
w, γ

warping window, soft-minimum temperature

window, gamma
𝐃, 𝐔

distance matrix, fuzzy memberships

pairwise_distances, memberships_

2.2 Segmentations

A segmentation 𝒮 of a series of length T into c segments is defined by the change points 0 = τ0 < τ1 < ⋯ < τc−1 < τc = T; segment k holds the samples 𝐱t, τk−1 ≤t < τk. Change points are thus the first samples of new segments, and the boundaries 0 and T are never listed. Most segmentation methods solve, exactly or approximately, the problem

min c,τ1<⋯<τc−1 ∑ k=1cℓ(τ k−1,τk) + β(c −1), (2.1)

where the cost ℓ(a,b) measures the inhomogeneity of the segment [a,b) and the penalty β prevents the trivial solution of one segment per sample [36]. With a fixed number of segments the penalty is dropped. Three ingredients define a method: the cost, which decides what kind of change is detected (levels, variances, correlations, dynamics, model parameters); the search, which decides how the minimum is found (exactly by dynamic programming, or greedily by merging or splitting); and the selection of c or β (fig. 2.1). Chapter 4 discusses all three; chapter 5 contributes costs based on latent-variable models; chapter 6 adds methods that do not fit the form (2.1), such as Bayesian on-line detection and state models.

Figure 2.1

Figure 2.1. A segmentation into c = 3 segments by the change points τ1,τ2, and the three ingredients that define a segmentation method: the segment cost, the search strategy and the rule that selects the number of segments.

Segmentation objects. Every segmenter of the package returns an instance of the Segmentation class. It holds the change points, the length of the series, and optionally state labels of the segments (when segments recur as states), fuzzy memberships of the samples, scores of the change points, the total cost and metadata. Its methods convert between representations: segments and lengths, to_labels (the segment or state index of every sample) and from_labels, to_frame (a table of the segments), to_dict and from_dict for files, and to_ruptures/from_ruptures for the breakpoint convention of ruptures.

2.3 Warping paths

Two series 𝐗 ∈ℝTx×n and 𝐘 ∈ℝTy×n are compared under time distortions by aligning their samples. A warping path is a sequence of index pairs π = ((i1,j1),…,(iK,jK)) with (i1,j1) = (1,1), (iK,jK) = (Tx,Ty) (boundary condition) and steps (ik+1 −ik,jk+1 −jk) ∈{(1,0),(0,1),(1,1)} (continuity and monotonicity). With the local cost matrix 𝐂, cij = ∥𝐱i −𝐲j∥2, dynamic time warping (DTW) finds the path of minimal total cost by the recursion

D(i,j) = cij + min{D(i −1,j),D(i,j −1),D(i −1,j −1)}, (2.2)

with D(0,0) = 0 and infinite values outside the matrix; the distance is DTW(𝐗,𝐘) = D(Tx,Ty), computed in O(TxTy) time [40]. Figure 2.2 shows the cost matrix, the path and the alignment it induces. A global constraint restricts the path to a band around the diagonal [40, 41]; other step patterns, penalties, soft minima and costs between segments instead of samples give the family of elastic measures of chapters 7 and 8.

Figure 2.2

Figure 2.2. Dynamic time warping. Left: the local cost matrix (darker = larger cost), the optimal warping path and a Sakoe–Chiba window of half-width w. Right: the alignment of the samples induced by the path; the peaks and the dips are matched although they occur at different times.

2.4 PCA models and their statistics

PCA describes the correlation structure of a set of samples. For standardized samples 𝐱t with covariance matrix Σ = 𝐔Λ𝐔𝖳, the first p eigenvectors 𝐔p span the subspace of the largest variance. The projection 𝐲t = 𝐔p𝖳𝐱t gives the scores and 𝐱^t = 𝐔p𝐲t the reconstruction. Two statistics measure how well a sample fits the model:

T2 t = 𝐲t𝖳Λ p−1𝐲 t,Qt = ∥𝐱t −𝐱^t∥2 = 𝐱 t𝖳(𝐈 −𝐔 p𝐔p𝖳)𝐱 t. (2.3)

The Hotelling statistic T2t is the Mahalanobis distance of the sample inside the model subspace; the Q statistic, or squared prediction error, is its distance from the subspace (fig. 2.3). In multivariate statistical process control, T2 detects unusual operation within the normal correlation structure, Q a broken correlation structure [22, 23]. The control limit of T2 follows from an F distribution and that of Q from the approximation of Jackson and Mudholkar [42]; PCAModel.control_limits computes both. Figure 2.4 shows the statistics of a model fitted on the first regime of a series whose correlation structure changes in the middle: Q exceeds its limit for most samples after the change.

Figure 2.3

Figure 2.3. The two statistics of a PCA model. T2t measures the position of the projection of 𝐱t inside the model subspace (scaled by the variances of the components), Qt the squared distance from the subspace. A change of the correlation structure shows up mainly in Q.
model = PCAModel(n_components=1).fit(X[:300])  # first regime as reference 
t2_lim, q_lim = model.control_limits(alpha=0.01) 
q = model.q_statistic(X) 
print( 
    f"Q limit {q_lim:.3f}; exceedance before/after the change: " 
    f"{np.mean(q[:300] > q_lim):.2f} / {np.mean(q[300:] > q_lim):.2f}" 
)
   

Figure 2.4

Figure 2.4. The T2 and Q statistics of a PCA model fitted on the first 300 samples, with their 99 % control limits. The correlation structure changes at sample 300; Q exceeds its limit for most of the later samples, while T2 hardly reacts. Produced by examples/01_basics/plot_03_pca_models.py.

Open in ColabExample plot_03_pca_models.py in the gallery

Comparing PCA models. Two models with loadings 𝐔p and 𝐕p are compared by the Krzanowski similarity factor [21]

sPCA(𝐔p,𝐕p) = 1 ptr (𝐔p𝖳𝐕 p𝐕p𝖳𝐔 p) = 1 p∑ i=1p ∑ j=1p cos⁡2𝜃 ij, (2.4)

where 𝜃ij are the angles between the loading vectors; sPCA = 1 for identical subspaces and 0 for orthogonal ones. Variants weight the angles by the eigenvalues (the λ-similarity of Johannesmeyer, Singhal and Seborg [43, 44]), use the eigenvalue-weighted Eros measure of Yang and Shahabi [45], or turn the principal angles into the Grassmann and chordal distances. The package implements all of them (krzanowski_similarity, lambda_similarity, eros_similarity, grassmann_distance, chordal_distance); the dissimilarity 1 −sPCA is the local cost of correlation-based warping (chapter 8).

m1, m2 = PCAModel(1).fit(X[:300]), PCAModel(1).fit(X[300:]) 
print( 
    "s_PCA(regime 1, regime 1 half) =", 
    round(m1.similarity(PCAModel(1).fit(X[:150])), 3), 
) 
print("s_PCA(regime 1, regime 2)      =", round(m1.similarity(m2), 3)) 
print( 
    "chordal distance               =", 
    round(chordal_distance(m1.components_, m2.components_), 3), 
)
   

In a nutshell: PCA models

A PCA model with p components describes the correlation structure of a set of samples by a subspace. The Hotelling statistic T2t measures variation inside the subspace, the Q statistic the squared distance from it; their control limits come from the F distribution and the Jackson–Mudholkar approximation. Two models are compared by the Krzanowski similarity, the mean squared cosine of the angles between their loadings. In mvtsa: PCAModel, PPCAModel, RecursivePCA, krzanowski_similarity and relatives.

2.5 Preprocessing

Most methods of the book assume that the variables are comparable in scale. zscore, robust_scale and minmax standardize a series, Standardizer learns the statistics on one series and applies them to others (which matters on line). resample and resample_collection bring series to a common length for lock-step measures; fill_missing interpolates gaps; moving_average, smooth and kalman_smoother reduce noise – the Kalman smoother was the key to segmenting noisy process transitions in [3]. derivative and keogh_derivative produce the derivatives used by derivative DTW, and detrend removes trends.

Lag matrices. Dynamic relations among variables become static relations among lagged variables. The lag matrix with L lags,

𝐗L = [ 𝐱L+1𝖳 𝐱L𝖳 ⋯ 𝐱1𝖳 ⋮ ⋮ ⋮ 𝐱T 𝖳 𝐱T−1𝖳 ⋯ 𝐱T−L𝖳 ] ∈ℝ(T−L)×n(L+1), (2.5)

is the input of dynamic PCA [46] (dynamize); delay_embedding builds the analogous embedding of a univariate series, with the delay and the dimension chosen by the mutual information [47] and the false nearest neighbours [48] (ami_lag, false_nearest_neighbors).

2.6 Conventions of the API

All estimators follow the same rules. Parameters are constructor arguments; fit learns and returns the estimator; learned attributes end with an underscore. Segmenters have fit(X), which sets segmentation_, and the shortcut segment(X), which returns it; the registry SEGMENTERS and the function segment(X, method, **params) make every segmenter available by name. Costs are objects with fit(X) and error(a, b); a cost can be passed to any search by name ("l2", "normal", "pca", …) or as an instance. Distances are functions f(x, y, **params) collected in the registry DISTANCES; pairwise_distances computes the distance matrix of a collection with any registered measure or with a fitted segment-level model such as CBDTW. Clusterers have fit and fit_predict and set labels_. Every object supports get_params, set_params and the configuration functions to_config and from_config of chapter 12. Random behaviour is controlled by random_state.