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) omaga = 1 / (1 + exp) return omaga def dtw_mahalanobis(s1, s2): s1, s2 = np.array(s1), np.array(s2) n1, n2 = len(s1), len(s2) d = np.zeros((n1 + 1, n2 + 1)) d[1:, 0] = np.inf d[0, 1:] = np.inf # 计算样本的协方差矩阵 X = np.vstack([s1, s2]) S = np.cov(X.T) S_inv = np.linalg.inv(S) for i in range(1, n1 + 1): for j in range(1, n2 + 1): cost = mahalanobis(s1[i - 1], s2[j - 1], S_inv) d[i, j] = cost + min(d[i - 1, j], d[i, j - 1], d[i - 1, j - 1]) return d[n1, n2] def mahalanobis(x, y, S_inv): diff = x - y return np.sqrt(np.dot(np.dot(diff, S_inv), diff.T)) s1=[[7,9,11,12,8],[6,8,9,11,13],[7,10,13,10,7]] s2 = [[7,8,11,10,9],[9,8,7,14,13],[8,10,8,10,9]] s3 = [[7,9,15,14,9],[9,8,8,14,3],[8,11,8,15,9]] result1 = dtw_mahalanobis(s1, s2) result2 = dtw_mahalanobis(s1, s3) print(result1) print(result2)如何改动
时间: 2023-06-15 22:07:57 浏览: 123
在代码中,需要导入math库,所以需要在代码开头加入import math。
另外,在计算omega时,需要在前面加上math,即math.exp(a)。
完整代码如下:
import numpy as np
import math
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_mahalanobis(s1, s2):
s1, s2 = np.array(s1), np.array(s2)
n1, n2 = len(s1), len(s2)
d = np.zeros((n1 + 1, n2 + 1))
d[1:, 0] = np.inf
d[0, 1:] = np.inf
# 计算样本的协方差矩阵
X = np.vstack([s1, s2])
S = np.cov(X.T)
S_inv = np.linalg.inv(S)
for i in range(1, n1 + 1):
for j in range(1, n2 + 1):
cost = mahalanobis(s1[i - 1], s2[j - 1], S_inv)
d[i, j] = cost + min(d[i - 1, j], d[i, j - 1], d[i - 1, j - 1])
return d[n1, n2]
def mahalanobis(x, y, S_inv):
diff = x - y
return np.sqrt(np.dot(np.dot(diff, S_inv), diff.T))
s1 = [[7,9,11,12,8],[6,8,9,11,13],[7,10,13,10,7]]
s2 = [[7,8,11,10,9],[9,8,7,14,13],[8,10,8,10,9]]
s3 = [[7,9,15,14,9],[9,8,8,14,3],[8,11,8,15,9]]
result1 = dtw_mahalanobis(s1, s2)
result2 = dtw_mahalanobis(s1, s3)
print(result1)
print(result2)
阅读全文