Dynamic time warping

import math

#the distance between two node in the time series
def calcdist(x,y):
    # if the node is a list
    if type(x) == 'list':
        length = len(x)
        sum = 0
        for i in range(length):
            sum = sum + (x[i]-y[i])*(x[i]-y[i])
        return math.sqrt(sum)
    else:# the node is just a number
        return abs(x-y)

# DP return the distance
def dynamicTimeWarp(seqA, seqB, d ):
    # create the cost matrix
    numRows, numCols = len(seqA), len(seqB)
    cost = [[0 for _ in range(numCols)] for _ in range(numRows)]

    # record father
    fa = [[(0,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 range(1, numRows):
        cost[i][0] = cost[i - 1][0] + d(seqA[i], seqB[0])
        fa[i][0] = (i-1,0)

    for j in range(1, numCols):
        cost[0][j] = cost[0][j - 1] + d(seqA[0], seqB[j])
        fa[0][j] = (0,j-1)

    # fill in the rest of the matrix
    for i in range(1, numRows):
        for j in range(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])
            if cost[i-1][j] < cost[i][j-1]:
                if cost[i-1][j] < cost[i-1][j-1]:
                    cost[i][j] = cost[i-1][j] + d(seqA[i], seqB[j])
                    fa[i][j] = (i-1,j)
                else:
                    cost[i][j] = cost[i - 1][j-1] + d(seqA[i], seqB[j])
                    fa[i][j] = (i-1,j-1)
            else:
                if cost[i][j-1] < cost[i-1][j-1]:
                    cost[i][j] = cost[i][j-1] + d(seqA[i], seqB[j])
                    fa[i][j] = (i,j-1)
                else:
                    cost[i][j] = cost[i - 1][j - 1] + d(seqA[i], seqB[j])
                    fa[i][j] = (i-1,j-1)

    # show the cost matrix
    for row in cost:
        for entry in row:
            print ("%03d" % entry,end="")
        print("")

    # show the path
    path = []
    i = numRows - 1
    j = numCols - 1
    path.append((i,j))
    while i!=0 or j!=0:
        i,j=fa[i][j]
        path.append((i,j))
    for cord in path[::-1]:
        print(cord, ' ', end="")
    print("")

    return cost[-1][-1]

seqA = [0,0,0,3,6,13,25,22,7,2,1,0,0,0,0,0,0]
seqB = [0,0,0,0,0,0,4,5,12,24,23,8,3,1,0,0]
print(type(seqA))
dist = dynamicTimeWarp(seqA,seqB,calcdist)
print(dist)

"""
[0,0,0,3,6,13,25,22,7,2,1,0,0,0,0,0,0]
[0,0,0,0,0,0,4,5,12,24,23,8,3,1,0,0]
"""

猜你喜欢

转载自blog.csdn.net/algzjh/article/details/81068693