Hubbry Logo
Dynamic time warpingDynamic time warpingMain
Open search
Dynamic time warping
Community hub
Dynamic time warping
logo
8 pages, 0 posts
0 subscribers
Be the first to start a discussion here.
Be the first to start a discussion here.
Dynamic time warping
Dynamic time warping
from Wikipedia
Dynamic time warping between two piecewise linear functions. The dotted line illustrates the time-warp relation. Notice that several points in the lower function are mapped to one point in the upper function, and vice versa.
Two repetitions of a walking sequence recorded using a motion-capture system. While there are differences in walking speed between repetitions, the spatial paths of limbs remain highly similar.[1]
DTW between a sinusoid and a noisy and shifted version of it.

In time series analysis, dynamic time warping (DTW) is an algorithm for measuring similarity between two temporal sequences, which may vary in speed. For instance, similarities in walking could be detected using DTW, even if one person was walking faster than the other, or if there were accelerations and decelerations during the course of an observation. DTW has been applied to temporal sequences of video, audio, and graphics data — indeed, any data that can be turned into a one-dimensional sequence can be analyzed with DTW. A well-known application has been automatic speech recognition, to cope with different speaking speeds. Other applications include speaker recognition and online signature recognition. It can also be used in partial shape matching applications.

In general, DTW is a method that calculates an optimal match between two given sequences (e.g. time series) with certain restriction and rules:

  • Every index from the first sequence must be matched with one or more indices from the other sequence, and vice versa
  • The first index from the first sequence must be matched with the first index from the other sequence (but it does not have to be its only match)
  • The last index from the first sequence must be matched with the last index from the other sequence (but it does not have to be its only match)
  • The mapping of the indices from the first sequence to indices from the other sequence must be monotonically increasing, and vice versa, i.e. if are indices from the first sequence, then there must not be two indices in the other sequence, such that index is matched with index and index is matched with index , and vice versa

We can plot each match between the sequences and as a path in a matrix from to , such that each step is one of . In this formulation, we see that the number of possible matches is the Delannoy number.

The optimal match is denoted by the match that satisfies all the restrictions and the rules and that has the minimal cost, where the cost is computed as the sum of absolute differences, for each matched pair of indices, between their values.

The sequences are "warped" non-linearly in the time dimension to determine a measure of their similarity independent of certain non-linear variations in the time dimension. This sequence alignment method is often used in time series classification. Although DTW measures a distance-like quantity between two given sequences, it doesn't guarantee the triangle inequality to hold.

In addition to a similarity measure between the two sequences (a so called "warping path" is produced), by warping according to this path the two signals may be aligned in time. The signal with an original set of points X(original), Y(original) is transformed to X(warped), Y(warped). This finds applications in genetic sequence and audio synchronisation. In a related technique sequences of varying speed may be averaged using this technique see the average sequence section.

This is conceptually very similar to the Needleman–Wunsch algorithm.

Implementation

[edit]

This example illustrates the implementation of the dynamic time warping algorithm when the two sequences s and t are strings of discrete symbols. For two symbols x and y, is a distance between the symbols, e.g., .

int DTWDistance(s: array [1..n], t: array [1..m]) {
    DTW := array [0..n, 0..m]
    
    for i := 0 to n
        for j := 0 to m
            DTW[i, j] := infinity
    DTW[0, 0] := 0
    
    for i := 1 to n
        for j := 1 to m
            cost := d(s[i], t[j])
            DTW[i, j] := cost + minimum(DTW[i-1, j  ],    // insertion
                                        DTW[i  , j-1],    // deletion
                                        DTW[i-1, j-1])    // match
    
    return DTW[n, m]
}

where DTW[i, j] is the distance between s[1:i] and t[1:j] with the best alignment.

We sometimes want to add a locality constraint. That is, we require that if s[i] is matched with t[j], then is no larger than w, a window parameter.

We can easily modify the above algorithm to add a locality constraint (differences marked). However, the above given modification works only if is no larger than w, i.e. the end point is within the window length from diagonal. In order to make the algorithm work, the window parameter w must be adapted so that (see the line marked with (*) in the code).

int DTWDistance(s: array [1..n], t: array [1..m], w: int) {
    DTW := array [0..n, 0..m]

    w := max(w, abs(n-m)) // adapt window size (*)

    for i := 0 to n
        for j:= 0 to m
            DTW[i, j] := infinity
    DTW[0, 0] := 0
    for i := 1 to n
        for j := max(1, i-w) to min(m, i+w)
            DTW[i, j] := 0

    for i := 1 to n
        for j := max(1, i-w) to min(m, i+w)
            cost := d(s[i], t[j])
            DTW[i, j] := cost + minimum(DTW[i-1, j  ],    // insertion
                                        DTW[i  , j-1],    // deletion
                                        DTW[i-1, j-1])    // match
    return DTW[n, m]
}

Warping properties

[edit]

The DTW algorithm produces a discrete matching between existing elements of one series to another. In other words, it does not allow time-scaling of segments within the sequence. Other methods allow continuous warping. For example, Correlation Optimized Warping (COW) divides the sequence into uniform segments that are scaled in time using linear interpolation, to produce the best matching warping. The segment scaling causes potential creation of new elements, by time-scaling segments either down or up, and thus produces a more sensitive warping than DTW's discrete matching of raw elements.

Complexity

[edit]

