DTW(Dynamic time warping)
基本方法
1 int DTWDistance(s: array [1..n], t: array [1..m]) { 2 DTW := array [0..n, 0..m] 3 4 for i := 1 to n 5 DTW[i, 0] := infinity 6 for i := 1 to m 7 DTW[0, i] := infinity 8 DTW[0, 0] := 0 9 10 for i := 1 to n 11 for j := 1 to m 12 cost := d(s[i], t[j]) 13 DTW[i, j] := cost + minimum(DTW[i-1, j ], // insertion 14 DTW[i , j-1], // deletion 15 DTW[i-1, j-1]) // match 16 17 return DTW[n, m] 18 }
加限制条件以后的方法
int DTWDistance(s: array [1..n], t: array [1..m], w: int) { DTW := array [0..n, 0..m] w := max(w, abs(n-m)) // adapt window size (*) for i := 0 to n for j:= 0 to m DTW[i, j] := infinity DTW[0, 0] := 0 for i := 1 to n for j := max(1, i-w) to min(m, i+w) cost := d(s[i], t[j]) DTW[i, j] := cost + minimum(DTW[i-1, j ], // insertion DTW[i, j-1], // deletion DTW[i-1, j-1]) // match return DTW[n, m] }
这两种方法的时间复杂度都是平方级的。
PrunedDTW
1 Input: Time series x, with length N 2 Time series y, with length M 3 Warping window size ws 4 Upper bound UB of the DTW between x and y 5 Output: The distance between x and y according DTW 6 {Auxiliary variable to prune lower triangular} 7 sc 1 8 {Auxiliary variable to prune upper triangular} 9 ec 1 10 {Initialize the matrix of DTW calculations } 11 for i = 1 to N do 12 D[i; 0] 1 13 end for 14 for i = 1 to M do 15 D[0; i] 1 16 end for 17 D[0; 0] 0 18 for i = 1 to N do 19 beg max(sc; i - ws) 20 end min(i + ws;M) 21 smaller found FALSE 22 ec next i 23 for j = beg to end do 24 D[i; j] = sqED(xi; yj ) 25 + min(D[i - 1; j - 1];D[i - 1; j];D[i; j - 1]) 26 if D[i; j] > UB then 27 if smaller found = FALSE then 28 sc j + 1 29 end if 30 if j ec then 31 break fbreak the for loop / jump to the next rowg 32 end if 33 else 34 smaller found TRUE 35 ec next j + 1 36 end if 37 end for 38 ec ec next 39 end for 40 return D[N;M]