'''原文链接 感谢博主 https://blog.csdn.net/weixin_39653948/article/details/124416873?ops_request_misc=&request_id=&biz_id=102&utm_term=DTW&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-0-124416873.142^v87^insert_down28v1,239^v2^insert_chatgpt&spm=1018.2226.3001.4187 ''' def dtw(s, t, window): #可以使用 n, m = len(s), len(t) w = np.max([window, abs(n - m)]) dtw_matrix = np.zeros((n + 1, m + 1)) for i in range(n + 1): for j in range(m + 1): dtw_matrix[i, j] = np.inf dtw_matrix[0, 0] = 0 for i in range(1, n + 1): for j in range(np.max([1, i - w]), np.min([m, i + w]) + 1): dtw_matrix[i, j] = 0 for i in range(1, n + 1): for j in range(np.max([1, i - w]), np.min([m, i + w]) + 1): cost = abs(s[i - 1] - t[j - 1]) # take last min from a square box last_min = np.min([dtw_matrix[i - 1, j], dtw_matrix[i, j - 1], dtw_matrix[i - 1, j - 1]]) dtw_matrix[i, j] = cost + last_min return dtw_matrix x = [1, 2, 3, 3, 5, 2, 6, 3] y = [1, 2, 2, 2, 2, 2, 2, 4] # x=torch.randn(1,8) # print(x) # y=torch.randn(1,8) outputs = dtw(x, y, window=3) print(outputs) from fastdtw import fastdtw from scipy.spatial.distance import euclidean # x = np.array([1, 2, 3, 3, 7, 2, 2, 4]) # y = np.array([1, 2, 2, 2, 2, 2, 2, 4]) # x0 = torch.tensor([[1, 2, 3, 3, 7, 2, 2, 4]]) # print(x0) # y = torch.tensor[1, 2, 2, 2, 2, 2, 2, 4] # x=torch.randn(1,8) # print(x) # y=torch.randn(1,8) x1=torch.tensor(x) x1=x1.reshape(1,8) y1=torch.tensor(y) y1=y1.reshape(1,8) distance1, path1 = fastdtw(x1, y1, dist=euclidean) # print(distance1) print(path1)
【DTW的实现】
最新推荐文章于 2024-07-12 16:16:27 发布