The time complexity of the DTW algorithm is , where and are the lengths of the two input sequences. The 50 years old quadratic time bound was broken in 2016: an algorithm due to Gold and Sharir enables computing DTW in time and space for two input sequences of length .[2] This algorithm can also be adapted to sequences of different lengths. Despite this improvement, it was shown that a strongly subquadratic running time of the form for some cannot exist unless the Strong exponential time hypothesis fails.[3][4]

While the dynamic programming algorithm for DTW requires space in a naive implementation, the space consumption can be reduced to using Hirschberg's algorithm.

Fast computation

[edit]

Fast techniques for computing DTW include PrunedDTW,[5] SparseDTW,[6] FastDTW,[7] and the MultiscaleDTW.[8][9]

A common task, retrieval of similar time series, can be accelerated by using lower bounds such as LB_Keogh,[10] LB_Improved,[11] or LB_Petitjean.[12] However, the Early Abandon and Pruned DTW algorithm reduces the degree of acceleration that lower bounding provides and sometimes renders it ineffective.

In a survey, Wang et al. reported slightly better results with the LB_Improved lower bound than the LB_Keogh bound, and found that other techniques were inefficient.[13] Subsequent to this survey, the LB_Enhanced bound was developed that is always tighter than LB_Keogh while also being more efficient to compute.[14] LB_Petitjean is the tightest known lower bound that can be computed in linear time.[12]

Average sequence

[edit]

Averaging for dynamic time warping is the problem of finding an average sequence for a set of sequences. NLAAF[15] is an exact method to average two sequences using DTW. For more than two sequences, the problem is related to that of multiple alignment and requires heuristics. DBA[16] is currently a reference method to average a set of sequences consistently with DTW. COMASA[17] efficiently randomizes the search for the average sequence, using DBA as a local optimization process.

Supervised learning

[edit]

A nearest-neighbour classifier can achieve state-of-the-art performance when using dynamic time warping as a distance measure.[18]

Amerced Dynamic Time Warping

[edit]

Amerced Dynamic Time Warping (ADTW) is a variant of DTW designed to better control DTW's permissiveness in the alignments that it allows.[19] The windows that classical DTW uses to constrain alignments introduce a step function. Any warping of the path is allowed within the window and none beyond it. In contrast, ADTW employs an additive penalty that is incurred each time that the path is warped. Any amount of warping is allowed, but each warping action incurs a direct penalty. ADTW significantly outperforms DTW with windowing when applied as a nearest neighbor classifier on a set of benchmark time series classification tasks.[19]

Alternative approaches

[edit]

In functional data analysis, time series are regarded as discretizations of smooth (differentiable) functions of time. By viewing the observed samples at smooth functions, one can utilize continuous mathematics for analyzing data.[20] Smoothness and monotonicity of time warp functions may be obtained for instance by integrating a time-varying radial basis function, thus being a one-dimensional diffeomorphism.[21] Optimal nonlinear time warping functions are computed by minimizing a measure of distance of the set of functions to their warped average. Roughness penalty terms for the warping functions may be added, e.g., by constraining the size of their curvature. The resultant warping functions are smooth, which facilitates further processing. This approach has been successfully applied to analyze patterns and variability of speech movements.[22][23]

Another related approach are hidden Markov models (HMM) and it has been shown that the Viterbi algorithm used to search for the most likely path through the HMM is equivalent to stochastic DTW.[24][25][26]

DTW and related warping methods are typically used as pre- or post-processing steps in data analyses. If the observed sequences contain both random variation in both their values, shape of observed sequences and random temporal misalignment, the warping may overfit to noise leading to biased results. A simultaneous model formulation with random variation in both values (vertical) and time-parametrization (horizontal) is an example of a nonlinear mixed-effects model.[27] In human movement analysis, simultaneous nonlinear mixed-effects modeling has been shown to produce superior results compared to DTW.[28]

Open-source software

[edit]
  • The tempo C++ library with Python bindings implements Early Abandoned and Pruned DTW as well as Early Abandoned and Pruned ADTW and DTW lower bounds LB_Keogh, LB_Enhanced and LB_Webb.
  • The UltraFastMPSearch Java library implements the UltraFastWWSearch algorithm[29] for fast warping window tuning.
  • The lbimproved C++ library implements Fast Nearest-Neighbor Retrieval algorithms under the GNU General Public License (GPL). It also provides a C++ implementation of dynamic time warping, as well as various lower bounds.
  • The FastDTW library is a Java implementation of DTW and a FastDTW implementation that provides optimal or near-optimal alignments with an O(N) time and memory complexity, in contrast to the O(N2) requirement for the standard DTW algorithm. FastDTW uses a multilevel approach that recursively projects a solution from a coarser resolution and refines the projected solution.
  • FastDTW fork (Java) published to Maven Central.
  • time-series-classification (Java) a package for time series classification using DTW in Weka.
  • The DTW suite provides Python (dtw-python) and R packages (dtw) with a comprehensive coverage of the DTW algorithm family members, including a variety of recursion rules (also called step patterns), constraints, and substring matching.
  • The mlpy Python library implements DTW.
  • The pydtw Python library implements the Manhattan and Euclidean flavoured DTW measures including the LB_Keogh lower bounds.
  • The cudadtw C++/CUDA library implements subsequence alignment of Euclidean-flavoured DTW and z-normalized Euclidean distance similar to the popular UCR-Suite on CUDA-enabled accelerators.
  • The JavaML machine learning library implements DTW.
  • The ndtw C# library implements DTW with various options.
  • Sketch-a-Char uses Greedy DTW (implemented in JavaScript) as part of LaTeX symbol classifier program.
  • The MatchBox implements DTW to match mel-frequency cepstral coefficients of audio signals.
  • Sequence averaging: a GPL Java implementation of DBA.[16]
  • The Gesture Recognition Toolkit|GRT C++ real-time gesture-recognition toolkit implements DTW.
  • The PyHubs software package implements DTW and nearest-neighbour classifiers, as well as their extensions (hubness-aware classifiers).
  • The simpledtw Python library implements the classic O(NM) Dynamic Programming algorithm and bases on Numpy. It supports values of any dimension, as well as using custom norm functions for the distances. It is licensed under the MIT license.
  • The tslearn Python library implements DTW in the time-series context.
  • The cuTWED CUDA Python library implements a state of the art improved Time Warp Edit Distance using only linear memory with phenomenal speedups.
  • DynamicAxisWarping.jl Is a Julia implementation of DTW and related algorithms such as FastDTW, SoftDTW, GeneralDTW and DTW barycenters.
  • The Multi_DTW implements DTW to match two 1-D arrays or 2-D speech files (2-D array).
  • The dtwParallel (Python) package incorporates the main functionalities available in current DTW libraries and novel functionalities such as parallelization, computation of similarity (kernel-based) values, and consideration of data with different types of features (categorical, real-valued, etc.).[30]

