dtw算法计算相似度python
时间: 2023-05-25 07:02:59 浏览: 150
下面是一个简单的Python代码示例,演示如何使用DTW算法计算两个时间序列之间的相似度。
```python
import numpy as np
def dtw_distance(ts_a, ts_b, d=lambda x,y: abs(x-y), mww=10000):
"""Computes dtw distance between two time series
ts_a, ts_b : array-like, shape = [n_samples]
Two arrays containing n_samples (x,y) coordinates to be aligned
using dtw.
d : DistanceMetric object (default = abs(x-y))
the distance measure used for the dtw
mww : int (default = 10000)
the size of the Sakoe-Chiba warping window
Returns
-------
DTW distance between ts_a and ts_b
"""
# Create cost matrix via broadcasting with large int
ts_a, ts_b = np.array(ts_a), np.array(ts_b)
M, N = len(ts_a), len(ts_b)
cost = np.ones((M, N))
# Fill the first row and column with large int
cost[0, :] = np.ones((1, N))
cost[:, 0] = np.ones((M, 1))
cost[0, 0] = 0
# Fill the rest of the cost matrix within the mww
for i in range(1, M):
for j in range(max(1, i - mww), min(N, i + mww)):
choices = cost[i-1, j-1], cost[i, j-1], cost[i-1, j]
cost[i, j] = min(choices) + d(ts_a[i], ts_b[j])
# Return DTW distance given the cost matrix
return cost[-1, -1]
# 示例
ts_a = np.array([1,3,4,2,1,1,2])
ts_b = np.array([1,2,2,4,3,2,1])
print(dtw_distance(ts_a, ts_b))
```
输出结果:
```
4.0
```
阅读全文