-
Notifications
You must be signed in to change notification settings - Fork 89
/
base.py
234 lines (197 loc) · 8.37 KB
/
base.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
"""Base class for clustering."""
__author__ = ["chrisholder", "TonyBagnall"]
__all__ = ["BaseClusterer"]
import time
from abc import ABC, abstractmethod
from typing import final
import numpy as np
from aeon.base import BaseCollectionEstimator
from aeon.utils.validation._dependencies import _check_estimator_deps
class BaseClusterer(BaseCollectionEstimator, ABC):
"""Abstract base class for time series clusterers.
Parameters
----------
n_clusters : int, default=None
Number of clusters for model.
"""
def __init__(self, n_clusters: int = None):
self.n_clusters = n_clusters
# required for compatibility with some sklearn interfaces e.g.
# CalibratedClassifierCV
self._estimator_type = "clusterer"
super().__init__()
_check_estimator_deps(self)
@final
def fit(self, X, y=None) -> BaseCollectionEstimator:
"""Fit time series clusterer to training data.
Parameters
----------
X : 3D np.ndarray (any number of channels, equal length series)
of shape (n_instances, n_channels, n_timepoints)
or 2D np.array (univariate, equal length series)
of shape (n_instances, n_timepoints)
or list of numpy arrays (any number of channels, unequal length series)
of shape [n_instances], 2D np.array (n_channels, n_timepoints_i), where
n_timepoints_i is length of series i
other types are allowed and converted into one of the above.
y: ignored, exists for API consistency reasons.
Returns
-------
self:
Fitted estimator.
"""
self.reset()
_start_time = int(round(time.time() * 1000))
X = self._preprocess_collection(X)
self._fit(X)
self.fit_time_ = int(round(time.time() * 1000)) - _start_time
self._is_fitted = True
return self
@final
def predict(self, X, y=None) -> np.ndarray:
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : 3D np.ndarray
Input data, any number of channels, equal length series of shape ``(
n_instances, n_channels, n_timepoints)``
or 2D np.array (univariate, equal length series) of shape
``(n_instances, n_timepoints)``
or list of numpy arrays (any number of channels, unequal length series)
of shape ``[n_instances]``, 2D np.array ``(n_channels, n_timepoints_i)``,
where ``n_timepoints_i`` is length of series ``i``. Other types are
allowed and converted into one of the above.
y: ignored, exists for API consistency reasons.
Returns
-------
np.array
shape ``(n_instances)`, index of the cluster each time series in X.
belongs to.
"""
self.check_is_fitted()
X = self._preprocess_collection(X)
return self._predict(X)
def fit_predict(self, X, y=None) -> np.ndarray:
"""Compute cluster centers and predict cluster index for each time series.
Convenience method; equivalent of calling fit(X) followed by predict(X)
Parameters
----------
X : np.ndarray (2d or 3d array of shape (n_instances, series_length) or shape
(n_instances, n_channels, series_length)).
Time series instances to train clusterer and then have indexes each belong
to return.
y: ignored, exists for API consistency reasons.
Returns
-------
np.ndarray (1d array of shape (n_instances,))
Index of the cluster each time series in X belongs to.
"""
self.fit(X)
return self.predict(X)
@final
def predict_proba(self, X) -> np.ndarray:
"""Predicts labels probabilities for sequences in X.
Default behaviour is to call _predict and set the predicted class probability
to 1, other class probabilities to 0. Override if better estimates are
obtainable.
Parameters
----------
X : 3D np.ndarray
Input data, any number of channels, equal length series of shape ``(
n_instances, n_channels, n_timepoints)``
or 2D np.array (univariate, equal length series) of shape
``(n_instances, n_timepoints)``
or list of numpy arrays (any number of channels, unequal length series)
of shape ``[n_instances]``, 2D np.array ``(n_channels, n_timepoints_i)``,
where ``n_timepoints_i`` is length of series ``i``. Other types are
allowed and converted into one of the above.
Returns
-------
y : 2D array of shape [n_instances, n_classes] - predicted class probabilities
1st dimension indices correspond to instance indices in X
2nd dimension indices correspond to possible labels (integers)
(i, j)-th entry is predictive probability that i-th instance is of class j
"""
self.check_is_fitted()
X = self._preprocess_collection(X)
return self._predict_proba(X)
def score(self, X, y=None) -> float:
"""Score the quality of the clusterer.
Parameters
----------
X : np.ndarray (2d or 3d array of shape (n_instances, series_length) or shape
(n_instances, n_channels, series_length)).
Time series instances to train clusterer and then have indexes each belong
to return.
y: ignored, exists for API consistency reasons.
Returns
-------
score : float
Score of the clusterer.
"""
self.check_is_fitted()
X = self._preprocess_collection(X)
return self._score(X, y)
def _predict_proba(self, X) -> np.ndarray:
"""Predicts labels probabilities for sequences in X.
Default behaviour is to call _predict and set the predicted class probability
to 1, other class probabilities to 0. Override if better estimates are
obtainable.
Parameters
----------
X : 3D np.ndarray
Input data, any number of channels, equal length series of shape ``(
n_instances, n_channels, n_timepoints)``
or 2D np.array (univariate, equal length series) of shape
``(n_instances, n_timepoints)``
or list of numpy arrays (any number of channels, unequal length series)
of shape ``[n_instances]``, 2D np.array ``(n_channels, n_timepoints_i)``,
where ``n_timepoints_i`` is length of series ``i``. Other types are
allowed and converted into one of the above.
Returns
-------
y : 2D array of shape [n_instances, n_classes] - predicted class probabilities
1st dimension indices correspond to instance indices in X
2nd dimension indices correspond to possible labels (integers)
(i, j)-th entry is predictive probability that i-th instance is of class j
"""
preds = self._predict(X)
n_instances = len(preds)
n_clusters = self.n_clusters
if n_clusters is None:
n_clusters = int(max(preds)) + 1
dists = np.zeros((X.shape[0], n_clusters))
for i in range(n_instances):
dists[i, preds[i]] = 1
return dists
@abstractmethod
def _score(self, X, y=None): ...
@abstractmethod
def _predict(self, X, y=None) -> np.ndarray:
"""Predict the closest cluster each sample in X belongs to.
Parameters
----------
X : np.ndarray (2d or 3d array of shape (n_instances, series_length) or shape
(n_instances,n_channels,series_length)).
Time series instances to predict their cluster indexes.
y: ignored, exists for API consistency reasons.
Returns
-------
np.ndarray (1d array of shape (n_instances,))
Index of the cluster each time series in X belongs to.
"""
...
@abstractmethod
def _fit(self, X, y=None):
"""Fit time series clusterer to training data.
Parameters
----------
X : np.ndarray (2d or 3d array of shape (n_instances, series_length) or shape
(n_instances,n_channels,series_length)).
Training time series instances to cluster.
Returns
-------
self:
Fitted estimator.
"""
...