Applications

[edit]

Spoken-word recognition

[edit]

Due to different speaking rates, a non-linear fluctuation occurs in speech pattern versus time axis, which needs to be eliminated.[31] DP matching is a pattern-matching algorithm based on dynamic programming (DP), which uses a time-normalization effect, where the fluctuations in the time axis are modeled using a non-linear time-warping function. Considering any two speech patterns, we can get rid of their timing differences by warping the time axis of one so that the maximal coincidence is attained with the other. Moreover, if the warping function is allowed to take any possible value, very less[clarify] distinction can be made between words belonging to different categories. So, to enhance the distinction between words belonging to different categories, restrictions were imposed on the warping function slope.

Correlation power analysis

[edit]

Unstable clocks are used to defeat naive power analysis. Several techniques are used to counter this defense, one of which is dynamic time warping.

Finance and econometrics

[edit]

Dynamic time warping is used in finance and econometrics to assess the quality of the prediction versus real-world data.[32][33][34]

See also

[edit]

References

[edit]

Further reading

[edit]
Revisions and contributorsEdit on WikipediaRead on Wikipedia
from Grokipedia
Dynamic time warping (DTW) is an algorithm that measures the similarity between two temporal sequences by allowing nonlinear alignments to account for variations in timing, speed, or distortions, effectively finding an optimal "warping" path that minimizes the distance between them. Originally developed as a dynamic programming-based technique for time normalization in recognition, DTW addresses the challenge of aligning speech patterns affected by differing speaking rates through elastic transformations of the time axis. Introduced in the late by Hiroaki Sakoe and Seibi Chiba, DTW optimizes the alignment of feature vectors from acoustic signals using a symmetric and constraints to enhance discrimination between word categories, achieving error rates as low as 0.3% on Japanese digit recognition tasks. The core algorithm constructs a cost matrix of local distances between elements and applies dynamic programming to compute the minimum accumulated cost path, subject to constraints such as monotonicity, boundary conditions, and continuity, resulting in a of O(NM) for sequences of lengths N and M. This approach outperforms linear normalization methods by handling nonlinear time fluctuations, making it superior for tasks where sequences exhibit phase shifts or stretching. Beyond its origins in speech processing, DTW has been widely adopted in time series analysis for applications including , clustering, , , gesture analysis, bioinformatics for protein , and . In data mining, it excels over by accommodating temporal distortions, though it requires constraints like the Sakoe-Chiba band (a diagonal window limiting excessive warping) to improve efficiency and accuracy, often reducing effective complexity to near-linear with lower bounding techniques. Variants such as DTW incorporate information for smoother alignments, while modern adaptations address scalability for large datasets in fields like and medical . Despite not satisfying the , which complicates indexing, DTW remains a foundational tool due to its robustness in capturing semantic similarities in sequential data.

Fundamentals

Definition and Motivation

Time series data consist of ordered sequences of observations recorded at successive points in time, capturing temporal dependencies and patterns in domains such as , , and . Dynamic time warping (DTW) is an for measuring similarity between two temporal sequences by aligning them through a nonlinear warping of the time axis, which minimizes the overall distance between the sequences while accommodating variations in timing or speed. This approach finds an optimal warping path that maps corresponding elements between the sequences, allowing similar shapes to be matched despite elastic distortions. The motivation for DTW arises from the limitations of rigid similarity metrics like the , which assumes a one-to-one point correspondence and performs poorly on sequences with temporal shifts, stretching, or compression, even if their underlying patterns are similar. For instance, in , spoken words exhibit nonlinear fluctuations in speaking rate, making direct comparisons unreliable; DTW addresses this by time-normalizing the patterns to enhance matching accuracy, as demonstrated in early applications achieving up to 99.8% recognition rates for isolated words. By enabling flexible alignments, DTW provides a more robust measure for tasks involving variable-speed sequences across diverse fields.

History

