【发布时间】:2026-01-07 05:20:06
【问题描述】:
女士们,先生们,晚上好,
我想在 Python 中实现一个动态时间规整 (DTW) 算法。
出于测试目的,我设置了一个小的随机距离矩阵(例如,由曼哈顿度量生成),然后用它调用我的 DTW 算法。
import numpy as np
from dynamic_time_warping import compute_dtw
x=np.zeros((3,4))
x[0,2]=1.0
x[0,3]=2.0
x[1,2]=1.0
x[1,3]=2.0
x[2,0]=1.0
x[2,1]=1.0
x[2,3]=1.0
compute_dtw(x)
我的DTW算法如下:
def compute_dtw(W):
if W.shape[0]==1 or W.shape[1]==1:
C=float("inf")
if W.shape[0]==1 and W.shape[1]==1:
C=0.0
else:
C=W[len(W),len(W)]+min(compute_dtw(W[0:-1, 0:-1]),
compute_dtw(W[0:-1]), compute_dtw(W[:, 0:-1]))
return C
我希望算法获取 x 的 m*n 值并将其添加到下一个最小值,我试图通过使用更小的矩阵再次调用该函数来实现该最小值。 (compute_dtw(W[0:-1, 0:-1]), compute_dtw(W[0:-1]), compute_dtw(W[:, 0:-1]))
通过脚本后,这给了我以下错误:
C=W[len(W),len(W)]+min(compute_dtw(W[0:-1, 0:-1]), compute_dtw(W[0:-1]), compute_dtw(W[:, 0:-1])) IndexError: index 3 is 尺寸为 3 的轴 0 超出范围
显然,我正在调用不存在的数组元素,但我无法弄清楚它在哪里中断。
感谢您的建议和帮助!
//更新代码:
def compute_dtw(W):
if W.shape[0]==1 and W.shape[1]==1:
C=0.0
elif W.shape[0]==1 or W.shape[1]==1:
C=float("inf")
else:
C=W[W.shape[0]-1,W.shape[1]-1]+min(compute_dtw(W[0:-1, 0:-1]), compute_dtw(W[0:-1]), compute_dtw(W[:, 0:-1]))
return C
【问题讨论】:
-
有什么东西被保存到矩阵
W中了吗?看起来不是这样......此外,DTW 算法中的递归,就像在许多其他算法中一样,是使用动态编程实现的,以避免进行冗余计算,这会将您的时间复杂度从O(MN)提高到O(2^N)甚至更糟。这是 DTW 的动态编程实现:github.com/talcs/simpledtw/blob/master/simpledtw.py
标签: python optimization recursion