使用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")
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)# 制图