-
Notifications
You must be signed in to change notification settings - Fork 89
/
base.py
577 lines (489 loc) · 24.3 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
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
"""
Abstract base class for early time series classifiers.
class name: BaseEarlyClassifier
Defining methods:
fitting - fit(self, X, y)
predicting - predict(self, X)
- predict_proba(self, X)
updating predictions - update_predict(self, X)
(streaming) - update_predict_proba(self, X)
Inherited inspection methods:
hyper-parameter inspection - get_params()
fitted parameter inspection - get_fitted_params()
State:
fitted model/strategy - by convention, any attributes ending in "_"
fitted state flag - is_fitted (property)
fitted state inspection - check_is_fitted()
streaming decision info - state_info attribute
"""
__all__ = [
"BaseEarlyClassifier",
]
__author__ = ["mloning", "fkiraly", "TonyBagnall", "MatthewMiddlehurst"]
import time
from abc import ABC, abstractmethod
from typing import Tuple
import numpy as np
from aeon.base import BaseCollectionEstimator
from aeon.classification import BaseClassifier
class BaseEarlyClassifier(BaseCollectionEstimator, ABC):
"""
Abstract base class for early time series classifiers.
The base classifier specifies the methods and method signatures that all
early classifiers have to implement. Attributes with an underscore suffix are set in
the method fit.
Parameters
----------
classes_ : np.ndarray
Class labels, possibly strings.
n_classes_ : int
Number of classes (length of classes_).
fit_time_ : int
Time (in milliseconds) for fit to run.
_class_dictionary : dict
dictionary mapping classes_ onto integers 0...n_classes_-1.
_n_jobs : int, default=1
Number of threads to use in fit as determined by n_jobs.
state_info : array-like, default=None
An array containing the state info for each decision in X.
"""
_tags = {
"X_inner_type": "numpy3D",
"capability:multivariate": False,
"capability:unequal_length": False,
"capability:missing_values": False,
"capability:multithreading": False,
}
def __init__(self):
self.classes_ = []
self.n_classes_ = 0
self.fit_time_ = 0
self._class_dictionary = {}
self._n_jobs = 1
"""
An array containing the state info for each decision in X from update and
predict methods. Contains classifier dependant information for future decisions
on the data and information on when a cases decision has been made. Each row
contains information for a case from the latest decision on its safety made in
update/predict. Successive updates are likely to remove rows from the
state_info, as it will only store as many rows as there are input instances to
update/predict.
"""
self.state_info = None
super(BaseEarlyClassifier, self).__init__()
def fit(self, X, y):
"""Fit time series classifier to training data.
Parameters
----------
X : 3D np.array
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.
np.array
shape ``(n_instances)`` - class labels for fitting indices correspond to
instance indices in X.
Returns
-------
self : Reference to self.
Notes
-----
Changes state by creating a fitted model that updates attributes
ending in "_" and sets is_fitted flag to True.
"""
# reset estimator at the start of fit
self.reset()
# All of this can move up to BaseCollection
start = int(round(time.time() * 1000))
X = self._preprocess_collection(X)
y = BaseClassifier._check_y(self, y, self.metadata_["n_cases"])
self._fit(X, y)
self.fit_time_ = int(round(time.time() * 1000)) - start
# this should happen last
self._is_fitted = True
return self
def predict(self, X) -> Tuple[np.ndarray, np.ndarray]:
"""Predicts labels for sequences in X.
Early classifiers can predict at series lengths shorter than the train data
series length.
Predict will return -1 for cases which it cannot make a decision on yet. The
output is only guaranteed to return a valid class label for all cases when
using the full series length.
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 : np.array
shape ``[n_instances]`` - predicted class labels indices correspond to
instance indices in X.
decisions : 1D bool array
An array of booleans, containing the decision of whether a prediction is
safe to use or not.
i-th entry is the classifier decision that i-th instance safe to use.
"""
self.check_is_fitted()
X = self._preprocess_collection(X)
return self._predict(X)
def update_predict(self, X) -> Tuple[np.ndarray, np.ndarray]:
"""Update label prediction for sequences in X at a larger series length.
Uses information stored in the classifiers state from previous predictions and
updates at shorter series lengths. Update will only accept cases which have not
yet had a decision made, cases which have had a positive decision should be
removed from the input with the row ordering preserved.
If no state information is present, predict will be called instead.
Prediction updates will return -1 for cases which it cannot make a decision on
yet. The output is only guaranteed to return a valid class label for all cases
when using the full series length.
Parameters
----------
X : 3D np.array
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 : 1D np.array of int, of shape [n_cases] - predicted class labels
indices correspond to instance indices in X
decisions : 1D bool array
An array of booleans, containing the decision of whether a prediction is
safe to use or not.
i-th entry is the classifier decision that i-th instance safe to use
"""
self.check_is_fitted()
# boilerplate input checks for predict-like methods
X = self._preprocess_collection(X)
if self.state_info is None:
return self._predict(X)
else:
return self._update_predict(X)
def predict_proba(self, X) -> Tuple[np.ndarray, np.ndarray]:
"""Predicts labels probabilities for sequences in X.
Early classifiers can predict at series lengths shorter than the train data
series length.
Probability predictions will return [-1]*n_classes_ for cases which it cannot
make a decision on yet. The output is only guaranteed to return a valid class
label for all cases when using the full series length.
Parameters
----------
X : 3D np.array
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_cases, 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
decisions : 1D bool array
An array of booleans, containing the decision of whether a prediction is
safe to use or not.
i-th entry is the classifier decision that i-th instance safe to use
"""
self.check_is_fitted()
X = self._preprocess_collection(X)
return self._predict_proba(X)
def update_predict_proba(self, X) -> Tuple[np.ndarray, np.ndarray]:
"""Update label probabilities for sequences in X at a larger series length.
Uses information stored in the classifiers state from previous predictions and
updates at shorter series lengths. Update will only accept cases which have not
yet had a decision made, cases which have had a positive decision should be
removed from the input with the row ordering preserved.
If no state information is present, predict_proba will be called instead.
Probability predictions updates will return [-1]*n_classes_ for cases which it
cannot make a decision on yet. The output is only guaranteed to return a valid
class label for all cases when using the full series length.
Parameters
----------
X : 3D np.array
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_cases, 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
decisions : 1D bool array
An array of booleans, containing the decision of whether a prediction is
safe to use or not.
i-th entry is the classifier decision that i-th instance safe to use
"""
self.check_is_fitted()
X = self._preprocess_collection(X)
if self.state_info is None:
return self._predict_proba(X)
else:
return self._update_predict_proba(X)
def score(self, X, y) -> Tuple[float, float, float]:
"""Scores predicted labels against ground truth labels on X.
Parameters
----------
X : 3D np.array
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 : 1D np.ndarray of int, of shape [n_cases] - class labels (ground truth)
indices correspond to instance indices in X
Returns
-------
Tuple of floats, harmonic mean, accuracy and earliness scores of predict(X) vs y
"""
self.check_is_fitted()
X = self._preprocess_collection(X)
return self._score(X, y)
def get_state_info(self):
"""Return the state information generated from the last predict/update call.
Returns
-------
An array containing the state info for each decision in X from update and
predict methods. Contains classifier dependant information for future decisions
on the data and information on when a cases decision has been made. Each row
contains information for a case from the latest decision on its safety made in
update/predict. Successive updates are likely to remove rows from the
state_info, as it will only store as many rows as there are input instances to
update/predict.
"""
return self.state_info
def reset_state_info(self):
"""Reset the state information used in update methods."""
self.state_info = None
@staticmethod
def filter_X(X, decisions):
"""Remove True cases from X given a boolean array of decisions."""
inv_dec = np.invert(decisions)
return X[inv_dec]
@staticmethod
def filter_X_y(X, y, decisions):
"""Remove True cases from X and y given a boolean array of decisions."""
inv_dec = np.invert(decisions)
return X[inv_dec], y[inv_dec]
@staticmethod
def split_indices(indices, decisions):
"""Split a list of indices given a boolean array of decisions."""
inv_dec = np.invert(decisions)
return indices[inv_dec], indices[decisions]
@staticmethod
def split_indices_and_filter(X, indices, decisions):
"""Remove True cases and split a list of indices given an array of decisions."""
inv_dec = np.invert(decisions)
return X[inv_dec], indices[inv_dec], indices[decisions]
@abstractmethod
def _fit(self, X, y):
"""Fit time series classifier to training data.
Abstract method, must be implemented.
Parameters
----------
X : 3D np.array
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 : 1D np.array of int, of shape [n_cases] - class labels for fitting
indices correspond to instance indices in X
Returns
-------
self :
Reference to self.
Notes
-----
Changes state by creating a fitted model that updates attributes
ending in "_" and sets is_fitted flag to True.
"""
...
@abstractmethod
def _predict(self, X) -> Tuple[np.ndarray, np.ndarray]:
"""Predicts labels for sequences in X.
Abstract method, must be implemented.
This method should update state_info with any values necessary to make future
decisions. It is recommended that the previous time stamp used for each case
should be stored in the state_info. The number of rows in state_info after the
method has been called should match the number of input rows.
Parameters
----------
X : 3D np.array
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 : 1D np.array of int, of shape [n_cases] - predicted class labels
indices correspond to instance indices in X
decisions : 1D bool array
An array of booleans, containing the decision of whether a prediction is
safe to use or not.
i-th entry is the classifier decision that i-th instance safe to use
"""
...
@abstractmethod
def _update_predict(self, X) -> Tuple[np.ndarray, np.ndarray]:
"""Update label prediction for sequences in X at a larger series length.
Abstract method, must be implemented.
Uses information from previous decisions stored in state_info. This method
should update state_info with any values necessary to make future decisions.
It is recommended that the previous time stamp used for each case should be
stored in the state_info. The number of rows in state_info after the method has
been called should match the number of input rows.
Parameters
----------
X : 3D np.array
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 : 1D np.array of int, of shape [n_cases] - predicted class labels
indices correspond to instance indices in X
decisions : 1D bool array
An array of booleans, containing the decision of whether a prediction is
safe to use or not.
i-th entry is the classifier decision that i-th instance safe to use
"""
...
def _predict_proba(self, X) -> Tuple[np.ndarray, np.ndarray]:
"""Predicts labels probabilities for sequences in X.
This method should update state_info with any values necessary to make future
decisions. It is recommended that the previous time stamp used for each case
should be stored in the state_info. The number of rows in state_info after the
method has been called should match the number of input rows.
Default behaviour is to call _predict and set the predicted class probability
to 1, other class probabilities to 0 if a positive decision is made. Override if
better estimates are obtainable.
Parameters
----------
X : 3D np.array
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_cases, 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
decisions : 1D bool array
An array of booleans, containing the decision of whether a prediction is
safe to use or not.
i-th entry is the classifier decision that i-th instance safe to use
"""
dists = np.zeros((X.shape[0], self.n_classes_))
preds, decisions = self._predict(X)
for i in range(0, X.shape[0]):
if decisions[i]:
dists[i, self._class_dictionary[preds[i]]] = 1
else:
dists[i, :] = -1
return dists, decisions
def _update_predict_proba(self, X) -> Tuple[np.ndarray, np.ndarray]:
"""Update label probabilities for sequences in X at a larger series length.
Uses information from previous decisions stored in state_info. This method
should update state_info with any values necessary to make future decisions.
It is recommended that the previous time stamp used for each case should be
stored in the state_info. The number of rows in state_info after the method has
been called should match the number of input rows.
Default behaviour is to call _update_predict and set the predicted class
probability to 1, other class probabilities to 0 if a positive decision is made.
Override if better estimates are obtainable.
Parameters
----------
X : 3D np.array
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_cases, 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
decisions : 1D bool array
An array of booleans, containing the decision of whether a prediction is
safe to use or not.
i-th entry is the classifier decision that i-th instance safe to use
"""
dists = np.zeros((X.shape[0], self.n_classes_))
preds, decisions = self._update_predict(X)
for i in range(0, X.shape[0]):
if decisions[i]:
dists[i, self._class_dictionary[preds[i]]] = 1
else:
dists[i, :] = -1
return dists, decisions
@abstractmethod
def _score(self, X, y) -> Tuple[float, float, float]:
"""Scores predicted labels against ground truth labels on X.
Abstract method, must be implemented.
Parameters
----------
X : 3D np.array
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 : 1D np.array of int, of shape [n_cases] - class labels for fitting
indices correspond to instance indices in X
Returns
-------
Tuple of floats, harmonic mean, accuracy and earliness scores of predict(X) vs y
"""
...