/
_interval_pipelines.py
489 lines (428 loc) · 18.3 KB
/
_interval_pipelines.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
"""Interval Pipeline Classifiers.
Pipeline classifiers which extract interval features then build a base estimator.
"""
__maintainer__ = []
__all__ = ["RandomIntervalClassifier", "SupervisedIntervalClassifier"]
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from aeon.base._base import _clone_estimator
from aeon.classification.base import BaseClassifier
from aeon.transformations.collection.interval_based import (
RandomIntervals,
SupervisedIntervals,
)
class RandomIntervalClassifier(BaseClassifier):
"""
Random Interval Classifier.
Extracts multiple intervals with random length, position and dimension from series
and concatenates them into a feature vector. Builds an estimator on the
transformed data.
Parameters
----------
n_intervals : int, default=100,
The number of intervals of random length, position and dimension to be
extracted.
min_interval_length : int, default=3
The minimum length of extracted intervals. Minimum value of 3.
max_interval_length : int, default=3
The maximum length of extracted intervals. Minimum value of min_interval_length.
features : aeon transformer, a function taking a 2d numpy array parameter, or list
of said transformers and functions, default=None
Transformers and functions used to extract features from selected intervals.
If None, defaults to [mean, median, min, max, std, 25% quantile, 75% quantile]
dilation : int, list or None, default=None
Add dilation to extracted intervals. No dilation is added if None or 1. If a
list of ints, a random dilation value is selected from the list for each
interval.
The dilation value is selected after the interval star and end points. If the
number of values in the dilated interval is less than the min_interval_length,
the amount of dilation applied is reduced.
estimator : sklearn classifier, optional, default=None
An sklearn estimator to be built using the transformed data.
Defaults to sklearn RandomForestClassifier(n_estimators=200)
random_state : None, int or instance of RandomState, default=None
Seed or RandomState object used for random number generation.
If random_state is None, use the RandomState singleton used by np.random.
If random_state is an int, use a new RandomState instance seeded with seed.
n_jobs : int, default=1
The number of jobs to run in parallel for both `fit` and `transform` functions.
`-1` means using all processors.
parallel_backend : str, ParallelBackendBase instance or None, default=None
Specify the parallelisation backend implementation in joblib, if None a 'prefer'
value of "threads" is used by default.
Valid options are "loky", "multiprocessing", "threading" or a custom backend.
See the joblib Parallel documentation for more details.
Attributes
----------
n_cases_ : int
The number of train cases.
n_channels_ : int
The number of dimensions per case.
n_timepoints_ : int
The length of each series.
n_classes_ : int
Number of classes. Extracted from the data.
classes_ : ndarray of shape (n_classes)
Holds the label for each class.
See Also
--------
RandomIntervals
Examples
--------
>>> from aeon.classification.interval_based import RandomIntervalClassifier
>>> from sklearn.ensemble import RandomForestClassifier
>>> from aeon.testing.utils.data_gen import make_example_3d_numpy
>>> X, y = make_example_3d_numpy(n_cases=10, n_channels=1, n_timepoints=12,
... return_y=True, random_state=0)
>>> clf = RandomIntervalClassifier(
... estimator=RandomForestClassifier(n_estimators=5),
... n_intervals=5,
... random_state=0,
... )
>>> clf.fit(X, y)
RandomIntervalClassifier(...)
>>> clf.predict(X)
array([0, 1, 0, 1, 0, 0, 0, 1, 1, 0])
"""
_tags = {
"capability:multivariate": True,
"capability:multithreading": True,
"algorithm_type": "interval",
}
def __init__(
self,
n_intervals=100,
min_interval_length=3,
max_interval_length=np.inf,
features=None,
dilation=None,
estimator=None,
n_jobs=1,
random_state=None,
parallel_backend=None,
):
self.n_intervals = n_intervals
self.min_interval_length = min_interval_length
self.max_interval_length = max_interval_length
self.features = features
self.dilation = dilation
self.estimator = estimator
self.random_state = random_state
self.n_jobs = n_jobs
self.parallel_backend = parallel_backend
super().__init__()
def _fit(self, X, y):
"""Fit RandomIntervalClassifier to training data.
Parameters
----------
X : 3D np.ndarray (any number of channels, equal length series)
of shape (n_cases, n_channels, n_timepoints)
y : 1D np.array, of shape [n_cases] - class labels for fitting
indices correspond to instance indices in X
Returns
-------
self :
Reference to self.
"""
self.n_cases_, self.n_channels_, self.n_timepoints_ = X.shape
self._transformer = RandomIntervals(
n_intervals=self.n_intervals,
min_interval_length=self.min_interval_length,
max_interval_length=self.max_interval_length,
features=self.features,
dilation=self.dilation,
random_state=self.random_state,
n_jobs=self._n_jobs,
parallel_backend=self.parallel_backend,
)
self._estimator = _clone_estimator(
(
RandomForestClassifier(n_estimators=200)
if self.estimator is None
else self.estimator
),
self.random_state,
)
m = getattr(self._estimator, "n_jobs", None)
if m is not None:
self._estimator.n_jobs = self._n_jobs
X_t = self._transformer.fit_transform(X, y)
self._estimator.fit(X_t, y)
return self
def _predict(self, X) -> np.ndarray:
"""Predicts labels for sequences in X.
Parameters
----------
X : 3D np.ndarray (any number of channels, equal length series)
of shape (n_cases, n_channels, n_timepoints)
Returns
-------
y : array-like, shape = [n_cases]
Predicted class labels.
"""
return self._estimator.predict(self._transformer.transform(X))
def _predict_proba(self, X) -> np.ndarray:
"""Predicts labels probabilities for sequences in X.
Parameters
----------
X : 3D np.ndarray (any number of channels, equal length series)
of shape (n_cases, n_channels, n_timepoints)
Returns
-------
y : array-like, shape = [n_cases, n_classes_]
Predicted probabilities using the ordering in classes_.
"""
m = getattr(self._estimator, "predict_proba", None)
if callable(m):
return self._estimator.predict_proba(self._transformer.transform(X))
else:
dists = np.zeros((X.shape[0], self.n_classes_))
preds = self._estimator.predict(self._transformer.transform(X))
for i in range(0, X.shape[0]):
dists[i, self._class_dictionary[preds[i]]] = 1
return dists
@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.
RandomIntervalClassifier provides the following special sets:
"results_comparison" - used in some classifiers to compare against
previously generated results where the default set of parameters
cannot produce suitable probability estimates
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 aeon.utils.numba.stats import row_mean, row_numba_min
if parameter_set == "results_comparison":
return {
"n_intervals": 3,
"estimator": RandomForestClassifier(n_estimators=10),
"features": [row_mean, row_numba_min],
}
else:
return {
"n_intervals": 2,
"estimator": RandomForestClassifier(n_estimators=2),
"features": [row_mean, row_numba_min],
}
class SupervisedIntervalClassifier(BaseClassifier):
"""Supervised Interval Classifier.
Extracts multiple intervals from series with using a supervised process
and concatenates them into a feature vector. Builds an estimator on the
transformed data.
Parameters
----------
n_intervals : int, default=50
The number of times the supervised interval selection process is run. This
process will extract more then one interval per run.
Each supervised extraction will output a varying amount of features based on
series length, number of dimensions and the number of features.
min_interval_length : int, default=3
The minimum length of extracted intervals. Minimum value of 3.
features : callable, list of callables, default=None
Functions used to extract features from selected intervals. Must take a 2d
array of shape (n_cases, interval_length) and return a 1d array of shape
(n_cases) containing the features.
If None, defaults to the following statistics used in [2]:
[mean, median, std, slope, min, max, iqr, count_mean_crossing,
count_above_mean].
metric : ["fisher"] or callable, default="fisher"
The metric used to evaluate the usefulness of a feature extracted on an
interval. If "fisher", the Fisher score is used. If a callable, it must take
a 1d array of shape (n_cases) and return a 1d array of scores of shape
(n_cases).
randomised_split_point : bool, default=True
If True, the split point for interval extraction is randomised as is done in [2]
rather than split in half.
normalise_for_search : bool, default=True
If True, the data is normalised for the supervised interval search process.
Features extracted for the transform output will not use normalised data.
estimator : sklearn classifier, optional, default=None
An sklearn estimator to be built using the transformed data.
Defaults to sklearn RandomForestClassifier(n_estimators=200)
random_state : None, int or instance of RandomState, default=None
Seed or RandomState object used for random number generation.
If random_state is None, use the RandomState singleton used by np.random.
If random_state is an int, use a new RandomState instance seeded with seed.
n_jobs : int, default=1
The number of jobs to run in parallel for both `fit` and `transform` functions.
`-1` means using all processors.
parallel_backend : str, ParallelBackendBase instance or None, default=None
Specify the parallelisation backend implementation in joblib, if None a 'prefer'
value of "threads" is used by default.
Valid options are "loky", "multiprocessing", "threading" or a custom backend.
See the joblib Parallel documentation for more details.
Attributes
----------
n_cases_ : int
The number of train cases.
n_channels_ : int
The number of dimensions per case.
n_timepoints_ : int
The length of each series.
n_classes_ : int
Number of classes. Extracted from the data.
classes_ : ndarray of shape (n_classes)
Holds the label for each class.
See Also
--------
SupervisedIntervals
Examples
--------
>>> from aeon.classification.interval_based import SupervisedIntervalClassifier
>>> from sklearn.ensemble import RandomForestClassifier
>>> from aeon.testing.utils.data_gen import make_example_3d_numpy
>>> X, y = make_example_3d_numpy(n_cases=10, n_channels=1, n_timepoints=12,
... return_y=True, random_state=0)
>>> clf = SupervisedIntervalClassifier(
... estimator=RandomForestClassifier(n_estimators=5),
... n_intervals=2,
... random_state=0,
... )
>>> clf.fit(X, y)
SupervisedIntervalClassifier(...)
>>> clf.predict(X)
array([0, 1, 0, 1, 0, 0, 1, 1, 1, 0])
"""
_tags = {
"capability:multivariate": True,
"capability:multithreading": True,
"algorithm_type": "interval",
}
def __init__(
self,
n_intervals=50,
min_interval_length=3,
features=None,
metric="fisher",
randomised_split_point=True,
normalise_for_search=True,
estimator=None,
random_state=None,
n_jobs=1,
parallel_backend=None,
):
self.n_intervals = n_intervals
self.min_interval_length = min_interval_length
self.features = features
self.metric = metric
self.randomised_split_point = randomised_split_point
self.normalise_for_search = normalise_for_search
self.estimator = estimator
self.random_state = random_state
self.n_jobs = n_jobs
self.parallel_backend = parallel_backend
super().__init__()
def _fit(self, X, y):
"""Fit SupervisedIntervalClassifier to training data.
Parameters
----------
X : 3D np.ndarray (any number of channels, equal length series)
of shape (n_cases, n_channels, n_timepoints)
y : 1D np.array, of shape [n_cases] - class labels for fitting
indices correspond to instance indices in X
Returns
-------
self :
Reference to self.
"""
self.n_cases_, self.n_channels_, self.n_timepoints_ = X.shape
self._transformer = SupervisedIntervals(
n_intervals=self.n_intervals,
min_interval_length=self.min_interval_length,
features=self.features,
metric=self.metric,
randomised_split_point=self.randomised_split_point,
normalise_for_search=self.normalise_for_search,
random_state=self.random_state,
n_jobs=self.n_jobs,
parallel_backend=self.parallel_backend,
)
self._estimator = _clone_estimator(
(
RandomForestClassifier(n_estimators=200)
if self.estimator is None
else self.estimator
),
self.random_state,
)
m = getattr(self._estimator, "n_jobs", None)
if m is not None:
self._estimator.n_jobs = self._n_jobs
X_t = self._transformer.fit_transform(X, y)
self._estimator.fit(X_t, y)
return self
def _predict(self, X) -> np.ndarray:
"""Predicts labels for sequences in X.
Parameters
----------
X : 3D np.ndarray (any number of channels, equal length series)
of shape (n_cases, n_channels, n_timepoints)
Returns
-------
y : array-like, shape = [n_cases]
Predicted class labels.
"""
return self._estimator.predict(self._transformer.transform(X))
def _predict_proba(self, X) -> np.ndarray:
"""Predicts labels probabilities for sequences in X.
Parameters
----------
X : 3D np.ndarray (any number of channels, equal length series)
of shape (n_cases, n_channels, n_timepoints)
Returns
-------
y : array-like, shape = [n_cases, n_classes_]
Predicted probabilities using the ordering in classes_.
"""
m = getattr(self._estimator, "predict_proba", None)
if callable(m):
return self._estimator.predict_proba(self._transformer.transform(X))
else:
dists = np.zeros((X.shape[0], self.n_classes_))
preds = self._estimator.predict(self._transformer.transform(X))
for i in range(0, X.shape[0]):
dists[i, self._class_dictionary[preds[i]]] = 1
return dists
@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.
SupervisedIntervalClassifier provides the following special sets:
"results_comparison" - used in some classifiers to compare against
previously generated results where the default set of parameters
cannot produce suitable probability estimates
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 aeon.utils.numba.stats import row_mean, row_numba_min
if parameter_set == "results_comparison":
return {
"n_intervals": 2,
"estimator": RandomForestClassifier(n_estimators=10),
"features": [row_mean, row_numba_min],
}
else:
return {
"n_intervals": 1,
"estimator": RandomForestClassifier(n_estimators=2),
"features": [row_mean, row_numba_min],
}