/
compose.py
1751 lines (1451 loc) · 64 KB
/
compose.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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Meta-transformers for building composite transformers."""
from warnings import warn
import numpy as np
import pandas as pd
from sklearn import clone
from aeon.base import _HeterogenousMetaEstimator
from aeon.transformations._delegate import _DelegatedTransformer
from aeon.transformations.base import BaseTransformer
from aeon.utils.multiindex import flatten_multiindex
from aeon.utils.sklearn import (
is_sklearn_classifier,
is_sklearn_regressor,
is_sklearn_transformer,
)
from aeon.utils.validation.series import check_series
__maintainer__ = []
__all__ = [
"ColumnwiseTransformer",
"ColumnConcatenator",
"FeatureUnion",
"FitInTransform",
"Id",
"InvertTransform",
"MultiplexTransformer",
"OptionalPassthrough",
"TransformerPipeline",
"YtoX",
]
from aeon.utils import ALL_TIME_SERIES_TYPES
def _coerce_to_aeon(other):
"""Check and format inputs to dunders for compose."""
from aeon.transformations.adapt import TabularToSeriesAdaptor
# if sklearn transformer, adapt to aeon transformer first
if is_sklearn_transformer(other):
return TabularToSeriesAdaptor(other)
return other
class TransformerPipeline(_HeterogenousMetaEstimator, BaseTransformer):
"""
Pipeline of transformers compositor.
The `TransformerPipeline` compositor allows to chain transformers.
The pipeline is constructed with a list of aeon transformers, i.e.
estimators following the BaseTransformer interface. The list can be
unnamed (a simple list of transformers) or string named (a list of
pairs of string, estimator).
For a list of transformers `trafo1`, `trafo2`, ..., `trafoN`,
the pipeline behaves as follows:
* `fit`
Changes state by running `trafo1.fit_transform`,
trafo2.fit_transform` etc sequentially, with
`trafo[i]` receiving the output of `trafo[i-1]`
* `transform`
Result is of executing `trafo1.transform`, `trafo2.transform`,
etc with `trafo[i].transform` input = output of `trafo[i-1].transform`,
and returning the output of `trafoN.transform`
* `inverse_transform`
Result is of executing `trafo[i].inverse_transform`,
with `trafo[i].inverse_transform` input = output
`trafo[i-1].inverse_transform`, and returning the output of
`trafoN.inverse_transform`
* `update`
Changes state by chaining `trafo1.update`, `trafo1.transform`,
`trafo2.update`, `trafo2.transform`, ..., `trafoN.update`,
where `trafo[i].update` and `trafo[i].transform` receive as input
the output of `trafo[i-1].transform`
The `get_params`, `set_params` uses `sklearn` compatible nesting interface
if list is unnamed, names are generated as names of classes
if names are non-unique, `f"_{str(i)}"` is appended to each name string
where `i` is the total count of occurrence of a non-unique string
inside the list of names leading up to it (inclusive)
A `TransformerPipeline` can also be created by using the magic multiplication
on any transformer, i.e., any estimator inheriting from `BaseTransformer`
for instance, `my_trafo1 * my_trafo2 * my_trafo3`
will result in the same object as obtained from the constructor
`TransformerPipeline([my_trafo1, my_trafo2, my_trafo3])`
A magic multiplication can also be used with (str, transformer) pairs,
as long as one element in the chain is a transformer
Parameters
----------
steps : list of aeon transformers, or
List of tuples (str, transformer) of aeon transformers
these are "blueprint" transformers, states do not change when `fit` is called.
Attributes
----------
steps_ : list of tuples (str, transformer) of aeon transformers
Clones of transformers in `steps` which are fitted in the pipeline
is always in (str, transformer) format, even if `steps` is just a list
strings not passed in `steps` are replaced by unique generated strings
i-th transformer in `steps_` is clone of i-th in `steps`.
Examples
--------
>>> from aeon.transformations.exponent import ExponentTransformer
>>> t1 = ExponentTransformer(power=2)
>>> t2 = ExponentTransformer(power=0.5)
Example 1, option A: construct without strings (unique names are generated for
the two components t1 and t2)
>>> pipe = TransformerPipeline(steps = [t1, t2])
Example 1, option B: construct with strings to give custom names to steps
>>> pipe = TransformerPipeline(
... steps = [
... ("trafo1", t1),
... ("trafo2", t2),
... ]
... )
Example 1, option C: for quick construction, the * dunder method can be used
>>> pipe = t1 * t2
Example 2: sklearn transformers can be used in the pipeline.
If applied to Series, sklearn transformers are applied by series instance.
If applied to Table, sklearn transformers are applied to the table as a whole.
>>> from sklearn.preprocessing import StandardScaler
>>> from aeon.transformations.summarize import SummaryTransformer
This applies the scaler per series, then summarizes:
>>> pipe = StandardScaler() * SummaryTransformer()
This applies the sumamrization, then scales the full summary table:
>>> pipe = SummaryTransformer() * StandardScaler()
This scales the series, then summarizes, then scales the full summary table:
>>> pipe = StandardScaler() * SummaryTransformer() * StandardScaler()
"""
_tags = {
# we let all X inputs through to be handled by first transformer
"X_inner_type": ALL_TIME_SERIES_TYPES,
"univariate-only": False,
}
# no further default tag values - these are set dynamically below
# for default get_params/set_params from _HeterogenousMetaEstimator
# _steps_attr points to the attribute of self
# which contains the heterogeneous set of estimators
# this must be an iterable of (name: str, estimator, ...) tuples for the default
_steps_attr = "_steps"
# if the estimator is fittable, _HeterogenousMetaEstimator also
# provides an override for get_fitted_params for params from the fitted estimators
# the fitted estimators should be in a different attribute, _steps_fitted_attr
# this must be an iterable of (name: str, estimator, ...) tuples for the default
_steps_fitted_attr = "steps_"
def __init__(self, steps):
self.steps = steps
self.steps_ = self._check_estimators(self.steps, cls_type=BaseTransformer)
super().__init__()
# abbreviate for readability
ests = self.steps_
first_trafo = ests[0][1]
last_trafo = ests[-1][1]
self.clone_tags(first_trafo, ["input_data_type"])
# output type is that of last estimator, if no "Primitives" occur in the middle
# if "Primitives" occur in the middle, then output is set to that too
# this is in a case where "Series-to-Series" is applied to primitive df
# e.g., in a case of pipelining with scikit-learn transformers
last_out = last_trafo.get_tag("output_data_type")
self._anytagis_then_set("output_data_type", "Primitives", last_out, ests)
# set property tags based on tags of components
self._anytag_notnone_set("y_inner_type", ests)
self._anytag_notnone_set("transform_labels", ests)
self._anytagis_then_set("instancewise", False, True, ests)
self._anytagis_then_set("fit_is_empty", False, True, ests)
self._anytagis_then_set("transform-returns-same-time-index", False, True, ests)
self._anytagis_then_set("skip-inverse-transform", False, True, ests)
# self can inverse transform if for all est, we either skip or can inv-trasform
skips = [est.get_tag("skip-inverse-transform") for _, est in ests]
has_invs = [est.get_tag("capability:inverse_transform") for _, est in ests]
can_inv = [x or y for x, y in zip(skips, has_invs)]
self.set_tags(**{"capability:inverse_transform": all(can_inv)})
# can handle missing data iff all estimators can handle missing data
# up to a potential estimator when missing data is removed
# removes missing data iff can handle missing data,
# and there is an estimator in the chain that removes it
self._tagchain_is_linked_set(
"capability:missing_values", "capability:missing_values:removes", ests
)
# can handle unequal length iff all estimators can handle unequal length
# up to a potential estimator which turns the series equal length
# removes unequal length iff can handle unequal length,
# and there is an estimator in the chain that renders series equal length
self._tagchain_is_linked_set(
"capability:unequal_length", "capability:unequal_length:removes", ests
)
@property
def _steps(self):
return self._get_estimator_tuples(self.steps, clone_ests=False)
@_steps.setter
def _steps(self, value):
self.steps = value
def __mul__(self, other):
"""Magic * method, return (right) concatenated TransformerPipeline.
Implemented for `other` being a transformer, otherwise returns `NotImplemented`.
Parameters
----------
other: `aeon` transformer, must inherit from BaseTransformer
otherwise, `NotImplemented` is returned
Returns
-------
TransformerPipeline object, concatenation of `self` (first) with `other` (last).
not nested, contains only non-TransformerPipeline `aeon` transformers
"""
from aeon.classification.compose import SklearnClassifierPipeline
from aeon.regression.compose import SklearnRegressorPipeline
other = _coerce_to_aeon(other)
# if sklearn classifier, use sklearn classifier pipeline
if is_sklearn_classifier(other):
return SklearnClassifierPipeline(classifier=other, transformers=self.steps)
# if sklearn regressor, use sklearn regressor pipeline
if is_sklearn_regressor(other):
return SklearnRegressorPipeline(regressor=other, transformers=self.steps)
return self._dunder_concat(
other=other,
base_class=BaseTransformer,
composite_class=TransformerPipeline,
attr_name="steps",
concat_order="left",
)
def __rmul__(self, other):
"""Magic * method, return (left) concatenated TransformerPipeline.
Implemented for `other` being a transformer, otherwise returns `NotImplemented`.
Parameters
----------
other: `aeon` transformer, must inherit from BaseTransformer
otherwise, `NotImplemented` is returned
Returns
-------
TransformerPipeline object, concatenation of `other` (first) with `self` (last).
not nested, contains only non-TransformerPipeline `aeon` steps
"""
other = _coerce_to_aeon(other)
return self._dunder_concat(
other=other,
base_class=BaseTransformer,
composite_class=TransformerPipeline,
attr_name="steps",
concat_order="right",
)
def _fit(self, X, y=None):
"""Fit transformer to X and y.
private _fit containing the core logic, called from fit
Parameters
----------
X: data structure of type X_inner_type
if X_inner_type is list, _fit must support all types in it
Data to fit transform to
y : Series or Panel of type y_inner_type, default=None
Additional data, e.g., labels for transformation
Returns
-------
self: reference to self
"""
self.steps_ = self._check_estimators(self.steps, cls_type=BaseTransformer)
Xt = X
for _, transformer in self.steps_:
Xt = transformer.fit_transform(X=Xt, y=y)
return self
def _transform(self, X, y=None):
"""Transform X and return a transformed version.
private _transform containing core logic, called from transform
Parameters
----------
X: data structure of type X_inner_type
if X_inner_type is list, _transform must support all types in it
Data to be transformed
y : Series or Panel of type y_inner_type, default=None
Additional data, e.g., labels for transformation
Returns
-------
transformed version of X
"""
Xt = X
for _, transformer in self.steps_:
if not self.get_tag("fit_is_empty", False):
Xt = transformer.transform(X=Xt, y=y)
else:
Xt = transformer.fit_transform(X=Xt, y=y)
return Xt
def _inverse_transform(self, X, y=None):
"""Inverse transform, inverse operation to transform.
private _inverse_transform containing core logic, called from inverse_transform
Parameters
----------
X: data structure of type X_inner_type
if X_inner_type is list, _inverse_transform must support all types in it
Data to be inverse transformed
y : Series or Panel of type y_inner_type, optional (default=None)
Additional data, e.g., labels for transformation
Returns
-------
inverse transformed version of X
"""
Xt = X
for _, transformer in reversed(self.steps_):
if not self.get_tag("fit_is_empty", False):
Xt = transformer.inverse_transform(X=Xt, y=y)
else:
Xt = transformer.fit(X=Xt, y=y).inverse_transform(X=Xt, y=y)
return Xt
def _update(self, X, y=None):
"""Update transformer with X and y.
private _update containing the core logic, called from update
Parameters
----------
X: data structure of type X_inner_type
if X_inner_type is list, _update must support all types in it
Data to update transformer with
y : Series or Panel of type y_inner_type, default=None
Additional data, e.g., labels for tarnsformation
Returns
-------
self: reference to self
"""
Xt = X
for _, transformer in self.steps_:
transformer.update(X=Xt, y=y)
Xt = transformer.transform(X=Xt, y=y)
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.
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`.
"""
# imports
from aeon.transformations.exponent import ExponentTransformer
t1 = ExponentTransformer(power=2)
t2 = ExponentTransformer(power=0.5)
t3 = ExponentTransformer(power=1)
# construct without names
params1 = {"steps": [t1, t2]}
# construct with names
params2 = {"steps": [("foo", t1), ("bar", t2), ("foobar", t3)]}
# construct with names and provoke multiple naming clashes
params3 = {"steps": [("foo", t1), ("foo", t2), ("foo_1", t3)]}
return [params1, params2, params3]
class FeatureUnion(_HeterogenousMetaEstimator, BaseTransformer):
"""Concatenates results of multiple transformer objects.
This estimator applies a list of transformer objects in parallel to the
input data, then concatenates the results. This is useful to combine
several feature extraction mechanisms into a single transformer.
Parameters of the transformations may be set using its name and the
parameter name separated by a '__'. A transformer may be replaced entirely by
setting the parameter with its name to another transformer,
or removed by setting to 'drop' or ``None``.
Parameters
----------
transformer_list : list of (string, transformer) tuples
List of transformer objects to be applied to the data. The first
half of each tuple is the name of the transformer.
n_jobs : int or None, optional (default=None)
Number of jobs to run in parallel.
``None`` means 1 unless in a :obj:`joblib.parallel_backend`
context.
``-1`` means using all processors.
transformer_weights : dict, optional
Multiplicative weights for features per transformer.
Keys are transformer names, values the weights.
flatten_transform_index : bool, optional (default=True)
if True, columns of return DataFrame are flat, by "transformer__variablename"
if False, columns are MultiIndex (transformer, variablename)
has no effect if return type is one without column names
"""
_tags = {
"input_data_type": "Series",
"output_data_type": "Series",
"transform_labels": "None",
"instancewise": False, # depends on components
"univariate-only": False, # depends on components
"capability:missing_values": False, # depends on components
"X_inner_type": ["pd.DataFrame", "pd-multiindex", "pd_multiindex_hier"],
"y_inner_type": "None",
"X-y-must-have-same-index": False,
"enforce_index_type": None,
"fit_is_empty": False,
"transform-returns-same-time-index": False,
"skip-inverse-transform": False,
"capability:inverse_transform": False,
# unclear what inverse transform should be, since multiple inverse_transform
# would have to inverse transform to one
}
# for default get_params/set_params from _HeterogenousMetaEstimator
# _steps_attr points to the attribute of self
# which contains the heterogeneous set of estimators
# this must be an iterable of (name: str, estimator) pairs for the default
_steps_attr = "_transformer_list"
# if the estimator is fittable, _HeterogenousMetaEstimator also
# provides an override for get_fitted_params for params from the fitted estimators
# the fitted estimators should be in a different attribute, _steps_fitted_attr
_steps_fitted_attr = "transformer_list_"
def __init__(
self,
transformer_list,
n_jobs=None,
transformer_weights=None,
flatten_transform_index=True,
):
self.transformer_list = transformer_list
self.transformer_list_ = self._check_estimators(
transformer_list, cls_type=BaseTransformer
)
self.n_jobs = n_jobs
self.transformer_weights = transformer_weights
self.flatten_transform_index = flatten_transform_index
super().__init__()
# abbreviate for readability
ests = self.transformer_list_
# set property tags based on tags of components
self._anytag_notnone_set("y_inner_type", ests)
self._anytag_notnone_set("transform_labels", ests)
self._anytagis_then_set("instancewise", False, True, ests)
self._anytagis_then_set("X-y-must-have-same-index", True, False, ests)
self._anytagis_then_set("fit_is_empty", False, True, ests)
self._anytagis_then_set("transform-returns-same-time-index", False, True, ests)
self._anytagis_then_set("skip-inverse-transform", True, False, ests)
# self._anytagis_then_set("capability:inverse_transform", False, True, ests)
self._anytagis_then_set("capability:missing_values", False, True, ests)
self._anytagis_then_set("univariate-only", True, False, ests)
@property
def _transformer_list(self):
return self._get_estimator_tuples(self.transformer_list, clone_ests=False)
@_transformer_list.setter
def _transformer_list(self, value):
self.transformer_list = value
self.transformer_list_ = self._check_estimators(value, cls_type=BaseTransformer)
def __add__(self, other):
"""Magic + method, return (right) concatenated FeatureUnion.
Implemented for `other` being a transformer, otherwise returns `NotImplemented`.
Parameters
----------
other: `aeon` transformer, must inherit from BaseTransformer
otherwise, `NotImplemented` is returned
Returns
-------
TransformerPipeline object, concatenation of `self` (first) with `other` (last).
not nested, contains only non-FeatureUnion `aeon` transformers
"""
return self._dunder_concat(
other=other,
base_class=BaseTransformer,
composite_class=FeatureUnion,
attr_name="transformer_list",
concat_order="left",
)
def __radd__(self, other):
"""Magic + method, return (left) concatenated FeatureUnion.
Implemented for `other` being a transformer, otherwise returns `NotImplemented`.
Parameters
----------
other: `aeon` transformer, must inherit from BaseTransformer
otherwise, `NotImplemented` is returned
Returns
-------
TransformerPipeline object, concatenation of `self` (last) with `other` (first).
not nested, contains only non-FeatureUnion `aeon` transformers
"""
return self._dunder_concat(
other=other,
base_class=BaseTransformer,
composite_class=FeatureUnion,
attr_name="transformer_list",
concat_order="right",
)
def _fit(self, X, y=None):
"""Fit transformer to X and y.
private _fit containing the core logic, called from fit
Parameters
----------
X : pd.DataFrame
Data to fit transform to
y : Series or Panel of type y_inner_type, default=None
Additional data, e.g., labels for transformation
Returns
-------
self: reference to self
"""
self.transformer_list_ = self._check_estimators(
self.transformer_list, cls_type=BaseTransformer
)
for _, transformer in self.transformer_list_:
transformer.fit(X=X, y=y)
return self
def _transform(self, X, y=None):
"""Transform X and return a transformed version.
private _transform containing core logic, called from transform
Parameters
----------
X : pd.DataFrame
Data to be transformed
y : Series or Panel of type y_inner_type, default=None
Additional data, e.g., labels for transformation
Returns
-------
transformed version of X
"""
# retrieve fitted transformers, apply to the new data individually
transformers = self._get_estimator_list(self.transformer_list_)
if not self.get_tag("fit_is_empty", False):
Xt_list = [trafo.transform(X, y) for trafo in transformers]
else:
Xt_list = [trafo.fit_transform(X, y) for trafo in transformers]
transformer_names = self._get_estimator_names(self.transformer_list_)
Xt = pd.concat(
Xt_list, axis=1, keys=transformer_names, names=["transformer", "variable"]
)
if self.flatten_transform_index:
Xt.columns = flatten_multiindex(Xt.columns)
return Xt
@classmethod
def get_test_params(cls, parameter_set="default"):
"""Test parameters for FeatureUnion."""
from aeon.transformations.boxcox import BoxCoxTransformer
from aeon.transformations.exponent import ExponentTransformer
# with name and estimator tuple, all transformers don't have fit
TRANSFORMERS = [
("transformer1", ExponentTransformer(power=4)),
("transformer2", ExponentTransformer(power=0.25)),
]
params1 = {"transformer_list": TRANSFORMERS}
# only with estimators, some transformers have fit, some not
params2 = {
"transformer_list": [
ExponentTransformer(power=4),
ExponentTransformer(power=0.25),
BoxCoxTransformer(),
]
}
return [params1, params2]
class FitInTransform(BaseTransformer):
"""
Transformer wrapper to delay fit to the transform phase.
In panel settings, e.g., time series classification, it can be preferable
(or, necessary) to fit and transform on the test set, e.g., interpolate within the
same series that interpolation parameters are being fitted on. `FitInTransform` can
be used to wrap any transformer to ensure that `fit` and `transform` happen always
on the same series, by delaying the `fit` to the `transform` batch.
Warning: The use of `FitInTransform` will typically not be useful, or can constitute
a mistake (data leakage) when naively used in a forecasting setting.
Parameters
----------
transformer : Estimator
Scikit-learn-like or aeon-like transformer to fit and apply to series.
skip_inverse_transform : bool
The FitInTransform will skip inverse_transform by default, of the param
skip_inverse_transform=False, then the inverse_transform is calculated
by means of transformer.fit(X=X, y=y).inverse_transform(X=X, y=y) where
transformer is the inner transformer. So the inner transformer is
fitted on the inverse_transform data. This is required to have a non-
state changing transform() method of FitInTransform.
Examples
--------
>>> from aeon.datasets import load_longley
>>> from aeon.forecasting.naive import NaiveForecaster
>>> from aeon.forecasting.base import ForecastingHorizon
>>> from aeon.forecasting.compose import ForecastingPipeline
>>> from aeon.forecasting.model_selection import temporal_train_test_split
>>> from aeon.transformations.compose import FitInTransform
>>> from aeon.transformations.impute import Imputer
>>> y, X = load_longley()
>>> y_train, y_test, X_train, X_test = temporal_train_test_split(y, X)
>>> fh = ForecastingHorizon(y_test.index, is_relative=False)
>>> # we want to fit the Imputer only on the predict (=transform) data.
>>> # note that NaiveForecaster cant use X data, this is just a show case.
>>> pipe = ForecastingPipeline(
... steps=[
... ("imputer", FitInTransform(Imputer(method="mean"))),
... ("forecaster", NaiveForecaster()),
... ]
... )
>>> pipe.fit(y_train, X_train)
ForecastingPipeline(...)
>>> y_pred = pipe.predict(fh=fh, X=X_test)
"""
def __init__(self, transformer, skip_inverse_transform=True):
self.transformer = transformer
self.skip_inverse_transform = skip_inverse_transform
super().__init__()
self.clone_tags(transformer, None)
self.set_tags(
**{
"fit_is_empty": True,
"skip-inverse-transform": self.skip_inverse_transform,
}
)
def _transform(self, X, y=None):
"""Transform X and return a transformed version.
private _transform containing core logic, called from transform
Parameters
----------
X: data structure of type X_inner_type
if X_inner_type is list, _transform must support all types in it
Data to be transformed
y : Series or Panel of type y_inner_type, default=None
Additional data, e.g., labels for transformation
Returns
-------
transformed version of X
"""
return clone(self.transformer).fit_transform(X=X, y=y)
def _inverse_transform(self, X, y=None):
"""Inverse transform, inverse operation to transform.
private _inverse_transform containing core logic, called from inverse_transform
Parameters
----------
X: data structure of type X_inner_type
if X_inner_type is list, _inverse_transform must support all types in it
Data to be inverse transformed
y : Series or Panel of type y_inner_type, optional (default=None)
Additional data, e.g., labels for transformation
Returns
-------
inverse transformed version of X
"""
return clone(self.transformer).fit(X=X, y=y).inverse_transform(X=X, y=y)
def _get_fitted_params(self):
"""Get fitted parameters.
Returns
-------
fitted_params : dict
"""
return {}
@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.
There are currently no reserved values for transformers.
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.transformations.boxcox import BoxCoxTransformer
params = [
{"transformer": BoxCoxTransformer()},
{"transformer": BoxCoxTransformer(), "skip_inverse_transform": False},
]
return params
class MultiplexTransformer(_HeterogenousMetaEstimator, _DelegatedTransformer):
"""
Facilitate an AutoML based selection of the best transformer.
When used in combination with either TransformedTargetForecaster or
ForecastingPipeline in combination with ForecastingGridSearchCV
MultiplexTransformer provides a framework for transformer selection. Through
selection of the appropriate pipeline (ie TransformedTargetForecaster vs
ForecastingPipeline) the transformers in MultiplexTransformer will either be
applied to exogenous data, or to the target data.
MultiplexTransformer delegates all transforming tasks (ie, calls to fit, transform,
inverse_transform, and update) to a copy of the transformer in transformers
whose name matches selected_transformer. All other transformers in transformers
will be ignored.
Parameters
----------
transformers : list of aeon transformers, or
list of tuples (str, estimator) of named aeon transformers
MultiplexTransformer can switch ("multiplex") between these transformers.
Note - all the transformers passed in "transformers" should be thought of as
blueprints. Calling transformation functions on MultiplexTransformer will not
change their state at all. - Rather a copy of each is created and this is what
is updated.
selected_transformer : str or None, optional, Default=None.
If str, must be one of the transformer names.
If passed in transformers were unnamed then selected_transformer must
coincide with auto-generated name strings.
To inspect auto-generated name strings, call get_params.
If None, selected_transformer defaults to the name of the first transformer
in transformers.
selected_transformer represents the name of the transformer MultiplexTransformer
should behave as (ie delegate all relevant transformation functionality to)
Attributes
----------
transformer_ : aeon transformer
clone of the transformer named by selected_transformer to which all the
transformation functionality is delegated to.
_transformers : list of (name, est) tuples, where est are direct references to
the estimators passed in transformers passed. If transformers was passed
without names, those be auto-generated and put here.
Examples
--------
>>> from aeon.datasets import load_shampoo_sales
>>> from aeon.forecasting.naive import NaiveForecaster
>>> from aeon.transformations.compose import MultiplexTransformer
>>> from aeon.transformations.impute import Imputer
>>> from aeon.forecasting.compose import TransformedTargetForecaster
>>> from aeon.forecasting.model_selection import (
... ForecastingGridSearchCV,
... ExpandingWindowSplitter)
>>> # create MultiplexTransformer:
>>> multiplexer = MultiplexTransformer(transformers=[
... ("impute_mean", Imputer(method="mean", missing_values = -1)),
... ("impute_near", Imputer(method="nearest", missing_values = -1)),
... ("impute_rand", Imputer(method="random", missing_values = -1))])
>>> cv = ExpandingWindowSplitter(
... initial_window=24,
... step_length=12,
... fh=[1,2,3])
>>> pipe = TransformedTargetForecaster(steps = [
... ("multiplex", multiplexer),
... ("forecaster", NaiveForecaster())
... ])
>>> gscv = ForecastingGridSearchCV(
... cv=cv,
... param_grid={"multiplex__selected_transformer":
... ["impute_mean", "impute_near", "impute_rand"]},
... forecaster=pipe,
... )
>>> y = load_shampoo_sales()
>>> # randomly make some of the values nans:
>>> y.loc[y.sample(frac=0.1).index] = -1
>>> gscv = gscv.fit(y)
"""
# tags will largely be copied from selected_transformer
_tags = {
"fit_is_empty": False,
"univariate-only": False,
"X_inner_type": [
"dask_panel",
"pd-multiindex",
"pd-long",
"df-list",
"xr.DataArray",
"pd_multiindex_hier",
"numpy3D",
"np-list",
"pd.DataFrame",
"pd.Series",
"dask_hierarchical",
"np.ndarray",
"dask_series",
"nested_univ",
"pd-wide",
],
}
# attribute for _DelegatedTransformer, which then delegates
# all non-overridden methods are same as of getattr(self, _delegate_name)
# see further details in _DelegatedTransformer docstring
_delegate_name = "transformer_"
# for default get_params/set_params from _HeterogenousMetaEstimator
# _steps_attr points to the attribute of self
# which contains the heterogeneous set of estimators
# this must be an iterable of (name: str, estimator) pairs for the default
_steps_attr = "_transformers"
# if the estimator is fittable, _HeterogenousMetaEstimator also
# provides an override for get_fitted_params for params from the fitted estimators
# the fitted estimators should be in a different attribute, _steps_fitted_attr
_steps_fitted_attr = "transformers_"
def __init__(
self,
transformers: list,
selected_transformer=None,
):
super().__init__()
self.selected_transformer = selected_transformer
self.transformers = transformers
self._check_estimators(
transformers,
attr_name="transformers",
cls_type=BaseTransformer,
clone_ests=False,
)
self._set_transformer()
self.clone_tags(self.transformer_)
self.set_tags(**{"fit_is_empty": False})
# this ensures that we convert in the inner estimator, not in the multiplexer
self.set_tags(**{"X_inner_type": ALL_TIME_SERIES_TYPES})
@property
def _transformers(self):
"""Forecasters turned into name/est tuples."""
return self._get_estimator_tuples(self.transformers, clone_ests=False)
@_transformers.setter
def _transformers(self, value):
self.transformers = value
def _check_selected_transformer(self):
component_names = self._get_estimator_names(
self._transformers, make_unique=True
)
selected = self.selected_transformer
if selected is not None and selected not in component_names:
raise Exception(
f"Invalid selected_transformer parameter value provided, "
f" found: {selected}. Must be one of these"
f" valid selected_transformer parameter values: {component_names}."
)
def _set_transformer(self):
self._check_selected_transformer()
# clone the selected transformer to self.transformer_
if self.selected_transformer is not None:
for name, transformer in self._get_estimator_tuples(self.transformers):
if self.selected_transformer == name:
self.transformer_ = transformer.clone()
else:
# if None, simply clone the first transformer to self.transformer_
self.transformer_ = self._get_estimator_list(self.transformers)[0].clone()
@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
"""
from aeon.transformations.impute import Imputer
# test with 2 simple detrend transformations with selected_transformer
params1 = {
"transformers": [
("imputer_mean", Imputer(method="mean")),
("imputer_near", Imputer(method="nearest")),
],
"selected_transformer": "imputer_near",
}
# test no selected_transformer
params2 = {
"transformers": [
Imputer(method="mean"),
Imputer(method="nearest"),
],
}
return [params1, params2]
def __or__(self, other):
"""Magic | (or) method, return (right) concatenated MultiplexTransformer.
Implemented for `other` being a transformer, otherwise returns `NotImplemented`.
Parameters
----------
other: `aeon` transformer, must inherit from BaseTransformer
otherwise, `NotImplemented` is returned
Returns