Dynamic time warping (DTW) originated in the late 1960s as a technique for aligning speech signals in tasks. The method was first proposed by Taras K. Vintsyuk in 1968, who introduced a dynamic programming approach for speech discrimination by optimally aligning sequences to account for temporal variations in . Building on this, Sakoe and Seibi Chiba advanced the algorithm in 1971 for continuous , presenting it at the Seventh International Congress on Acoustics as a way to handle variable speaking rates through nonlinear time normalization. Their seminal 1978 paper further optimized the dynamic programming framework, introducing the Sakoe-Chiba band constraint to limit warping paths and improve computational efficiency for isolated . In the 1970s, DTW found early applications primarily in isolated word systems developed at laboratories such as and , where it enabled robust matching of utterances despite speed differences across speakers. By the , DTW was integrated with hidden Markov models (HMMs) to enhance continuous , as explored in unified frameworks that combined DTW's alignment capabilities with HMM's probabilistic modeling for improved accuracy in large-vocabulary tasks. DTW experienced a revival in the early 2000s for data mining, where researchers like Eamonn Keogh addressed common misconceptions about its computational cost and applicability, demonstrating its efficiency and effectiveness for tasks beyond speech, such as and sensor in papers from 2002 to 2004. During the , the technique expanded to diverse domains including for aligning DNA sequences and for detecting patterns in stock price movements, reflecting its versatility in handling non-stationary sequential . In the 2020s, focus has shifted toward acceleration methods for applications, with GPU-optimized implementations enabling scalable DTW computations for high-volume in fields like selective . As of 2025, DTW has seen further applications in for modeling symptom dynamics and in for brain network analysis.

Algorithm

Basic Implementation

The basic implementation of dynamic time warping (DTW) uses dynamic programming to find the minimum-cost alignment between two sequences of lengths nn and mm, respectively, under the assumption of unconstrained warping, where the alignment path is required to be monotonic but allows arbitrary or compression along the time axis. This approach computes an accumulated cost matrix that captures the optimal matching up to each pair of positions in the sequences. Given two sequences X=(x1,,xn)X = (x_1, \dots, x_n) and Y=(y1,,ym)Y = (y_1, \dots, y_m), the algorithm first constructs a cost matrix where each entry represents a local between elements. The local d(i,j)d(i,j) is typically defined as the squared (xiyj)2(x_i - y_j)^2 or the xiyj|x_i - y_j|, depending on whether the goal is to emphasize larger deviations or treat them linearly. The accumulated cost matrix γ(i,j)\gamma(i,j) is then filled using the : γ(i,j)=d(i,j)+min(γ(i1,j), γ(i,j1), γ(i1,j1))\gamma(i,j) = d(i,j) + \min \left( \gamma(i-1,j),\ \gamma(i,j-1),\ \gamma(i-1,j-1) \right) for i=1,,ni = 1, \dots, n and j=1,,mj = 1, \dots, m. The base cases initialize the boundaries to allow alignments starting from the beginning of either sequence: γ(1,1)=d(1,1),\gamma(1,1) = d(1,1), γ(i,1)=γ(i1,1)+d(i,1)i=2,,n,\gamma(i,1) = \gamma(i-1,1) + d(i,1) \quad \forall i = 2, \dots, n, γ(1,j)=γ(1,j1)+d(1,j)j=2,,m.\gamma(1,j) = \gamma(1,j-1) + d(1,j) \quad \forall j = 2, \dots, m. These ensure that the first row and column accumulate costs along the sequence axes, effectively permitting one sequence to "wait" while the other advances. The DTW distance, which quantifies the total alignment cost, is given by the bottom-right entry γ(n,m)\gamma(n,m). The algorithm can be implemented efficiently in O(nm)O(nm) time and space using a two-dimensional for γ\gamma. The following outlines the core computation, assuming 1-based indexing for clarity and using the squared :

function DTW(X, Y): n = [length](/page/Length)(X) m = [length](/page/Length)(Y) γ = [array](/page/Array) of size (n+1) x (m+1), initialized to [infinity](/page/Infinity) γ[1,1] = (X[1] - Y[1])^2 for i = 2 to n: γ[i,1] = γ[i-1,1] + (X[i] - Y[1])^2 for j = 2 to m: γ[1,j] = γ[1,j-1] + (X[1] - Y[j])^2 for i = 2 to n: for j = 2 to m: γ[i,j] = (X[i] - Y[j])^2 + min(γ[i-1,j], γ[i,j-1], γ[i-1,j-1]) return γ[n,m]

function DTW(X, Y): n = [length](/page/Length)(X) m = [length](/page/Length)(Y) γ = [array](/page/Array) of size (n+1) x (m+1), initialized to [infinity](/page/Infinity) γ[1,1] = (X[1] - Y[1])^2 for i = 2 to n: γ[i,1] = γ[i-1,1] + (X[i] - Y[1])^2 for j = 2 to m: γ[1,j] = γ[1,j-1] + (X[1] - Y[j])^2 for i = 2 to n: for j = 2 to m: γ[i,j] = (X[i] - Y[j])^2 + min(γ[i-1,j], γ[i,j-1], γ[i-1,j-1]) return γ[n,m]

