In [1]:
%pylab inline
The dtw module contains a single function named dtw as well.
In [2]:
from dtw import dtw
In [3]:
x = array([0, 0, 1, 1, 2, 4, 2, 1, 2, 0]).reshape(-1, 1)
y = array([1, 1, 1, 2, 2, 2, 2, 3, 2, 0]).reshape(-1, 1)
In [4]:
plot(x)
plot(y)
Out[4]:
In [5]:
dist, cost, acc, path = dtw(x, y, dist=lambda x, y: norm(x - y, ord=1))
In [6]:
print 'Minimum distance found:', dist
In [7]:
imshow(acc.T, origin='lower', cmap=cm.gray, interpolation='nearest')
plot(path[0], path[1], 'w')
xlim((-0.5, acc.shape[0]-0.5))
ylim((-0.5, acc.shape[1]-0.5))
Out[7]:
You can specify your own distance used as the cost measure by the DTW. By default the L1 norm is used.
In [8]:
def my_custom_norm(x, y):
return (x * x) + (y * y)
dist, cost, acc, path = dtw(x, y, dist=my_custom_norm)
Obviously you can also directly use those defined in numpy.
In [9]:
from numpy.linalg import norm
dist, cost, acc, path = dtw(x, y, dist=norm)
The sequences used can be of different length. DTW can also be useful to detect subsequences.
In [10]:
x = range(10)
y = [0] * 5 + x
x = array(x).reshape(-1, 1)
y = array(y).reshape(-1, 1)
In [11]:
dist, cost, acc, path = dtw(x, y, dist=lambda x, y: norm(x - y, ord=1))
In [12]:
imshow(acc.T, origin='lower', cmap=cm.gray, interpolation='nearest')
plot(path[0], path[1], 'w')
xlim((-0.5, acc.shape[0]-0.5))
ylim((-0.5, acc.shape[1]-0.5))
Out[12]:
In [ ]: