DTW 算法优化
作者:互联网
import numpy as np #优化前 def Dtw(a, b): dis = np.full((len(a) + 1, len(b) + 1), np.inf) dis[0, 0] = 0 for i in range(0, len(a)): for j in range(0, len(b)): print(a[i],b[j]) dis[i + 1, j + 1] = (a[i] - b[j]) ** 2 for i in range(1, len(a) + 1): for j in range(1, len(b) + 1): dis[i, j] = min(dis[i - 1, j - 1], dis[i, j - 1], dis[i - 1, j]) + dis[i, j] result = dis[len(a)-1, len(b)-1] / (len(a) + len(b)) return result #优化后 def Dtw_k(a, b): dis = np.full((len(a) + 1, len(b) + 1), np.inf) dis[0, 0] = 0 x=np.array(a).repeat(len(b),axis=0).reshape(len(a),len(b)).T y=np.array(b).repeat(len(a),axis=0).reshape(len(b),len(a)) # for i in range(0, len(a)): # for j in range(0, len(b)): # print(a[i],b[j]) # dis[i + 1, j + 1] = (a[i] - b[j]) ** 2 dis[1:, 1:] = ((x - y) ** 2).T for i in range(1, len(a) + 1): for j in range(1, len(b) + 1): print(dis[i - 1, j - 1], dis[i, j - 1],dis[i - 1, j]) dis[i, j] = min(dis[i - 1, j - 1], dis[i, j - 1], dis[i - 1, j]) + dis[i, j] result = dis[len(a)-1, len(b)-1] / (len(a) + len(b)) return result x = [3, 2, 1] y = [1, 2] print(Dtw_k(x, y)) if __name__ == '__main__': pass
标签:__,DTW,range,len,算法,result,np,优化,dis 来源: https://www.cnblogs.com/ltkekeli1229/p/16371966.html