An Illustrative Introduction to Dynamic Time Warping | by Esmaeil Alizadeh | Towards Data Science

Dynamic Time Warping (DTW) is a way to compare two -usually temporal- sequences that do not sync up perfectly. It is a method to calculate the optimal matching between two sequences. DTW is useful in many domains such as speech recognition, data mining, financial markets, etc. It’s commonly used in data mining to measure the distance between two time-series.
In this post, we will go over the mathematics behind DTW. Then, two illustrative examples are provided to better understand the concept. If you are not interested in the math behind it, please jump to examples.
Let’s assume we have two sequences like the following:
X=x[1], x[2], ..., x[i], ..., x[n]
Y=y[1], y[2], ..., y[j], ..., y[m]
The sequences X and Y can be arranged to form an n-by-m grid, where each point (i, j) is the alignment between x[i] and y[j].
A warping path W maps the elements of X and Y to minimize the distance between them. W is a sequence of grid points (i, j). We will see an example of the warping path later.
The Optimal path to (i_k, j_k) can be computed by:
where d is the Euclidean distance. Then, the overall path cost can be calculated as
The warping path is found using a dynamic programming approach to align two sequences. Going through all possible paths is “combinatorically explosive” [1]. Therefore, for efficiency purposes, it’s important to limit the number of possible warping paths, and hence the following constraints are outlined:
Boundary Condition: This constraint ensures that the warping path begins with the start points of both signals and terminates with their endpoints.
Monotonicity condition: This constraint preserves the time-order of points (not going back in time).
Continuity (step size) condition: This constraint limits the path transitions to adjacent points in time (not jumping in time).
In addition to the above three constraints, there are other less frequent conditions for an allowable warping path:
Warping window condition: Allowable points can be restricted to fall within a given warping window of width ω (a positive integer).
Slope condition: The warping path can be constrained by restricting the slope, and consequently avoiding extreme movements in one direction.
An acceptable warping path has combinations of chess king moves that are:
Horizontal moves: (i, j) → (i, j+1)
Vertical moves: (i, j) → (i+1, j)
Diagonal moves: (i, j) → (i+1, j+1)
Let’s import all python packages we need.
import pandas as pdimport numpy as np# Plotting Packagesimport matplotlib.pyplot as pltimport seaborn as sbn# Configuring Matplotlibimport matplotlib as mplmpl.rcParams['figure.dpi'] = 300savefig_options = dict(format="png", dpi=300, bbox_inches="tight")# Computation packagesfrom scipy.spatial.distance import euclideanfrom fastdtw import fastdtw
Let’s define a method to compute the accumulated cost matrix D for the warp path. The cost matrix uses the Euclidean distance to calculate the distance between every two points. The methods to compute the Euclidean distance matrix and accumulated cost matrix are defined below:
In this example, we have two sequences x and y with different lengths.
# Create two sequencesx = [3, 1, 2, 2, 1]y = [2, 0, 0, 3, 3, 1, 0]
We cannot calculate the Euclidean distance between x and y since they don’t have equal lengths.
Many Python packages calculate the DTW by just providing the sequences and the type of distance (usually Euclidean). Here, we use a popular Python implementation of DTW that is FastDTW which is an approximate DTW algorithm with lower time and memory complexities [2].
dtw_distance, warp_path = fastdtw(x, y, dist=euclidean)
Note that we are using SciPy’s distance function Euclidean that we imported earlier. For a better understanding of the warp path, let’s first compute the accumulated cost matrix and then visualize the path on a grid. The following code will plot a heatmap of the accumulated cost matrix.
cost_matrix = compute_accumulated_cost_matrix(x, y)
The color bar shows the cost of each point in the grid. As can be seen, the warp path (blue line) is going through the lowest cost on the grid. Let’s see the DTW distance and the warping path by printing these two variables.
>>> DTW distance:  6.0>>> Warp path: [(0, 0), (1, 1), (1, 2), (2, 3), (3, 4), (4, 5), (4, 6)]
The warping path starts at point (0, 0) and ends at (4, 6) by 6 moves. Let’s also calculate the accumulated cost most using the functions we defined earlier and compare the values with the heatmap.
cost_matrix = compute_accumulated_cost_matrix(x, y)print(np.flipud(cost_matrix)) # Flipping the cost matrix for easier comparison with heatmap values!>>> [[32. 12. 10. 10.  6.]       [23. 11.  6.  6.  5.]        [19. 11.  5.  5.  9.]       [19.  7.  4.  5.  8.]       [19.  3.  6. 10.  4.]       [10.  2.  6.  6.  3.]       [ 1.  2.  2.  2.  3.]]
The cost matrix is printed above has similar values to the heatmap.
Now let’s plot the two sequences and connect the mapping points. The code to plot the DTW distance between x and y is given below.
In this example, we will use two sinusoidal signals and see how they will be matched by calculating the DTW distance between them.
Just like Example 1, let’s calculate the DTW distance and the warp path for x1 and x2 signals using FastDTW package.
distance, warp_path = fastdtw(x1, x2, dist=euclidean)
As can be seen in above figure, the DTW distance between the two signals is particularly powerful when the signals have similar patterns. The extrema (maximum and minimum points) between the two signals are correctly mapped. Moreover, unlike Euclidean distance, we may see many-to-one mapping when DTW distance is used, particularly if the two signals have different lengths.
You may spot an issue with dynamic time warping from the figure above. Can you guess what it is?
The issue is around the head and tail of time-series that do not properly match. This is because the DTW algorithm cannot afford the warping invariance for at the endpoints. In short, the effect of this is that a small difference at the sequence endpoints will tend to contribute disproportionately to the estimated similarity[3].
DTW is an algorithm to find an optimal alignment between two sequences and a useful distance metric to have in our toolbox. This technique is useful when we are working with two non-linear sequences, particularly if one sequence is a non-linear stretched/shrunk version of the other. The warping path is a combination of “chess king” moves that starts from the head of two sequences and ends with their tails.
You can find the Jupyter notebook for this blog post here. Thanks for reading!
[1] Donald J. Berndt and James Clifford, Using Dynamic Time Warping to Find Patterns in Time Series, 3rd International Conference on Knowledge Discovery and Data Mining
[2] Salvador, S. and P. Chan, FastDTW: Toward accurate dynamic time warping in linear time and space (2007), Intelligent Data Analysis
[3] Diego Furtado Silva, et al., On the effect of endpoints on dynamic time warping (2016), SIGKDD Workshop on Mining and Learning from Time Series