如何创建成对的 DTW 成本矩阵?

How to create a pairwise DTW cost matrix?

我正在尝试在 python 中创建成对的 DTW(动态时间扭曲)矩阵。我已经有了下面的代码,但不知何故不正确。我当前的输出是一个充满无穷大的矩阵,这是不正确的。我不知道我做错了什么。

def calc_pairwise_dtw_cost(x, y):
    
    cost_matrix = np.zeros((len(y), len(x)))
    dtw_cost = None


    for i in range(0, len(y)):
        for j in range(0, len(x)):
            cost_matrix[i, j] = float('inf')
        

    for i in range(1, len(y)):
        for j in range(1, len(x)):
            dtw_cost = cost_matrix[-1,-1]
            cost_matrix[i, j] = dtw_cost + min(
                cost_matrix[i-1, j],    # insertion
                cost_matrix[i, j-1],    # deletion
                cost_matrix[i-1, j-1])   # match

    return cost_matrix

当前输出为:

array([[inf, inf, inf, ..., inf, inf, inf],
       [inf, inf, inf, ..., inf, inf, inf],
       [inf, inf, inf, ..., inf, inf, inf],
       ...,
       [inf, inf, inf, ..., inf, inf, inf],
       [inf, inf, inf, ..., inf, inf, inf],
       [inf, inf, inf, ..., inf, inf, inf]])

根据 IEEE 754 规则,inf + 任何东西都是 inf。由于您用无穷大填充矩阵,然后从中读取一个值并添加另一个值,因此您不禁会得到一个无穷大的结果。

在您的实施中有几个错误,包括:

  • 忽略使用输入数组 x, y
  • cost_matrix 声明的尺寸不正确
  • cost_matrix[0,0] 应该初始化为 0

Dynamic Time Warping: Explanation and Code Implementation 提供了一个 DTW 的实现,它紧跟 Wikipedia 伪代码如下。

代码

def dtw(s, t):
    n, m = len(s), len(t)
    dtw_matrix = np.zeros((n+1, m+1))  # note the +1 added to n & m
    for i in range(n+1):
        for j in range(m+1):
            dtw_matrix[i, j] = np.inf
    dtw_matrix[0, 0] = 0               # [0,0] element set to 0
    
    for i in range(1, n+1):
        for j in range(1, m+1):
            cost = abs(s[i-1] - t[j-1]) # use inputs s & t
            # 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