Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Time Warping in Python [closed]

Tags:

python

Does anyone know of a python library that has DTW implementation? mlpy seems to have what I'm looking for, but I can't seem to install it correctly -- currently awaiting replies from the mailing list so I thought I would scope out other libraries.

like image 207
C. Reed Avatar asked Apr 17 '11 18:04

C. Reed


Video Answer


2 Answers

Had to chime in on this one. To follow up with C's response, here's an implementation that is geared more towards interfacing with data generated in NumPy. I find this to be considerably more useful since typically I'm generating data in Python and want to interface with R resources.

import numpy as np

import rpy2.robjects.numpy2ri
from rpy2.robjects.packages import importr

rpy2.robjects.numpy2ri.activate()

# Set up our R namespaces
R = rpy2.robjects.r
DTW = importr('dtw')

# Generate our data
idx = np.linspace(0, 2*np.pi, 100)
template = np.cos(idx)
query = np.sin(idx) + np.array(R.runif(100))/10

# Calculate the alignment vector and corresponding distance
alignment = R.dtw(query, template, keep=True)
dist = alignment.rx('distance')[0][0]

print(dist)

Note that this is the example problem stated on the DTW site.

like image 81
Stefan Novak Avatar answered Oct 06 '22 16:10

Stefan Novak


For the record, I have been able to use a mashup of R, DTW in R, and rpy2. Working with R in Python is surprisingly simple and extends python's statistical capabilities considerably. Here's an example of finding the distance between an offset noisy sine and cosine series:

    import rpy2.robjects as robjects
    r = robjects.r
    r('library("dtw")')
    idx = r.seq(0,6.28,len=100)
    template = r.cos(idx)
    query = r.sin(idx)+r('runif(100)/10')
    alignment=r.dtw(query,template,keep=r('TRUE'))
    robjects.globalenv["alignment"] =  alignment
    dist = r('alignment$distance')
    print(dist)

like image 38
C. Reed Avatar answered Oct 06 '22 15:10

C. Reed