DTW simple example


In [1]:
%matplotlib inline

import matplotlib.pyplot as plt
import numpy as np

Let's define our two sequences


In [2]:
# We define two sequences x, y as numpy array
# where y is actually a sub-sequence from x
x = np.array([2, 0, 1, 1, 2, 4, 2, 1, 2, 0]).reshape(-1, 1)
y = np.array([1, 1, 2, 4, 2, 1, 2, 0]).reshape(-1, 1)

In [3]:
plt.plot(x, label='x')
plt.plot(y, label='y')
plt.title('Our two temporal sequences')
plt.legend()


Out[3]:
<matplotlib.legend.Legend at 0x11ad8a390>

Compute the dynamic time warped distance between x and y


In [4]:
from dtw import dtw

# Here, we use L2 norm as the element comparison distance
l2_norm = lambda x, y: (x - y) ** 2

dist, cost_matrix, acc_cost_matrix, path = dtw(x, y, dist=l2_norm)

dist


Out[4]:
2.0

You can plot the accumulated cost matrix and the "shortest" wrap path.


In [5]:
plt.imshow(acc_cost_matrix.T, origin='lower', cmap='gray', interpolation='nearest')
plt.plot(path[0], path[1], 'w')
plt.show()