@@ -64,7 +64,7 @@ def _kdtw_lk(x, y, local_kernel):
6464 return cost_matrix [x_timepoints - 1 , y_timepoints - 1 ]
6565
6666
67- def kdtw (x , y , sigma = 1.0 , epsilon = 1e-3 ):
67+ def _kdtw (x , y , sigma = 1.0 , epsilon = 1e-3 ):
6868 """
6969 Callable kernel function for KernelKMeans.
7070
@@ -81,6 +81,12 @@ def kdtw(x, y, sigma=1.0, epsilon=1e-3):
8181 A small constant added for numerical stability to avoid zero values in the
8282 local kernel matrix.
8383
84+ Notes
85+ -----
86+ Inspired by the original implementation
87+ https://github.com/pfmarteau/KDTW/tree/master
88+ Copyright (c) 2020 Pierre-François Marteau, MIT License
89+
8490 Returns
8591 -------
8692 similarity : float
@@ -92,35 +98,6 @@ def kdtw(x, y, sigma=1.0, epsilon=1e-3):
9298 return _kdtw_lk (x , y , local_kernel )
9399
94100
95- def factory_kdtw_kernel (channels : int ):
96- """
97- Return a kdtw kernel callable function that flattened samples to (T, channels).
98-
99- Parameters
100- ----------
101- channels: int
102- Number of channels per timepoint.
103-
104- Returns
105- -------
106- kdtw_kernel : callable
107- A callable kernel function that computes the KDTW similarity between two
108- time series samples. The function signature is the same as the kdtw
109- function.
110- """
111-
112- def kdtw_kernel (x , y , sigma = 1.0 , epsilon = 1e-3 ):
113- if x .ndim == 1 :
114- T = x .size // channels
115- x = x .reshape (T , channels )
116- if y .ndim == 1 :
117- T = y .size // channels
118- y = y .reshape (T , channels )
119- return kdtw (x , y , sigma = sigma , epsilon = epsilon )
120-
121- return kdtw_kernel
122-
123-
124101class TimeSeriesKernelKMeans (BaseClusterer ):
125102 """Kernel K Means [1]_: wrapper of the ``tslearn`` implementation.
126103
@@ -255,7 +232,18 @@ def _fit(self, X, y=None):
255232 verbose = 1
256233
257234 if self .kernel == "kdtw" :
258- self .kernel = factory_kdtw_kernel (channels = X .shape [1 ])
235+ n_channels = X .shape [1 ]
236+
237+ def kdtw_kernel (x , y , sigma = 1.0 , epsilon = 1e-3 ):
238+ if x .ndim == 1 :
239+ T = x .size // n_channels
240+ x = x .reshape (T , n_channels )
241+ if y .ndim == 1 :
242+ T = y .size // n_channels
243+ y = y .reshape (T , n_channels )
244+ return _kdtw (x , y , sigma = sigma , epsilon = epsilon )
245+
246+ self .kernel = kdtw_kernel
259247
260248 self ._tslearn_kernel_k_means = TsLearnKernelKMeans (
261249 n_clusters = self .n_clusters ,
0 commit comments