動態時間規整matlab和python代碼

幾篇寫得很好的文章

【重大修改】動態時間規整(Dynamic Time Warping)
算法筆記-DTW動態時間規整
動態時間規整算法(Dynamic Time Warping, DTW)之初探單詞語音識別

(1)相似度計算

先計算歐式距離,然後計算累計損失距離,計算到最後一個值即爲兩個序列的最終距離。
這個最終距離表示兩個序列的相似度,距離越小,相似度越大。
借用上面第二篇的例子:
X:3,5,6,7,7,1
Y:3,6,6,7,8,1,1
DIST
求出第一個歐式距離表後,通過下面公式計算 Mc(i,j)=Min(Mc(i1,j1),Mc(i1,j),Mc(i,j1))+M(i,j)M_c(i,j)=Min(M_c(i-1,j-1),M_c(i-1,j),M_c(i,j-1))+M(i,j)
例如圖中要計算 ? 的值,考慮其左上相鄰3個值和其歐式距離表對應位置上的值。這裏 min(0, 3, 6)+3 = 3.

(2)輸出最佳路徑path

這裏參數包含了對應兩個輸入序列的規整序列,其實就是索引值。這個算法認爲對應索引位置上的值相似度比較大。見代碼如何得到規整後的序列。

(3)代碼

matlab代碼

參考這裏: 【重大修改】動態時間規整(Dynamic Time Warping)

python代碼

import numpy as np
import matplotlib.pyplot as plt

def dtw(x, y, dist):
    """
    Computes Dynamic Time Warping (DTW) of two sequences.

    :param array x: N1*M array
    :param array y: N2*M array
    :param func dist: distance used as cost measure

    Returns the minimum distance, the cost matrix, the accumulated cost matrix, and the wrap path.
    """
    assert len(x)  # Report error while x is none
    assert len(y)
    r, c = len(x), len(y)
    D0 = zeros((r + 1, c + 1))
    D0[0, 1:] = inf
    D0[1:, 0] = inf
    D1 = D0[1:, 1:]  # view

    for i in range(r):
        for j in range(c):
            D1[i, j] = dist(x[i], y[j])
    C = D1.copy()

    for i in range(r):
        for j in range(c):
            D1[i, j] += min(D0[i, j], D0[i, j + 1], D0[i + 1, j])
    if len(x) == 1:
        path = zeros(len(y)), range(len(y))
    elif len(y) == 1:
        path = range(len(x)), zeros(len(x))
    else:
        path = _traceback(D0)
    return D1[-1, -1] / sum(D1.shape), C, D1, path
 

x = np.array([0, 0, 1, 1, 2, 4, 2, 1, 2, 0]).reshape(-1, 1)
y = np.array([1, 1, 1, 2, 2, 2, 2, 3, 2, 0]).reshape(-1, 1)

dist, cost, acc, path = dtw(x, y, dist=lambda x, y: np.linalg.norm(x - y, ord=1))
print('Minimum distance found:', dist)

plt.figure()
plt.subplot(131)
plt.plot(x)
plt.plot(y)
plt.title('orignal data')
plt.subplot(132)
plt.imshow(cost.T, origin='lower', cmap=plt.cm.gray, interpolation='nearest')
plt.plot(path[0], path[1], 'w')
plt.xlim((-0.5, cost.shape[0]-0.5))
plt.ylim((-0.5, cost.shape[1]-0.5))
plt.title('the cost matrix and the wrap path')
plt.subplot(133)
plt.plot(x[path[0]])
plt.plot(y[path[1]])
plt.xlim((-0.5, cost.shape[0]-0.5))
plt.ylim((-0.5, cost.shape[1]-0.5))
plt.title('wrapped signal')
plt.show()

dtw

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章