使用dtaidistance實現dtw算法(二)


使用dtaidistance實現dtw算法(二)

1、實現兩兩序列之間的距離計算

# DTW Distance Measures Between Set of Series 查看兩兩序列之間的距離
from dtaidistance import dtw
import numpy as np
# The distance_matrix method expects a list of lists/arrays: 數據格式
series = [
    np.array([0, 0, 1, 2, 1, 0, 1, 0, 0], dtype=np.double),
    np.array([0.0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0]),
    np.array([0.0, 0, 1, 2, 1, 0, 0, 0])]

 

dtw.distance_matrix_fast(series)

array([[0. , 1.41421356, 1. ],
[1.41421356, 0. , 1. ],
[1. , 1. , 0. ]])

兩序列之間的距離矩陣,和相關系數矩陣的排列方式是一樣的,(1,1)0第一個、第一個序列之間的距離,(2,1)1.41421356第一個、第二個序列之間的距離,(3,1)1第一個、第三個序列之間的距離,(3,2)1第二個、第三個序列之間的距離。

# or a matrix (in case all series have the same length): numpy格式
series = np.matrix([
    [0.0, 0, 1, 2, 1, 0, 1, 0, 0],
    [0.0, 1, 2, 0, 0, 0, 0, 0, 0],
    [0.0, 0, 1, 2, 1, 0, 0, 0, 0],
    [0.0, 0, 1, 2, 1, 0, 1, 0, 1] # 多加了一行
])
dtw.distance_matrix_fast(series)

array([[0. , 1.41421356, 1. , 1. ],
[1.41421356, 0. , 1. , 1.73205081],
[1. , 1. , 0. , 1.41421356],
[1. , 1.73205081, 1.41421356, 0. ]])
 

2、兩兩序列之間的對應

# 展示兩兩之間的對應關系
from dtaidistance import dtw
from dtaidistance import dtw_visualisation as dtwvis
import numpy as np
s1 = np.array([0., 0, 1, 2, 1, 0, 1, 0, 0, 2, 1, 0, 0])
s2 = np.array([0., 1, 2, 3, 1, 0, 0, 0, 2, 1, 0, 0, 0])
path = dtw.warping_path(s1, s2)
dtwvis.plot_warping(s1, s2, path, filename="warp.png")

image-20211027092440318
 

3、最佳路徑

distance, paths = dtw.warping_paths(s1, s2
                                    #, window=25
                                    #, psi=2
                                   )
print(distance)
best_path = dtw.best_path(paths)# 最短路徑
dtwvis.plot_warpingpaths(s1, s2, paths, best_path)# 制圖

0100


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM