Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c59858d

Browse files
committed
Cythonify slow for loops.
1 parent 65e46de commit c59858d

2 files changed

Lines changed: 16 additions & 8 deletions

File tree

sdtw/distance.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from sklearn.metrics.pairwise import euclidean_distances
44

5+
from .soft_dtw_fast import _jacobian_product_sq_euc
56

67
class SquaredEuclidean(object):
78

@@ -45,15 +46,8 @@ def jacobian_product(self, E):
4546
Product with Jacobian
4647
([m x d, m x n] * [m x n] = [m x d]).
4748
"""
48-
m = self.X.shape[0]
49-
n = self.Y.shape[0]
50-
d = self.X.shape[1]
51-
5249
G = np.zeros_like(self.X)
5350

54-
for i in range(m):
55-
for j in range(n):
56-
for k in range(d):
57-
G[i, k] += E[i,j] * 2 * (self.X[i, k] - self.Y[j, k])
51+
_jacobian_product_sq_euc(self.X, self.Y, E, G)
5852

5953
return G

sdtw/soft_dtw_fast.pyx

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,3 +99,17 @@ def _soft_dtw_grad(np.ndarray[double, ndim=2] D,
9999
b = exp((R[i, j+1] - R[i, j] - D[i-1, j]) / gamma)
100100
c = exp((R[i+1, j+1] - R[i, j] - D[i, j]) / gamma)
101101
E[i, j] = E[i+1, j] * a + E[i, j+1] * b + E[i+1,j+1] * c
102+
103+
104+
def _jacobian_product_sq_euc(np.ndarray[double, ndim=2] X,
105+
np.ndarray[double, ndim=2] Y,
106+
np.ndarray[double, ndim=2] E,
107+
np.ndarray[double, ndim=2] G):
108+
cdef int m = X.shape[0]
109+
cdef int n = Y.shape[0]
110+
cdef int d = X.shape[1]
111+
112+
for i in range(m):
113+
for j in range(n):
114+
for k in range(d):
115+
G[i, k] += E[i,j] * 2 * (X[i, k] - Y[j, k])

0 commit comments

Comments
 (0)