Chapter 7
Elastic similarity
Two series that follow the same pattern at different speeds are far apart in the Euclidean sense and close in any sensible one. This chapter develops the family of elastic measures that compensate time distortions: dynamic time warping with its constraints, step patterns and lower bounds; its variants for derivatives, phase penalties, local shape and multivariate data; the edit-type measures; the soft, differentiable relatives with their expected alignments; and the averaging, diagnosis and learning of warping. Chapter 8 builds on these tools to warp sequences of segments instead of samples.
7.1 Dynamic time warping
The recursion (2.2) defines DTW [40]; three choices refine it. The step pattern fixes the allowed steps and their weights: in the symmetric pattern of type I every step costs , in the symmetric type II a diagonal step costs so that all paths have the same total weight and the distance can be normalized by it, and the asymmetric pattern lets only one of the series be stretched [98, 99]. A penalty added to every non-diagonal step discourages pathological warping. A global constraint restricts the path to the Sakoe–Chiba band [40] or to the Itakura parallelogram [41]; besides speed, a band of a few per cent of the length often improves nearest-neighbour accuracy [100, 101]. dtw returns the distance, dtw_path the full result with the path and the matrices; window_mask builds the constraints (integer half-width, fraction of the length, or ("itakura", s) with maximal slope ).
res = wp.dtw_path(x, y) print( f"Euclidean {np.linalg.norm(x - y) ** 2:.2f} | DTW {res.distance:.2f} " f"| path length {len(res.path)}" )
Lower bounds. Nearest-neighbour search under DTW is accelerated by lower bounds that are cheaper than DTW and discard most candidates. LB_Kim compares the first, last, largest and smallest values [102]; LB_Keogh compares the query with the envelope of the candidate under a band of half-width and lower-bounds the constrained DTW [103]. subsequence_dtw finds the best match of a short query anywhere in a long series by an open-begin, open-end recursion; fast_dtw approximates DTW in linear time by refining a coarse path [104].
print( f"LB_Kim {wp.lb_kim(x, y):.3f} <= LB_Keogh {wp.lb_keogh(x, y, radius=12):.3f} " f"<= DTW(window=12) {wp.dtw(x, y, window=12):.3f}" )
7.2 Variants
Derivative DTW aligns the estimated derivatives instead of the values, which matches shapes rather than levels and avoids the singularities of DTW on series with different offsets [105] (ddtw).
Weighted DTW multiplies the local cost by a logistic function of the phase difference, , a soft band [106] (wdtw).
Amerced DTW adds a constant penalty to every non-diagonal step; small gives DTW, large the Euclidean distance, and the penalty is easier to tune than a window [107] (adtw).
shapeDTW aligns local shape descriptors (raw subsequences, slopes, PAA) of a window around every sample [108] (shape_dtw).
Multivariate DTW has two strategies: the dependent one uses the squared Euclidean distance of the sample vectors as local cost (one path for all variables, dtw), the independent one warps every variable separately and sums the distances (dtw_independent); neither dominates [109], and both extend to the other elastic measures [110].
7.3 Edit-type measures
Edit distances count the cost of transforming one series into the other. LCSS matches samples within a tolerance and a time window and counts the length of the longest common subsequence, ignoring outliers [111]; EDR counts the edits needed under the same tolerance [112]. ERP charges gaps against a constant reference value and is a metric [113]. TWED combines edit operations with a stiffness parameter that penalizes time differences and a constant for deletions, also a metric [114]. MSM transforms one series into the other by move, split and merge operations with a cost for splits and merges [115]. All are dynamic programs with the same structure as DTW and run in the same compiled kernels. Figure 7.2 compares the measures on the Cylinder–Bell–Funnel problem [116], the classic test of elastic similarity: the three classes differ in shape, but the onsets and lengths of the events vary.
measures = { "euclidean": {}, "dtw": {}, "dtw (10% band)": {"metric": "dtw", "window": 0.1}, "ddtw": {}, "wdtw": {"g": 0.05}, "adtw": {"penalty": 0.5}, "shape_dtw": {"width": 9}, "lcss": {"epsilon": 0.5, "delta": 10}, "edr": {"epsilon": 0.25}, "erp": {}, "twed": {}, "msm": {"c": 0.5}, "sbd": {}, } rows = [] for name, kw in measures.items(): kw = dict(kw) metric = kw.pop("metric", name) t0 = time.perf_counter() D = pairwise_distances(C, metric=metric, **kw) rows.append( { "measure": name, "1-NN accuracy": knn_accuracy(D, y), "seconds": time.perf_counter() - t0, } ) table = pd.DataFrame(rows).sort_values("1-NN accuracy", ascending=False) print(table.round(3).to_string(index=False))
7.4 Soft alignment
DTW is not differentiable: its minimum switches between paths. Soft-DTW replaces the minimum of the recursion by the soft minimum
| (7.1) |
which tends to the minimum as [29]. The resulting value is differentiable, and its gradient with respect to the cost matrix is the expected alignment : the probability, under a Gibbs distribution over all paths, that are aligned. A backward recursion computes it at the cost of the forward pass. The expected alignment shows how certain an alignment is: a sharp ridge where the series match unambiguously, a diffuse band where they do not (fig. 7.3). Because , soft-DTW is not a proper dissimilarity; the soft-DTW divergence
| (7.2) |
is non-negative and zero only for identical series [117]. The global alignment kernel sums the exponentiated similarities of all paths and is positive definite, which makes it usable in kernel methods such as spectral clustering [118, 119] (gak). The shape-based distance SBD is one minus the maximal normalized cross-correlation over all shifts, computed with the fast Fourier transform [30] (sbd).
fig, axes = plt.subplots(1, 3, figsize=(9, 3.2)) for ax, g in zip(axes, (0.01, 0.1, 1.0), strict=True): value, E = wp.soft_dtw_alignment(x, y, gamma=g) viz.plot_alignment_uncertainty(E, path=wp.dtw_path(x, y).path, ax=ax) ax.set_title(f"$\\gamma$={g}, soft-DTW={value:.2f}")
7.5 Averaging
The arithmetic mean of warped series blurs their features. DTW barycenter averaging (DBA) iterates two steps: align every series to the current average with DTW, then replace every sample of the average by the mean of the samples aligned to it [33] (algorithm 7.1). The soft-DTW barycenter minimizes the sum of soft-DTW values to the series by gradient descent [29]. The medoid – the member with the smallest total distance – is the robust alternative. Averages are the centres of -means clustering under DTW (chapter 9).
7.6 Diagnosing and learning warping
How much warping does a data set need? A warping path is summarized by its length relative to the series, the share of non-diagonal steps, the longest horizontal and vertical runs and the area between the path and the diagonal (path_statistics); the warping function , the average aligned index of for every index of , shows the distortion directly. The tightness of warping (ToW) of Bankó and Abonyi, the average path length relative to the number of aligned elements over many pairs, compares how much different measures warp [7] (tightness_of_warping, section 8.4). A window can be learned by maximizing the leave-one-out 1-NN accuracy over candidate widths [100] (learn_window), and the elastic ensemble lets several measures vote, each with a weight equal to its leave-one-out accuracy on the training collection [120] (ElasticEnsemble).
best, scores = wp.learn_window( C, y, candidates=(0.0, 0.02, 0.05, 0.1, 0.2, None) ) print( "accuracy by window:", {str(k): round(v, 3) for k, v in scores.items()}, "-> best", best, )
In a nutshell: Elastic similarity
DTW aligns two series by a monotone path of minimal cost; step patterns, penalties and Sakoe–Chiba or Itakura windows shape the path, and LB_Kim and LB_Keogh accelerate searches. Derivative, weighted, amerced and shape DTW change what is aligned or how warping is penalized; the dependent and independent strategies extend DTW to many variables. LCSS, EDR, ERP, TWED and MSM count edits; soft-DTW makes alignment differentiable and yields expected alignments, its divergence a proper dissimilarity; GAK is a positive definite kernel, SBD a fast shape distance. DBA and the soft-DTW barycenter average warped series. Path statistics, the tightness of warping, window learning and the elastic ensemble diagnose and tune warping. In mvtsa: dtw, dtw_path, window_mask, lb_keogh, ddtw, wdtw, adtw, shape_dtw, lcss, edr, erp, twed, msm, soft_dtw, soft_dtw_alignment, gak, sbd, dba, pairwise_distances.