/
dist_to_kern.py
272 lines (208 loc) · 9.21 KB
/
dist_to_kern.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
"""Wrappers to convert distance to kernel or kernel to distance."""
__author__ = ["fkiraly"]
import numpy as np
from sktime.dists_kernels.base import BasePairwiseTransformerPanel
SUPPORTED_MTYPES = ["pd-multiindex", "nested_univ", "df-list", "numpy3D"]
def _trafo_diag(fun):
"""Obtain a function which returns the diagonal from one that returns a matrix."""
def diag(X):
mat = fun(X)
return np.diag(mat)
return diag
class KernelFromDist(BasePairwiseTransformerPanel):
r"""Kernel function obtained from a distance function.
Formal details (for real valued objects, mixed typed rows in analogy):
Let :math:`d: \mathbb{R}^D \times \mathbb{R}^D\rightarrow \mathbb{R}`
be the pairwise function in ``dist``, when applied to ``D``-vectors.
If ``dist_diag=None``, then ``KernelFromDist(dist)`` corresponds to the kernel
function
:math:`k(x, y) := d(x, x)^2 + d(y, y)^2 - 0.5 \cdot d(x, y)^2`.
If ``dist_diag`` is provided,
and corresponds to a function :math:`f:\mathbb{R}^D \rightarrow \mathbb{R}`,
then ``KernelFromDist(dist)`` corresponds to the kernel function
:math:`k(x, y) := f(x, x)^2 + f(y, y)^2 - 0.5 \cdot d(x, y)^2`.
It should be noted that :math:`k` is, in general, not positive semi-definite.
Parameters
----------
dist : pairwise transformer of BasePairwiseTransformer scitype, or
callable np.ndarray (n_samples, nd) x (n_samples, nd) -> (n_samples x n_samples)
dist_diag : pairwise transformer of BasePairwiseTransformer scitype, or
series-to-panel transformer of Basetransformer scitype, or
callable np.ndarray (n_samples, nd) -> (n_samples, )
"""
_tags = {
"authors": "fkiraly",
"X_inner_mtype": SUPPORTED_MTYPES,
"capability:missing_values": True, # can estimator handle missing data?
"capability:multivariate": True, # can estimator handle multivariate data?
"capability:unequal_length": True, # can dist handle unequal length panels?
"pwtrafo_type": "kernel",
}
def __init__(self, dist, dist_diag=None):
self.dist = dist
self.dist_diag = dist_diag
super().__init__()
# set property tags based on tags of components
missing = True
multi = True
unequal = True
if isinstance(dist, BasePairwiseTransformerPanel):
missing = missing and dist.get_tag("capability:missing_values")
multi = multi and dist.get_tag("capability:multivariate")
unequal = unequal and dist.get_tag("capability:unequal_length")
tag_dict = {
"capability:missing_values": missing,
"capability:multivariate": multi,
"capability:unequal_length": unequal,
}
self.set_tags(**tag_dict)
def _transform(self, X, X2=None):
"""Compute distance/kernel matrix.
private _transform containing core logic, called from public transform
Parameters
----------
X: sktime Panel data container
X2: sktime Panel data container
Returns
-------
distmat: np.array of shape [n, m]
(i,j)-th entry contains distance/kernel between X.iloc[i] and X2.iloc[j]
"""
from sktime.transformations.base import BaseTransformer
dist = self.dist
dist_diag = self.dist_diag
if dist_diag is None:
dist_diag = dist
if isinstance(dist_diag, BasePairwiseTransformerPanel):
diagfun = dist_diag.transform_diag
elif isinstance(dist_diag, BaseTransformer):
diagfun = dist_diag.fit_transform
else:
diagfun = _trafo_diag(dist_diag)
distmat = dist(X, X2) ** 2
diag1 = diagfun(X)
if X2 is None:
diag2 = diag1
else:
diag2 = diagfun(X2)
diag1 = np.array(diag1).flatten() ** 2
diag2 = np.array(diag2).flatten() ** 2
n, m = distmat.shape
mat1 = np.tile(np.expand_dims(diag1, 1), m)
mat2 = np.tile(np.expand_dims(diag2, 1), n)
mat2 = mat2.transpose()
kernmat = mat1 + mat2 - 0.5 * distmat
return kernmat
@classmethod
def get_test_params(cls, parameter_set="default"):
"""Return testing parameter settings for the estimator.
Parameters
----------
parameter_set : str, default="default"
Name of the set of test parameters to return, for use in tests. If no
special parameters are defined for a value, will return ``"default"`` set.
Returns
-------
params : dict or list of dict, default={}
Parameters to create testing instances of the class.
Each dict are parameters to construct an "interesting" test instance, i.e.,
``MyClass(**params)`` or ``MyClass(**params[i])`` creates a valid test
instance.
``create_test_instance`` uses the first (or only) dictionary in ``params``.
"""
from sktime.dists_kernels.dtw import DtwDist
from sktime.transformations.series.adapt import PandasTransformAdaptor
from sktime.transformations.series.summarize import SummaryTransformer
params1 = {"dist": DtwDist()}
t = SummaryTransformer("mean", None)
# we need this since multivariate summary produces two columns
# if one column, has no effect; if multiple, takes means by row
t = PandasTransformAdaptor("mean", {"axis": 1}) * t
params2 = {"dist": DtwDist(), "dist_diag": t}
return [params1, params2]
class DistFromKernel(BasePairwiseTransformerPanel):
r"""Distance function obtained from a kernel function.
Formal details (for real valued objects, mixed typed rows in analogy):
Let :math:`k: \mathbb{R}^D \times \mathbb{R}^D\rightarrow \mathbb{R}`
be the pairwise function in ``kernel``, when applied to ``D``-vectors.
``DistFromKernel(dist)`` corresponds to the distance function
:math:`d(x, y) := \sqrt{k(x, x) + k(y, y) - 2 \cdot k(x, y)}`.
It should be noted that if :math:`k` is positive semi-definite,
then :math:`d` will be a metric and satisfy the triangle inequality.
Parameters
----------
kernel : pairwise transformer of BasePairwiseTransformer scitype, or
callable np.ndarray (n_samples, nd) x (n_samples, nd) -> (n_samples x n_samples)
"""
_tags = {
"authors": "fkiraly",
"X_inner_mtype": SUPPORTED_MTYPES,
"capability:missing_values": True, # can estimator handle missing data?
"capability:multivariate": True, # can estimator handle multivariate data?
"capability:unequal_length": True, # can dist handle unequal length panels?
"pwtrafo_type": "distance",
}
def __init__(self, kernel):
self.kernel = kernel
super().__init__()
# set property tags based on tags of components
tags_to_clone = [
"capability:missing_values",
"capability:multivariate",
"capability:unequal_length",
]
if isinstance(kernel, BasePairwiseTransformerPanel):
self.clone_tags(kernel, tags_to_clone)
def _transform(self, X, X2=None):
"""Compute distance/kernel matrix.
private _transform containing core logic, called from public transform
Parameters
----------
X: sktime Panel data container
X2: sktime Panel data container
Returns
-------
distmat: np.array of shape [n, m]
(i,j)-th entry contains distance/kernel between X.iloc[i] and X2.iloc[j]
"""
kernel = self.kernel
kernelmat = kernel(X, X2)
if isinstance(kernel, BasePairwiseTransformerPanel):
diagfun = kernel.transform_diag
else:
diagfun = _trafo_diag(kernel)
diag1 = diagfun(X)
if X2 is None:
diag2 = diag1
else:
diag2 = diagfun(X2)
diag1 = np.array(diag1).flatten()
diag2 = np.array(diag2).flatten()
n, m = kernelmat.shape
mat1 = np.tile(np.expand_dims(diag1, 1), m)
mat2 = np.tile(np.expand_dims(diag2, 1), n)
mat2 = mat2.transpose()
distmat = mat1 + mat2 - 2 * kernelmat
distmat = np.sqrt(np.abs(distmat))
return distmat
@classmethod
def get_test_params(cls, parameter_set="default"):
"""Return testing parameter settings for the estimator.
Parameters
----------
parameter_set : str, default="default"
Name of the set of test parameters to return, for use in tests. If no
special parameters are defined for a value, will return ``"default"`` set.
Returns
-------
params : dict or list of dict, default={}
Parameters to create testing instances of the class.
Each dict are parameters to construct an "interesting" test instance, i.e.,
``MyClass(**params)`` or ``MyClass(**params[i])`` creates a valid test
instance.
``create_test_instance`` uses the first (or only) dictionary in ``params``.
"""
from sktime.dists_kernels import DtwDist, EditDist
params1 = {"kernel": DtwDist()}
params2 = {"kernel": EditDist()}
return [params1, params2]