pollen-robotics / dtw

DTW (Dynamic Time Warping) python module
GNU General Public License v3.0
1.16k stars 233 forks source link

how to use 1 dtw process to figure out the best match #41

Open Erickrus opened 5 years ago

Erickrus commented 5 years ago

I'm working on a sequence matching problem. I cannot figure out a way to find the best match using a single execution. I kind of using dist to move step by step and figure out the corresponding smallest position.

Could you give me some hints, how to use 1 dtw process to figure out the best match? below is the code, modified a little from the example

import numpy as np
from dtw import dtw , accelerated_dtw
import random
import matplotlib.pyplot as plt

# We define two sequences x, y as numpy array
# where y is actually a sub-sequence from x
x = np.array([3,9,9,8,7,2,2, 0, 1, 1.2, 0, 3, 2, 4.3, 2.3, 1, 2.2, 0]).reshape(-1, 1) +2.0
y = np.array([      1, 1.1, 3.5,2, 2, 1, 4.2, 2.1, 1, 2.5, 0]).reshape(-1, 1)

x = x.reshape(-1).tolist()

# added some random samples
for i in range(15):
    x.append(random.randint(0,99)/10.0)
x = np.array(x)

euclidean_norm = lambda x, y: np.abs(x - y)

ds = []
for i in range(x.shape[0] - y.shape[0]-1):
    d, cost_matrix, acc_cost_matrix, path = accelerated_dtw(x[i:i+y.shape[0]], y, dist=euclidean_norm, warp=1)
    ds.append(d)
ds = np.array(ds)

# figure out the position
offset = np.argmin(ds)
print(offset)

plt.plot(x)
if offset>0:
    # padding zeros, align it
    z = np.zeros(offset)
    z = z.tolist()
    z.extend(y.reshape(-1).tolist())
    print(z)
    z = np.array(z)

    plt.plot(z)
else:
    plt.plot(y)
plt.show()