import numpy as np
def do(ts_a, ts_b):
ts_c = ts_a - ts_b
ts_c = ts_c[np.newaxis,:]
osd = np.linalg.norm(ts_c, ord=None, axis=1, keepdims=True)
return osd
def cal_dtw_distance(ts_a, ts_b):
"""Returns the DTW similarity distance between two 2-D
timeseries numpy arrays.
Arguments
---------
ts_a, ts_b : array of shape [n_samples, n_timepoints]
Two arrays containing n_samples of timeseries data
whose DTW distance between each sample of A and B
will be compared
d : DistanceMetric object (default = abs(x-y))
the distance measure used for A_i - B_j in the
DTW dynamic programming function
Returns
-------
DTW distance between A and B
"""
# Create cost matrix via broadcasting with large int
ts_a, ts_b = np.array(ts_a), np.array(ts_b)
M, N = len(ts_a), len(ts_b)
cost = np.ones((M, N))
# Initialize the first row and column
cost[0, 0] = do(ts_a[0], ts_b[0])
for i in range(1, M):
cost[i, 0] = cost[i - 1, 0] + do(ts_a[i], ts_b[0])
for j in range(1, N):
cost[0, j] = cost[0, j - 1] + do(ts_a[0], ts_b[j])
# Populate rest of cost matrix within window
for i in range(1, M):
for j in range(1,N):
choices = cost[i - 1, j - 1], cost[i, j - 1], cost[i - 1, j]
cost[i, j] = min(choices) + do(ts_a[i], ts_b[j])
# Return DTW distance given window
return cost[-1, -1]
if __name__ == "__main__":
# 案例:判断ts_a与ts_b和ts_c哪个更相似
path1 = './m1_a2_list.npy'
data1 = np.load(path1)
ts_a1 = data1[0]
ts_b1 = data1[1]
print(ts_a1)
path2 = './m2_a2_list.npy'
data2 = np.load(path2)
ts_a2 = data2[0]
# 调用cal_dtw_distance计算dtw相似度
dtw_ab = cal_dtw_distance(ts_a1, ts_a2)
print('ts_a与ts_b的dtw相似度为 : ',dtw_ab)