This reflects the standard dynamic programming setup, where values for out-of-bounds accesses are handled implicitly by the boundary initializations. To illustrate, consider two short sequences X=(1,3,2)X = (1, 3, 2) and Y=(1,2,3)Y = (1, 2, 3), using the as the local distance d(i,j)=xiyjd(i,j) = |x_i - y_j|. The cost matrix CC is:
Y1=1Y2=2Y3=3
X1=1012
X2=3210
X3=2101
The accumulated cost matrix γ\gamma is computed row-by-row. Starting with boundaries: γ(1,1)=0\gamma(1,1) = 0, γ(2,1)=0+2=2\gamma(2,1) = 0 + 2 = 2, γ(3,1)=2+1=3\gamma(3,1) = 2 + 1 = 3; γ(1,2)=0+1=1\gamma(1,2) = 0 + 1 = 1, γ(1,3)=1+2=3\gamma(1,3) = 1 + 2 = 3. For inner cells: γ(2,2)=1+min(2,1,0)=1+0=1\gamma(2,2) = 1 + \min(2, 1, 0) = 1 + 0 = 1; γ(2,3)=0+min(3,3,1)=0+1=1\gamma(2,3) = 0 + \min(3, 3, 1) = 0 + 1 = 1; γ(3,2)=0+min(1,1,2)=0+1=1\gamma(3,2) = 0 + \min(1, 1, 2) = 0 + 1 = 1; γ(3,3)=1+min(3,1,1)=1+1=2\gamma(3,3) = 1 + \min(3, 1, 1) = 1 + 1 = 2. Thus, the DTW distance is 2, reflecting an optimal alignment that warps XX to match YY's progression despite the reversal in XX. This example demonstrates how DTW accommodates non-linear temporal variations, with the monotonicity of the path ensuring no backward steps in the alignment.

Warping Path Computation

Once the dynamic programming (DP) table for the accumulated costs has been constructed, the optimal warping path is retrieved through a procedure. This process begins at the bottom-right cell of the table, corresponding to the indices (n, m) where n and m are the lengths of the two sequences, and traces backward to the top-left cell at (1, 1). At each step, the algorithm selects the predecessor cell that offers the minimum accumulated cost, moving either horizontally, vertically, or diagonally, thereby forming a sequence of index pairs (i_k, j_k) that define the alignment between the sequences. The warping path exhibits specific properties that ensure a valid alignment. It is monotonic, meaning the indices i_k and j_k are non-decreasing along the path (i_{k} \geq i_{k-1} and j_{k} \geq j_{k-1}), preventing reversals in the time progression. The path is also continuous, with adjacent steps limited to increments of at most one in each index (i_k - i_{k-1} \leq 1 and j_k - j_{k-1} \leq 1), which avoids skipping elements in either sequence. Additionally, boundary conditions enforce that the path starts at (1, 1) and ends at (n, m), guaranteeing full coverage of both sequences. These allow the path to accommodate expansions and contractions in the sequences, such as aligning multiple points from one sequence to a single point in the other. For instance, consider two short sequences: X = [1, 3, 9, 2, 1] and Y = [2, 0, 0, 8, 7, 2]. The optimal warping path, visualized on a 2D grid of the cost matrix, might proceed as follows: starting at (1,1), it moves to align early elements, then contracts by matching X to multiple Y elements (e.g., horizontal steps), expands later to align Y's trailing points, and ends at (5,6). This path can be represented as a list of pairs:
Stepi_kj_k
111
212
323
434
535
646
756
Such a path illustrates contractions (e.g., step 5, where i_k stays the same) and ensures the total cost is the sum of local distances along these pairs. The warping path serves practical purposes beyond distance computation, including visualization of sequence alignments to highlight temporal correspondences and feature matching in applications like . The accumulated cost along the path provides the overall DTW distance, while the path itself enables detailed inspections, such as identifying regions of significant warping.

Properties and Analysis

Key Properties

Dynamic time warping (DTW) alignments are defined by a warping path that satisfies several fundamental properties to ensure meaningful temporal correspondences between two sequences. These properties guarantee that the alignment respects the sequential order and local of the while minimizing a cumulative cost measure. The monotonicity property requires that the indices in the warping path are non-decreasing, meaning the path can only move forward or stay in place along both sequences, preventing backward jumps that would violate temporal order. Formally, for a warping path p=(p1,,pL)p = (p_1, \dots, p_L) where pk=(ik,jk)p_k = (i_k, j_k), monotonicity holds if ik1iki_{k-1} \leq i_k and jk1jkj_{k-1} \leq j_k for all kk. This ensures faithful timing preservation, such that if one element precedes another in the original sequence, the corresponding elements maintain this order in the alignment. Continuity enforces that steps in the path are adjacent, allowing only horizontal, vertical, or diagonal moves without jumps over elements in either sequence. This is captured by the condition ikik11|i_k - i_{k-1}| \leq 1 and jkjk11|j_k - j_{k-1}| \leq 1, which prohibits omissions and promotes smooth transitions. Together with monotonicity, continuity restricts possible steps to the set {(1,0),(0,1),(1,1)}\{(1,0), (0,1), (1,1)\}, ensuring no element is skipped. Boundary conditions mandate that the path begins at the first elements of both sequences and ends at the last, i.e., p1=(1,1)p_1 = (1,1) and pL=(N,M)p_L = (N,M) for sequences of lengths NN and MM. This anchors the alignment to the full extent of the input data. The locality property in basic DTW arises from the continuity constraint, which bounds individual steps, though global warping can extend far without additional limits; extensions like the Sakoe-Chiba band impose a warping window to further restrict deviations, such as ijr|i - j| \leq r, enhancing computational efficiency and alignment quality. The optimality property ensures the warping path minimizes the total alignment cost, defined as DTW(X,Y)=min{cp(X,Y)p is a valid warping path}\text{DTW}(X,Y) = \min \{ c_p(X,Y) \mid p \text{ is a valid warping path} \}, where cp(X,Y)=k=1Ld(Xik,Yjk)c_p(X,Y) = \sum_{k=1}^L d(X_{i_k}, Y_{j_k}) and dd is a local . Dynamic programming achieves this global optimum by recursively computing minimum costs for subproblems, leveraging the additive cost structure and the monotonic, continuous nature of paths: the optimal path to any cell (i,j)(i,j) is the minimum over admissible predecessors, ensuring no better path exists due to the exhaustive exploration of all valid alignments. Basic DTW exhibits invariance to temporal shifts and speed variations, as the alignment adapts to differences in sequence length and pacing without assuming uniform sampling rates. In some variants, alignments are piecewise linear, approximating nonlinear warps with linear segments between matched points.

