8
8
9
9
import numpy as np
10
10
11
- def utw (x , y , metric ):
11
+ def utw (x , y , div ):
12
12
"""
13
13
Uniform Time Warping
14
+
15
+ Parameters
16
+ ----------
17
+ x : numpy.Array
18
+ Size m_x by n
19
+ y : numpy.Array
20
+ Size m_y by n
21
+ div : function
22
+ Takes two m by n arrays and returns a m by 1 array
23
+ containing the distances between rows 1, rows 2, ...,
24
+ rows m of the two arrays. Does not need to be a metric
25
+ in the mathematical sense
26
+
27
+ Returns
28
+ -------
29
+ dis : float
30
+ The UTW distance between x and y according to
31
+ distance function div
14
32
"""
15
33
if x .shape [0 ] > y .shape [0 ]:
16
34
z = x , y
17
35
y , x = z
18
36
n1 = x .shape [0 ]
19
37
n2 = y .shape [0 ]
20
38
i_half , j_half , i_whole , j_whole = distance_coordinates (n1 , n2 )
21
- d = np .sum ([metric (x [i ,:], y [j ,:]) for i , j in zip (i_half , j_half )]) / 2. + \
22
- np .sum ([metric (x [i ,:], y [j ,:]) for i , j in zip (i_whole , j_whole )])
23
- return d
39
+ dis = 0
40
+ if i_half .size > 0 :
41
+ dis = dis + np .sum (div (x [i_half ,:], y [j_half ,:])) / 2.
42
+ if i_whole .size > 0 :
43
+ dis = dis + np .sum (div (x [i_whole ,:], y [j_whole ,:]))
44
+ return dis
24
45
25
46
26
47
def distance_coordinates (n1 , n2 ):
@@ -40,7 +61,7 @@ def distance_coordinates(n1, n2):
40
61
41
62
42
63
def test ():
43
- metric = lambda x , y : np .sum (np .abs (x - y ))
64
+ metric = lambda x , y : np .sum (np .abs (x - y ), axis = 1 )
44
65
x = np .array ([[0 , 0 ],
45
66
[0 , - 1 ],
46
67
[0 , 0 ],
@@ -54,3 +75,5 @@ def test():
54
75
[1 , 1 ]])
55
76
assert (utw (x , y , metric ) == 26.5 )
56
77
assert (utw (y , x , metric ) == 26.5 )
78
+
79
+ test ()
0 commit comments