import numpy as np
a = np.random.randint(0,5,5)
b = np.random.randint(0,5,2)
a,b
(array([3, 1, 3, 1, 4]), array([1, 2]))
l1 = len(a)
l2 = len(b)
dp table备忘录
dp = np.full((l1+1,l2+1),fill_value=float('inf'))
dp[0,0]=0
choices记录移动方向,初始化
最终要从dp[i,j]往dp[1,1]的回推
choices = np.full((l1+1,l2+1),fill_value='45')
choices
array([['45', '45', '45'],
['45', '45', '45'],
['45', '45', '45'],
['45', '45', '45'],
['45', '45', '45'],
['45', '45', '45']], dtype='
计算两点距离
def distance(m,n):
return np.abs((m-n))
DTW
for i in range(1,l1+1):
for j in range(1,l2+1):
which = np.argmin((dp[i-1,j-1],dp[i-1,j],dp[i,j-1]))
if which==0:
pass
elif which==1:
choices[i,j]='up'
else:
choices[i,j] = 'lf'
dp[i,j] = min(dp[i-1,j-1],dp[i-1,j],dp[i,j-1])+distance(a[i-1],b[j-1])
dp
array([[ 0., inf, inf],
[inf, 2., 3.],
[inf, 2., 3.],
[inf, 4., 3.],
[inf, 4., 4.],
[inf, 7., 6.]])
choices
array([['45', '45', '45'],
['45', '45', 'lf'],
['45', 'up', '45'],
['45', 'up', '45'],
['45', 'up', 'up'],
['45', 'up', '45']], dtype='
你可能感兴趣的:(动态规划,相似度,动态规划,python)