Computational Complexity

The standard dynamic time warping (DTW) algorithm exhibits a time complexity of O(nm)O(nm), where nn and mm are the lengths of the two input sequences, arising from the need to fill an n×mn \times m dynamic programming table by evaluating each cell in constant time. This quadratic scaling stems from the exhaustive search over all possible alignments in the warping path, making DTW computationally intensive for long sequences. In terms of space complexity, the naive implementation requires O(nm)O(nm) storage to hold the entire cost matrix, which can become prohibitive for large datasets—for instance, sequences of length 177,000 could demand terabytes of memory. However, this can be optimized to O(min(n,m))O(\min(n, m)) by computing the table row-by-row (or column-by-column) and retaining only the previous and current rows, as each subsequent row depends solely on the prior one, though this approach prevents full path reconstruction without additional bookkeeping. The impact of sequence length is significant: for equal-length sequences with n=m=1000n = m = 1000, DTW requires approximately 1 million operations, which remains feasible on modern hardware but highlights the poor scalability for applications where quadratic growth quickly overwhelms resources. This limitation motivates trade-offs between exact DTW, which guarantees optimality at O(nm)O(nm) cost, and approximate methods that reduce complexity for practical large-scale use while introducing bounded error.

Variants and Extensions

Fast and Approximate DTW

Dynamic time warping (DTW) computations can become prohibitive for long time series due to their quadratic time and space complexity of O(nm), where n and m are the lengths of the input sequences. To address this, fast and approximate DTW techniques employ pruning, approximations, and hardware acceleration to achieve significant speedups while maintaining acceptable accuracy for practical applications. Pruning methods leverage lower bounds to enable early abandoning of unpromising computations during the dynamic programming process. A seminal approach is the LB_Keogh lower bound, which constructs an envelope around one time series and computes the distance to this envelope as a quick lower bound on the true DTW distance, allowing branches in the search to be pruned if their lower bound exceeds the current best distance. This technique, introduced for exact indexing of DTW, facilitates faster similarity searches by skipping irrelevant path regions without missing the optimal alignment. Multiscale approximations reduce computational load by performing DTW at multiple resolutions, starting coarse and refining progressively. The FastDTW algorithm exemplifies this with a recursive multi-resolution strategy: it first computes an approximate warping path on downsampled sequences, then refines it on higher-resolution versions, achieving linear O(n) time and . FastDTW demonstrates high accuracy, often within 1% of exact DTW, while originally reported to provide substantial speedups over the full algorithm; however, recent optimizations to exact DTW, such as advanced lower bounding, can make it faster in realistic applications. Window-based constraints limit the warping path to a local band around the diagonal of the cost matrix, drastically reducing the number of cells evaluated. The Sakoe-Chiba band imposes a fixed-width constraint, typically parameterized by a r, confining alignments to |i - j| ≤ r, which lowers complexity to O(n · r) for equal-length series and is particularly effective for sequences with limited temporal distortions. Similarly, the Itakura parallelogram enforces a constraint with a maximum s, forming a -shaped region that prevents excessive stretching or compression, suitable for applications like speech where distortions follow predictable patterns. Sparse DTW variants further optimize by using heuristics to focus computations on promising path regions, avoiding a full matrix fill. The SparseDTW method dynamically identifies and exploits local similarities between series to sparsely populate the cost matrix, ensuring the exact optimal path is found while using O(k · n) space, where k is the sparsity factor determined by sequence similarity. This approach is especially beneficial for highly similar , yielding speedups proportional to the degree of alignment. Recent advances incorporate GPU acceleration for parallelizing DTW computations, enabling real-time processing of large-scale data. For instance, GPU implementations like those optimized for parallelize the dynamic programming wavefront across thousands of threads, achieving up to 100x speedups over CPU versions for batch alignments while preserving exactness. These methods scale well to modern hardware, supporting applications in streaming analysis, with ongoing developments enhancing efficiency further as of 2025. Evaluations of these techniques highlight trade-offs between accuracy and speed: FastDTW and window-based methods often deliver 10-100x speedups with error rates under 5% relative to exact DTW on benchmark datasets, while like LB_Keogh enables exact results with 5-50x gains in indexing tasks, depending on data characteristics. Sparse and GPU approaches excel in specific regimes, such as sparse alignments or high-throughput scenarios, but may incur minor approximations or hardware dependencies.

Constrained and Weighted DTW

