-
Notifications
You must be signed in to change notification settings - Fork 89
/
_inception_time.py
698 lines (619 loc) · 26.3 KB
/
_inception_time.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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
"""InceptionTime regressor."""
__author__ = ["hadifawaz1999"]
__all__ = ["InceptionTimeRegressor"]
import gc
import os
import time
from copy import deepcopy
import numpy as np
from sklearn.utils import check_random_state
from aeon.networks import InceptionNetwork
from aeon.regression.base import BaseRegressor
from aeon.regression.deep_learning.base import BaseDeepRegressor
class InceptionTimeRegressor(BaseRegressor):
"""InceptionTime ensemble regressor.
Ensemble of IndividualInceptionRegressor, as described in [1]_.
This ensemble regressor is adapted from the classier InceptionTime
Parameters
----------
n_regressors : int, default = 5,
the number of Inception models used for the
Ensemble in order to create
InceptionTime.
depth : int, default = 6,
the number of inception modules used
nb_filters : int or list of int32, default = 32,
the number of filters used in one inception
module, if not a list,
the same number of filters is used in
all inception modules
nb_conv_per_layer : int or list of int, default = 3,
the number of convolution layers in each inception
module, if not a list,
the same number of convolution layers is used
in all inception modules
kernel_size : int or list of int, default = 40,
the head kernel size used for each inception
module, if not a list,
the same is used in all inception modules
use_max_pooling : bool or list of bool, default = True,
conditioning whether or not to use max pooling layer
in inception modules,if not a list,
the same is used in all inception modules
max_pool_size : int or list of int, default = 3,
the size of the max pooling layer, if not a list,
the same is used in all inception modules
strides : int or list of int, default = 1,
the strides of kernels in convolution layers for each
inception module, if not a list,
the same is used in all inception modules
dilation_rate : int or list of int, default = 1,
the dilation rate of convolutions in each inception
module, if not a list,
the same is used in all inception modules
padding : str or list of str, default = "same",
the type of padding used for convoltuon for each
inception module, if not a list,
the same is used in all inception modules
activation : str or list of str, default = "relu",
the activation function used in each inception
module, if not a list,
the same is used in all inception modules
use_bias : bool or list of bool, default = False,
condition whether or not convolutions should
use bias values in each inception
module, if not a list,
the same is used in all inception modules
use_residual : bool, default = True,
condition whether or not to use residual
connections all over Inception
use_bottleneck : bool, default = True,
condition whether or not to use bottlenecks
all over Inception
bottleneck_size : int, default = 32,
the bottleneck size in case use_bottleneck = True
use_custom_filters : bool, default = False,
condition on whether or not to use custom
filters in the first inception module
output_activation : str, default = "linear",
the output activation for the regressor
batch_size : int, default = 64
the number of samples per gradient update.
use_mini_batch_size : bool, default = False
condition on using the mini batch size
formula Wang et al.
n_epochs : int, default = 1500
the number of epochs to train the model.
callbacks : callable or None, default
ReduceOnPlateau and ModelCheckpoint
list of tf.keras.callbacks.Callback objects.
file_path : str, default = './'
file_path when saving model_Checkpoint callback
save_best_model : bool, default = False
Whether or not to save the best model, if the
modelcheckpoint callback is used by default,
this condition, if True, will prevent the
automatic deletion of the best saved model from
file and the user can choose the file name
save_last_model : bool, default = False
Whether or not to save the last model, last
epoch trained, using the base class method
save_last_model_to_file
best_file_name : str, default = "best_model"
The name of the file of the best model, if
save_best_model is set to False, this parameter
is discarded
last_file_name : str, default = "last_model"
The name of the file of the last model, if
save_last_model is set to False, this parameter
is discarded
random_state : int, default = 0
seed to any needed random actions.
verbose : boolean, default = False
whether to output extra information
optimizer : keras optimizer, default = Adam
loss : keras loss,
default = mean_squared_error
will be set to accuracy as default if None
Notes
-----
..[1] Fawaz et al. InceptionTime: Finding AlexNet for Time Series
regression, Data Mining and Knowledge Discovery, 34, 2020
..[2] Ismail-Fawaz et al. Deep Learning For Time Series
regression Using New
Hand-Crafted Convolution Filters, 2022 IEEE International
Conference on Big Data.
Adapted from the implementation from Fawaz et. al
https://github.com/hfawaz/InceptionTime/blob/master/regressors/inception.py
and Ismail-Fawaz et al.
https://github.com/MSD-IRIMAS/CF-4-TSC
Examples
--------
>>> from aeon.regression.deep_learning import InceptionTimeRegressor
>>> 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, regression_target=True,
... random_state=0)
>>> inctime = InceptionTimeRegressor(n_epochs=20,batch_size=4) # doctest: +SKIP
>>> inctime.fit(X, y) # doctest: +SKIP
InceptionTimeRegressor(...)
"""
_tags = {
"python_dependencies": "tensorflow",
"capability:multivariate": True,
"non-deterministic": True,
"cant-pickle": True,
"algorithm_type": "deeplearning",
}
def __init__(
self,
n_regressors=5,
nb_filters=32,
nb_conv_per_layer=3,
kernel_size=40,
use_max_pooling=True,
max_pool_size=3,
strides=1,
dilation_rate=1,
padding="same",
activation="relu",
use_bias=False,
use_residual=True,
use_bottleneck=True,
bottleneck_size=32,
depth=6,
use_custom_filters=False,
output_activation="linear",
file_path="./",
save_last_model=False,
save_best_model=False,
best_file_name="best_model",
last_file_name="last_model",
batch_size=64,
use_mini_batch_size=False,
n_epochs=1500,
callbacks=None,
random_state=None,
verbose=False,
loss="mse",
optimizer=None,
):
self.n_regressors = n_regressors
self.nb_filters = nb_filters
self.nb_conv_per_layer = nb_conv_per_layer
self.use_max_pooling = use_max_pooling
self.max_pool_size = max_pool_size
self.strides = strides
self.dilation_rate = dilation_rate
self.padding = padding
self.activation = activation
self.use_bias = use_bias
self.use_residual = use_residual
self.use_bottleneck = use_bottleneck
self.bottleneck_size = bottleneck_size
self.depth = depth
self.kernel_size = kernel_size
self.batch_size = batch_size
self.n_epochs = n_epochs
self.use_custom_filters = use_custom_filters
self.output_activation = output_activation
self.file_path = file_path
self.save_last_model = save_last_model
self.save_best_model = save_best_model
self.best_file_name = best_file_name
self.last_file_name = last_file_name
self.callbacks = callbacks
self.random_state = random_state
self.verbose = verbose
self.use_mini_batch_size = use_mini_batch_size
self.loss = loss
self.optimizer = optimizer
self.regressors_ = []
super().__init__()
def _fit(self, X, y):
"""Fit each of the Individual Inception models.
Parameters
----------
X : np.ndarray of shape (n_instances, n_channels, series_length)
The training input samples.
y : np.ndarray of shape n
The training data target values.
Returns
-------
self : object
fitted estimator
"""
self.regressors_ = []
rng = check_random_state(self.random_state)
for n in range(0, self.n_regressors):
rgs = IndividualInceptionRegressor(
nb_filters=self.nb_filters,
nb_conv_per_layer=self.nb_conv_per_layer,
kernel_size=self.kernel_size,
use_max_pooling=self.use_max_pooling,
max_pool_size=self.max_pool_size,
strides=self.strides,
dilation_rate=self.dilation_rate,
padding=self.padding,
activation=self.activation,
use_bias=self.use_bias,
use_residual=self.use_residual,
use_bottleneck=self.use_bottleneck,
depth=self.depth,
use_custom_filters=self.use_custom_filters,
output_activation=self.output_activation,
file_path=self.file_path,
save_best_model=self.save_best_model,
save_last_model=self.save_last_model,
best_file_name=self.best_file_name + str(n),
last_file_name=self.last_file_name + str(n),
batch_size=self.batch_size,
use_mini_batch_size=self.use_mini_batch_size,
n_epochs=self.n_epochs,
callbacks=self.callbacks,
loss=self.loss,
optimizer=self.optimizer,
random_state=rng.randint(0, np.iinfo(np.int32).max),
verbose=self.verbose,
)
rgs.fit(X, y)
self.regressors_.append(rgs)
gc.collect()
return self
def _predict(self, X) -> np.ndarray:
"""Predict the values of the test set using InceptionTime.
Parameters
----------
X : np.ndarray of shape (n_instances, n_channels, series_length)
The testing input samples.
Returns
-------
Y : np.ndarray of shape = (n_instances)
The predicted values
"""
ypreds = np.zeros(shape=(X.shape[0]))
for rgs in self.regressors_:
ypreds = ypreds + rgs._predict(X)
ypreds = ypreds / self.n_regressors
return ypreds
@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.
For regressors, a "default" set of parameters should be provided for
general testing, and a "results_comparison" set for comparing against
previously recorded results if the general set does not produce suitable
probabilities to compare against.
Returns
-------
params : dict or list of dict, default=[None]
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`.
"""
param1 = {
"n_regressors": 1,
"n_epochs": 10,
"batch_size": 4,
"kernel_size": 4,
"use_residual": False,
"depth": 1,
"use_custom_filters": False,
}
return [param1]
class IndividualInceptionRegressor(BaseDeepRegressor):
"""Single Inception regressor.
Parameters
----------
depth : int, default = 6,
the number of inception modules used
nb_filters : int or list of int32, default = 32,
the number of filters used in one inception module, if not a list,
the same number of filters is used in all inception modules
nb_conv_per_layer : int or list of int, default = 3,
the number of convolution layers in each inception module, if not a list,
the same number of convolution layers is used in all inception modules
kernel_size : int or list of int, default = 40,
the head kernel size used for each inception module, if not a list,
the same is used in all inception modules
use_max_pooling : bool or list of bool, default = True,
condition whether or not to use max pooling layer
in inception modules,if not a list,
the same is used in all inception modules
max_pool_size : int or list of int, default = 3,
the size of the max pooling layer, if not a list,
the same is used in all inception modules
strides : int or list of int, default = 1,
the strides of kernels in convolution layers for
each inception module, if not a list,
the same is used in all inception modules
dilation_rate : int or list of int, default = 1,
the dilation rate of convolutions in each inception module, if not a list,
the same is used in all inception modules
padding : str or list of str, default = "same",
the type of padding used for convoltuon for each
inception module, if not a list,
the same is used in all inception modules
activation : str or list of str, default = "relu",
the activation function used in each inception module, if not a list,
the same is used in all inception modules
use_bias : bool or list of bool, default = False,
condition whether or not convolutions should
use bias values in each inception
module, if not a list,
the same is used in all inception modules
use_residual : bool, default = True,
condition whether or not to use residual connections all over Inception
use_bottleneck : bool, default = True,
condition whether or not to use bottlesnecks all over Inception
bottleneck_size : int, default = 32,
the bottleneck size in case use_bottleneck = True
use_custom_filters : bool, default = False,
condition on whether or not to use custom filters
in the first inception module
output_activation : str, default = "linear",
the output activation of the regressor
batch_size : int, default = 64
the number of samples per gradient update.
use_mini_batch_size : bool, default = False
condition on using the mini batch size formula Wang et al.
n_epochs : int, default = 1500
the number of epochs to train the model.
callbacks : callable or None, default
ReduceOnPlateau and ModelCheckpoint
list of tf.keras.callbacks.Callback objects.
file_path : str, default = './'
file_path when saving model_Checkpoint callback
save_best_model : bool, default = False
Whether or not to save the best model, if the
modelcheckpoint callback is used by default,
this condition, if True, will prevent the
automatic deletion of the best saved model from
file and the user can choose the file name
save_last_model : bool, default = False
Whether or not to save the last model, last
epoch trained, using the base class method
save_last_model_to_file
best_file_name : str, default = "best_model"
The name of the file of the best model, if
save_best_model is set to False, this parameter
is discarded
last_file_name : str, default = "last_model"
The name of the file of the last model, if
save_last_model is set to False, this parameter
is discarded
random_state : int, default = 0
seed to any needed random actions.
verbose : boolean, default = False
whether to output extra information
optimizer : keras optimizer, default = Adam
loss : keras loss, default = mean_squared_error
to accuracy as default if None
Notes
-----
..[1] Fawaz et al. InceptionTime: Finding AlexNet for Time Series
regression, Data Mining and Knowledge Discovery, 34, 2020
..[2] Ismail-Fawaz et al. Deep Learning For Time Series regression Using New
Hand-Crafted Convolution Filters, 2022 IEEE International Conference on Big Data.
Adapted from the implementation from Fawaz et. al
https://github.com/hfawaz/InceptionTime/blob/master/regressors/inception.py
and Ismail-Fawaz et al.
https://github.com/MSD-IRIMAS/CF-4-TSC
Examples
--------
>>> from aeon.regression.deep_learning import IndividualInceptionRegressor
>>> 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, regression_target=True,
... random_state=0)
>>> inc = IndividualInceptionRegressor(n_epochs=20,batch_size=4) # doctest: +SKIP
>>> inc.fit(X, y) # doctest: +SKIP
IndividualInceptionRegressor(...)
"""
def __init__(
self,
nb_filters=32,
nb_conv_per_layer=3,
kernel_size=40,
use_max_pooling=True,
max_pool_size=3,
strides=1,
dilation_rate=1,
padding="same",
activation="relu",
use_bias=False,
use_residual=True,
use_bottleneck=True,
bottleneck_size=32,
depth=6,
use_custom_filters=False,
output_activation="linear",
file_path="./",
save_best_model=False,
save_last_model=False,
best_file_name="best_model",
last_file_name="last_model",
batch_size=64,
use_mini_batch_size=False,
n_epochs=1500,
callbacks=None,
random_state=None,
verbose=False,
loss="mse",
optimizer=None,
):
# predefined
self.nb_filters = nb_filters
self.nb_conv_per_layer = nb_conv_per_layer
self.use_max_pooling = use_max_pooling
self.max_pool_size = max_pool_size
self.strides = strides
self.dilation_rate = dilation_rate
self.padding = padding
self.activation = activation
self.use_bias = use_bias
self.use_residual = use_residual
self.use_bottleneck = use_bottleneck
self.bottleneck_size = bottleneck_size
self.depth = depth
self.kernel_size = kernel_size
self.n_epochs = n_epochs
self.use_custom_filters = use_custom_filters
self.output_activation = output_activation
self.file_path = file_path
self.save_best_model = save_best_model
self.save_last_model = save_last_model
self.best_file_name = best_file_name
self.callbacks = callbacks
self.random_state = random_state
self.verbose = verbose
self.use_mini_batch_size = use_mini_batch_size
self.loss = loss
self.optimizer = optimizer
super().__init__(batch_size=batch_size, last_file_name=last_file_name)
self._network = InceptionNetwork(
nb_filters=self.nb_filters,
nb_conv_per_layer=self.nb_conv_per_layer,
kernel_size=self.kernel_size,
use_max_pooling=self.use_max_pooling,
max_pool_size=self.max_pool_size,
strides=self.strides,
dilation_rate=self.dilation_rate,
padding=self.padding,
activation=self.activation,
use_bias=self.use_bias,
use_residual=self.use_residual,
use_bottleneck=self.use_bottleneck,
bottleneck_size=self.bottleneck_size,
depth=self.depth,
use_custom_filters=self.use_custom_filters,
random_state=self.random_state,
)
def build_model(self, input_shape, **kwargs):
"""
Construct a compiled, un-trained, keras model that is ready for training.
Parameters
----------
input_shape : tuple
The shape of the data fed into the input layer
Returns
-------
tf.keras.models.Model
A compiled Keras Model
"""
import tensorflow as tf
input_layer, output_layer = self._network.build_network(input_shape, **kwargs)
output_layer = tf.keras.layers.Dense(1, activation=self.output_activation)(
output_layer
)
model = tf.keras.models.Model(inputs=input_layer, outputs=output_layer)
tf.random.set_seed(self.random_state)
self.optimizer_ = (
tf.keras.optimizers.Adam() if self.optimizer is None else self.optimizer
)
model.compile(
loss=self.loss,
optimizer=self.optimizer_,
)
return model
def _fit(self, X, y):
"""
Fit the regressor on the training set (X, y).
Parameters
----------
X : np.ndarray of shape (n_instances, n_channels, series_length)
The training input samples. If a 2D array-like is passed,
n_channels is assumed to be 1.
y : np.ndarray of shape (n_instances)
The training data target values.
Returns
-------
self : object
"""
import tensorflow as tf
rng = check_random_state(self.random_state)
self.random_state_ = rng.randint(0, np.iinfo(np.int32).max)
# Transpose to conform to Keras input style.
X = X.transpose(0, 2, 1)
# ignore the number of instances, X.shape[0],
# just want the shape of each instance
self.input_shape_ = X.shape[1:]
if self.use_mini_batch_size:
mini_batch_size = int(min(X.shape[0] // 10, self.batch_size))
else:
mini_batch_size = self.batch_size
self.training_model_ = self.build_model(self.input_shape_)
if self.verbose:
self.training_model_.summary()
self.file_name_ = (
self.best_file_name if self.save_best_model else str(time.time_ns())
)
self.callbacks_ = (
[
tf.keras.callbacks.ReduceLROnPlateau(
monitor="loss", factor=0.5, patience=50, min_lr=0.0001
),
tf.keras.callbacks.ModelCheckpoint(
filepath=self.file_path + self.file_name_ + ".hdf5",
monitor="loss",
save_best_only=True,
),
]
if self.callbacks is None
else self.callbacks
)
self.history = self.training_model_.fit(
X,
y,
batch_size=mini_batch_size,
epochs=self.n_epochs,
verbose=self.verbose,
callbacks=self.callbacks_,
)
try:
self.model_ = tf.keras.models.load_model(
self.file_path + self.file_name_ + ".hdf5", compile=False
)
if not self.save_best_model:
os.remove(self.file_path + self.file_name_ + ".hdf5")
except FileNotFoundError:
self.model_ = deepcopy(self.training_model_)
if self.save_last_model:
self.save_last_model_to_file(file_path=self.file_path)
gc.collect()
return self
@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.
For regressors, a "default" set of parameters should be provided for
general testing, and a "results_comparison" set for comparing against
previously recorded results if the general set does not produce suitable
probabilities to compare against.
Returns
-------
params : dict or list of dict, default=[None]
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`.
"""
param1 = {
"n_epochs": 10,
"batch_size": 4,
"kernel_size": 4,
"use_residual": False,
"use_bottleneck": True,
"depth": 1,
"use_custom_filters": False,
}
return [param1]