import math import numpy as np def mlwf(alpha, beta, t_i, t_j): # 时间权重 g = abs(int(t_i) - int(t_j)) a = -alpha * (g - beta) exp = math.exp(a) omega = 1 / (1 + exp) return omega def dtw(s, t, alpha, beta): # 计算 DTW 距离 n, m = len(s), len(t) dtw_matrix = np.zeros((n + 1, m + 1)) for i in range(1, n + 1): dtw_matrix[i, 0] = float('inf') for j in range(1, m + 1): dtw_matrix[0, j] = float('inf') dtw_matrix[0, 0] = 0 for i in range(1, n + 1): for j in range(1, m + 1): cost = abs(s[i - 1] - t[j - 1]) omaga = mlwf(alpha, beta, s[i - 1][0], t[j - 1][0]) # 计算时间权重 dtw_matrix[i, j] = cost * omaga + min(dtw_matrix[i - 1, j], dtw_matrix[i, j - 1], dtw_matrix[i - 1, j - 1]) return dtw_matrix[n, m] def calculate_dtw(seq1, seq2, alpha, beta): s = np.array(seq1) t = np.array(seq2) return dtw(s, t, alpha, beta) # 示例代码 seq1 = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 41)] seq2 = [(1, 15), (2, 32), (3, 25), (4, 35), (5, 49)] alpha = 0.5 beta = 2 dtw_distance = calculate_dtw(seq1, seq2, alpha, beta) print('DTW距离:', dtw_distance)检查一下有什莫问题
时间: 2023-06-16 18:04:15 浏览: 154
python 3.74 运行import numpy as np 报错lib\site-packages\numpy\__init__.py
代码中存在一个拼写错误:第8行的 mlwf 函数中的 omaga 应该为 omega。另外,在调用 calculate_dtw 函数时,seq1 和 seq2 序列中的元素应该是数字,而不是元组。可以将示例代码改为:
seq1 = [10, 20, 30, 40, 41]
seq2 = [15, 32, 25, 35, 49]
alpha = 0.5
beta = 2
dtw_distance = calculate_dtw(seq1, seq2, alpha, beta)
print('DTW距离:', dtw_distance)
阅读全文