Constrained variants of dynamic time warping (DTW) introduce restrictions on the allowable warping paths to prevent excessive distortions, improving robustness in applications like where alignments must remain plausible. The Sakoe-Chiba band imposes a global constraint by limiting the warping path to a diagonal band of width 2K+12K+1 around the in the cost matrix, such that ijK|i - j| \leq K for all aligned points (i,j)(i, j), where KK is a user-defined parameter typically set to 10-20% of the sequence length. This constraint reduces from O(NM)O(NM) to O(Kmax(N,M))O(K \max(N,M)) while avoiding implausible alignments in similar-length sequences, as originally proposed for optimizing recognition. The Itakura parallelogram, in contrast, applies a local constraint that allows more flexibility at the endpoints but restricts the slope of the warping path to between 0 and some maximum value, forming a parallelogram-shaped region in the cost matrix suitable for utterance-like signals with varying durations. This approach, developed for minimum residual in , better handles cases where one sequence is significantly shorter by permitting asymmetric warping near the boundaries. Amerced DTW (ADTW) addresses outliers and extreme warping by adding a fixed additive penalty ω\omega to the cost of each non-diagonal step in the warping path, discouraging excessive compressions or expansions without completely forbidding them. Introduced as an intuitive constraint for classification, ADTW has demonstrated superior performance over standard DTW with Sakoe-Chiba banding on UCR datasets, with mean rank improvements in nearest-neighbor classifiers. The penalty ω\omega is tuned based on the scale, often set to 10-20% of the average local distance, making ADTW particularly effective for signals with irregular perturbations. Weighted DTW variants modify the local cost function to incorporate domain-specific priorities, enhancing alignment quality for non-stationary data. Time-weighted DTW (TWDTW) assigns exponentially increasing weights λt\lambda^t to observations at time tt, emphasizing recent data in the alignment—ideal for phenological where later seasonal changes are more informative—by multiplying the local distance by λt1+t2/2\lambda^{t_1 + t_2}/2 for aligned points (t1,t2)(t_1, t_2), with λ>1\lambda > 1 typically around 1.1-1.5. This method, applied in for land-cover mapping, improves classification accuracy by 5-15% over vanilla DTW on MODIS imagery by prioritizing temporal recency. Soft-DTW, a smoothed and differentiable , replaces the min\min operation in standard DTW with a log-sum-exp softmin over all possible paths, weighted by a temperature parameter σ\sigma, enabling gradient-based optimization in pipelines while approximating the original DTW distance closely for small σ\sigma. Proposed as a for time-series tasks, soft-DTW facilitates end-to-end learning in neural networks, with convergence rates comparable to Euclidean losses but better handling of temporal misalignments. Derivative DTW (DDTW) incorporates velocity information by augmenting the local distance to include both amplitude and first-derivative differences, defined as d(qi,cj)=qicj+γqicjd(q_i, c_j) = \|q_i - c_j\| + \gamma \|q_i' - c_j'\| , where γ\gamma balances the contributions (often 1-3) and primes denote derivatives approximated via finite differences. This extension produces smoother alignments by penalizing abrupt changes, addressing limitations of vanilla DTW on series with varying speeds, such as motion trajectories, and improving classification accuracy on datasets like ECG signals. DDTW maintains the same computational complexity as DTW but enhances invariance to linear trends, making it suitable for preprocessing before averaging warped series.

Multi-dimensional and Supervised DTW

Multi-dimensional dynamic time warping (DTW) extends the univariate algorithm to sequences in DD-dimensional feature spaces, such as multivariate from sensors, by computing alignments that account for multiple attributes simultaneously. Two primary approaches exist: independent DTW (DTWI_I), which applies univariate DTW to each dimension separately and sums the costs, and dependent DTW (DTWD_D), which enforces a single warping path across all dimensions using a multivariate distance metric, such as the Euclidean norm in the feature space. Neither method universally outperforms the other, as DTWI_I may fail when dimensions are correlated, while DTWD_D can be overly rigid; an adaptive strategy, DTWA_A, selects the better approach per query instance by comparing their minimum costs against a learned threshold, achieving accuracy at least as good as the superior of the two and often higher across diverse datasets like gestures and signals. A notable application of multi-dimensional DTW is in identifying time-varying lead-lag relationships in multivariate , where a two-step method first computes alignments using shapeDTW—a variant incorporating local shape descriptors—and then extracts lag structures from the warping path. This approach, applied to financial and , outperforms alternatives like rolling cross-correlations and standard DTW in robustness to and varying lag patterns, with simulations showing superior recovery of true structures under additive levels up to 20%. In sensor data contexts, such as for human activity analysis, multi-dimensional DTW classifies skeletal trajectories by warping multidimensional joint positions or quaternions, achieving up to 90% accuracy with nearest-neighbor classifiers when using distances, and enabling joint selection to reduce dimensionality without performance loss. For , multi-dimensional DTW synchronizes trajectories across spatial dimensions using a 1-norm , outperforming single-dimension variants by 10-15% in noisy conditions when incorporating derivatives. Supervised DTW integrates warping into pipelines for tasks like and clustering, where optimal paths are learned from to enhance discriminative power. ShapeDTW improves alignment in supervised nearest-neighbor by matching points based on local neighborhoods (e.g., via shape contexts), yielding over 10% accuracy gains on 18 of 84 UCR datasets compared to DTW. It supports template computation by producing more accurate averages for prototypes in or recognition. For kernel-based methods, weighted DTW serves as a kernel in support vector machines (SVMs), penalizing phase differences to classify non-aligned sequences, with multiclass SVM-WDTW achieving state-of-the-art results on UCR archives by leveraging supervised training on annotated . Neural network integrations, such as DTWNet, embed learnable DTW layers for end-to-end feature extraction, using stochastic on warping paths to handle temporal invariances in , reducing while matching or exceeding DTW-based baselines on tasks like . In clustering, DTW Barycenter Averaging (DBA) computes an average template by iteratively aligning sequences to a barycenter via an expectation-maximization-like process: it finds DTW associations between the current average and inputs, then updates positions as weighted means of aligned points, converging to minimize within-cluster . DBA reduces clustering by up to 65% over prior methods like shape-level averaging on standard datasets, making it suitable for template-based supervised refinement in multi-dimensional settings. High dimensionality poses challenges, as the curse of dimensionality amplifies sparsity and computational costs in DTWD_D, potentially degrading alignment quality; solutions include preprocessing with (PCA) to project data onto lower-dimensional subspaces while preserving variance, as commonly applied in to focus on principal joint movements before DTW. Recent advancements as of 2025 include hybrid models combining DTW with transformers for better scalability in large multivariate datasets.

