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 and 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 ; row is the sample at time , column the trajectory of variable . In the package a series is a NumPy array of shape ; a one-dimensional array is a univariate series and is treated as . A collection is a list of series with the same variables and possibly different lengths . Table 2.1 summarizes the notation, which is the same in the docstrings, the documentation and this book.
| Symbol | Meaning | Code |
| , | series, sample at time | X, X[t] |
| , | length, number of variables | n_samples, n_variables |
| , | collection, number of series | list of arrays |
| change points (first sample of a new segment) | change_points | |
| , | number of segments, segment (, ) | n_segments, segments |
| , | cost of segment , penalty per change point | cost.error(a, b), penalty |
| number of principal components | n_components | |
| , | loadings and eigenvalues of a PCA model | components_, explained_variance_ |
| , | Hotelling statistic, reconstruction error of | t2_statistic, q_statistic |
| Krzanowski similarity of two PCA models | krzanowski_similarity | |
| , | lags of dynamic PCA, forgetting factor | lags, forgetting |
| , , | local cost matrix, warping path, accumulated cost | cost_matrix, path, accumulated |
| , | warping window, soft-minimum temperature | window, gamma |
| , | distance matrix, fuzzy memberships | pairwise_distances, memberships_ |
2.2 Segmentations
A segmentation of a series of length into segments is defined by the change points ; segment holds the samples , . Change points are thus the first samples of new segments, and the boundaries and are never listed. Most segmentation methods solve, exactly or approximately, the problem
| (2.1) |
where the cost measures the inhomogeneity of the segment 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 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.
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 and are compared under time distortions by aligning their samples. A warping path is a sequence of index pairs with , (boundary condition) and steps (continuity and monotonicity). With the local cost matrix , , dynamic time warping (DTW) finds the path of minimal total cost by the recursion
| (2.2) |
with and infinite values outside the matrix; the distance is , computed in 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.
2.4 PCA models and their statistics
PCA describes the correlation structure of a set of samples. For standardized samples with covariance matrix , the first eigenvectors span the subspace of the largest variance. The projection gives the scores and the reconstruction. Two statistics measure how well a sample fits the model:
| (2.3) |
The Hotelling statistic is the Mahalanobis distance of the sample inside the model subspace; the statistic, or squared prediction error, is its distance from the subspace (fig. 2.3). In multivariate statistical process control, detects unusual operation within the normal correlation structure, a broken correlation structure [22, 23]. The control limit of follows from an distribution and that of 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: exceeds its limit for most samples after the change.
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}" )
Comparing PCA models. Two models with loadings and are compared by the Krzanowski similarity factor [21]
| (2.4) |
where are the angles between the loading vectors; for identical subspaces and 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 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 components describes the correlation structure of a set of samples by a subspace. The Hotelling statistic measures variation inside the subspace, the statistic the squared distance from it; their control limits come from the 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 lags,
| (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.