# Dynamic Time Warping for Sequence Comparison

DevFeed: [Dynamic Time Warping for Sequence Comparison](<https://devfeed.tech/articles/dynamic-time-warping-for-sequence-comparison-40281.md>)

Original publisher: [Read original article](<https://www.jeremykun.com/2012/07/25/dynamic-time-warping/>)

Published: 2012-07-25T20:11:39Z

Content type: tutorial

Language: en

Sources: [Jeremy Kun](<https://devfeed.tech/sources/jeremy-kun.md>)

Topics: [Sequences](<https://devfeed.tech/topics/sequences.md>), [Python](<https://devfeed.tech/topics/python.md>), [coding](<https://devfeed.tech/topics/coding.md>), [math](<https://devfeed.tech/topics/math.md>)

Tags: [dynamic-programming](<https://devfeed.tech/tags/dynamic-programming.md>), [function](<https://devfeed.tech/tags/function.md>), [lambda](<https://devfeed.tech/tags/lambda.md>), [math](<https://devfeed.tech/tags/math.md>), [mathematics](<https://devfeed.tech/tags/mathematics.md>), [matrix](<https://devfeed.tech/tags/matrix.md>), [min](<https://devfeed.tech/tags/min.md>), [programming](<https://devfeed.tech/tags/programming.md>), [python](<https://devfeed.tech/tags/python.md>), [range](<https://devfeed.tech/tags/range.md>), [return](<https://devfeed.tech/tags/return.md>), [sequences](<https://devfeed.tech/tags/sequences.md>)

## AI overview

This tutorial explains dynamic time warping for comparing sequences of different lengths when their features may occur at different times or rates. It presents a Python implementation using a cost matrix and dynamic programming, with a local numeric distance based on absolute difference.

## Source excerpt

Problem: Write a program that compares two sequences of differing lengths for similarity. Solution: (In Python) import math def dynamicTimeWarp(seqA, seqB, d = lambda x,y: abs(x-y)): # create the cost matrix numRows, numCols = len(seqA), len(seqB) cost = [[0 for _ in range(numCols)] for _ in range(numRows)] # initialize the first row and column cost[0][0] = d(seqA[0], seqB[0]) for i in xrange(1, numRows): cost[i][0] = cost[i-1][0] + d(seqA[i], seqB[0]) for j in xrange(1, numCols): cost[0][j] = cost[0][j-1] + d(seqA[0], seqB[j]) # fill in the rest of the matrix for i in xrange(1, numRows): for j in xrange(1, numCols): choices = cost[i-1][j], cost[i][j-1], cost[i-1][j-1] cost[i][j] = min(choices) + d(seqA[i], seqB[j]) for row in cost: for entry in row: print "%03d" % entry, print "" return cost[-1][-1] Discussion: Comparing sequences of numbers can be tricky business.