Applications

Speech and Audio Processing

Dynamic time warping (DTW) emerged as a foundational technique in during the , enabling the alignment of variable-length utterances to reference templates by compensating for temporal distortions in . Early applications focused on isolated digit and word recognition, where DTW facilitated endpoint detection and whole-word matching by computing optimal nonlinear alignments between input signals and stored patterns. At Bell Laboratories, systems in the early transitioned from linear time normalization to DTW-based approaches, achieving high accuracy for speaker-dependent isolated digits using spectral features like (LPC) coefficients. The seminal optimization of DTW for recognition, proposed by Sakoe and Chiba, introduced symmetric formulations and slope constraints to improve discrimination, reducing error rates to as low as 0.3% for Japanese digits in controlled tests. In isolated word recognition, DTW excelled by aligning acoustic features frame-by-frame, allowing systems to handle speaking rate variations without requiring fixed durations; this was particularly effective for small-vocabulary tasks like command recognition in the and . For connected word recognition, extensions such as level-building DTW enabled phoneme-level alignment by segmenting utterances into subword units, supporting fluent speech with minimal pauses. By the mid-, DTW was increasingly combined with hidden Markov models (HMMs) to model probabilistic transitions, enhancing robustness for continuous speech; this hybrid approach, developed at , integrated DTW's alignment with HMM's statistical framework, reducing errors in connected digit sequences by incorporating mixture Gaussian densities for acoustic variability. Beyond speech, DTW found applications in music , notably query-by-humming systems where users retrieve songs by singing or melodies; a pioneering implementation used DTW to match hummed pitch sequences against databases, achieving retrieval accuracies over 70% for short queries by tolerating and deviations. In beat tracking, DTW variants align onset detection outputs to estimated grids, enabling precise extraction of rhythmic structures in audio signals; for instance, dynamic programming akin to DTW has been applied to minimize path costs in -varying music, supporting real-time applications. Despite its strengths in temporal alignment, DTW's performance in is limited by sensitivity to speaker variability, as templates are typically speaker-dependent and struggle with inter-speaker acoustic differences like pitch or shifts. Adaptations such as spectral normalization and multiple-template averaging mitigate this, improving speaker independence, but full robustness often requires integration with HMMs or speaker adaptation techniques to normalize features across users.

Time Series in Finance and Other Domains

Dynamic time warping (DTW) has been applied in and to measure similarity between such as prices and economic indicators, accommodating timing shifts and non-linear alignments that Euclidean distances cannot handle effectively. For instance, DTW enables the of temporal alignment across economic indicators like real GDP, revealing patterns despite phase differences. In applications, it facilitates in price fluctuations, allowing traders to identify recurring motifs adjusted for varying speeds of market movements. Additionally, DTW supports portfolio similarity assessment by computing elastic distances between asset return series, aiding in diversification strategies that account for asynchronous behaviors. In , particularly for side-channel attacks since the 2010s, DTW has been used to align power traces in correlation power analysis (CPA), improving key recovery by compensating for timing variations in hardware implementations of cryptographic algorithms like AES. This elastic alignment enhances the correlation between hypothesized and measured power consumption, enabling more robust detection of data-dependent leaks in non-synchronized traces. Beyond , DTW finds applications in for aligning , where it warps trajectories to synchronize expression profiles across experiments with differing sampling rates or biological variability. In for human , multi-dimensional DTW aligns skeletal joint trajectories, distinguishing actions like walking or gesturing despite speed variations in captured data. For , DTW accelerates real-time alignment of raw electrical signals to reference sequences, supporting selective sequencing decisions with GPU-optimized implementations that achieve up to 1.92× speedup in processing. In sensor data analysis, DTW aids by measuring deviations in time-warped distances, such as identifying faults in industrial equipment through scoring in aligned multivariate streams. Recent advances include multi-dimensional DTW for detecting lead-lag relationships in multivariate financial , such as between sector indices, where it identifies directional influences with in high-frequency data from 2022 studies. Weighted DTW variants address non-stationarity in financial markets by assigning higher penalties to recent observations, improving similarity measures for volatile, irregularly sampled economic indicators. These extensions highlight DTW's benefit in handling irregular sampling inherent in real-world , enhancing robustness in domains with sparse or asynchronous data collection.

Alternatives and Implementations

Alternative Similarity Measures

While dynamic time warping (DTW) excels at handling temporal distortions, several alternative similarity measures address its limitations, such as computational expense and potential over-alignment, by imposing stricter assumptions or incorporating noise tolerance. The Euclidean distance computes the root-mean-square difference between aligned points of two time series X=(x1,,xn)X = (x_1, \dots, x_n) and Y=(y1,,ym)Y = (y_1, \dots, y_m), defined as dEucl(X,Y)=i=1min(n,m)(xiyi)2,d_{\text{Eucl}}(X, Y) = \sqrt{\sum_{i=1}^{\min(n,m)} (x_i - y_i)^2},
Add your contribution
Related Hubs
User Avatar
No comments yet.