Visualizing the cost matrix and the optimal warping path of Dynamic Time Warping (DTW) is crucial for understanding how DTW aligns two time series.
1. The Cost Matrix:
- Construction:
- Imagine two time series,
X
and Y
, with lengths m
and n
, respectively.
- A cost matrix of size
(m x n)
is created.
- Each cell
(i, j)
in the matrix represents the cost of aligning the i
th element of X
with the j
th element of Y
.
- The cost is often calculated using a distance metric like Euclidean distance.
- Visualization:
- The cost matrix is typically visualized as a heatmap.
- The color intensity of each cell corresponds to the cost:
- Darker colors represent higher costs (greater dissimilarity).
- Lighter colors represent lower costs (greater similarity).
- This visualization shows the "local" alignment costs between all pairs of points from the two time series.
2. The Optimal Warping Path:
- Finding the Path:
- DTW finds the path through the cost matrix that minimizes the cumulative cost of aligning the two time series.
- The path starts at the top-left cell (1, 1) and ends at the bottom-right cell (m, n).
- The path is constrained to move only right, down, or diagonally down-right.
- Visualization:
- The optimal warping path is overlaid on the cost matrix.
- It's typically shown as a line or a sequence of connected cells.
- This path highlights the optimal alignment between the two time series, showing which points are matched together.
- Also, sometimes the warping path is shown as lines connecting the two time series, in a two graph plot.
š§ Implementation
1st Method
https://gist.github.com/viadean/8fff37b278271a4f5888fe0b79d91760

2nd Method
https://gist.github.com/viadean/d687dc50f966de3d606e3610662d4eaa

Here is the visualization of the DTW cost matrix with the optimal warping path (in red). The heatmap represents the accumulated cost, while the red path shows the best alignment between the two sequences.