-
Notifications
You must be signed in to change notification settings - Fork 89
/
_base.py
1131 lines (919 loc) · 38.1 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
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
"""
Base class template for objects and fittable objects.
templates in this module:
BaseObject - object with parameters and tags
BaseEstimator - BaseObject that can be fitted
Interface specifications below.
---
class name: BaseObject
Parameter inspection and setter methods
inspect parameter values - get_params()
setting parameter values - set_params(**params)
list of parameter names - get_param_names()
dict of parameter defaults - get_param_defaults()
Tag inspection and setter methods
inspect tags (all) - get_tags()
inspect tags (one tag) - get_tag(tag_name: str, tag_value_default=None)
inspect tags (class method) - get_class_tags()
inspect tags (one tag, class) - get_class_tag(tag_name:str, tag_value_default=None)
setting dynamic tags - set_tags(**tag_dict: dict)
set/clone dynamic tags - clone_tags(estimator, tag_names=None)
Blueprinting: resetting and cloning, post-init state with same hyper-parameters
reset estimator to post-init - reset()
cloneestimator (copy&reset) - clone()
Testing with default parameters methods
getting default parameters (all sets) - get_test_params()
get one test instance with default parameters - create_test_instance()
get list of all test instances plus name list - create_test_instances_and_names()
---
class name: BaseEstimator
Provides all interface points of BaseObject, plus:
Parameter inspection:
fitted parameter inspection - get_fitted_params()
State:
fitted model/strategy - by convention, any attributes ending in "_"
fitted state flag - is_fitted (property)
fitted state check - check_is_fitted (raises error if not is_fitted)
"""
__author__ = ["mloning", "RNKuhns", "fkiraly"]
__all__ = ["BaseEstimator", "BaseObject"]
import inspect
import warnings
from collections import defaultdict
from copy import deepcopy
from sklearn import clone
from sklearn.base import BaseEstimator as _BaseEstimator
from sklearn.ensemble._base import _set_random_states
from aeon.exceptions import NotFittedError
class BaseObject(_BaseEstimator):
"""Base class for parametric objects with tags aeon.
Extends scikit-learn's BaseEstimator to include aeon interface for tags.
"""
def __init__(self):
self._tags_dynamic = dict()
super().__init__()
def __eq__(self, other):
"""Equality dunder. Checks equal class and parameters.
Returns True iff result of get_params(deep=False)
results in equal parameter sets.
Nested BaseObject descendants from get_params are compared via __eq__ as well.
"""
from aeon.testing.utils.deep_equals import deep_equals
if not isinstance(other, BaseObject):
return False
self_params = self.get_params(deep=False)
other_params = other.get_params(deep=False)
return deep_equals(self_params, other_params)
def reset(self):
"""Reset the object to a clean post-init state.
Equivalent to sklearn.clone but overwrites self.
After ``self.reset()`` call, self is equal in value to
``type(self)(**self.get_params(deep=False))``
Detail behaviour:
removes any object attributes, except:
hyper-parameters = arguments of ``__init__``
object attributes containing double-underscores, i.e., the string "__"
runs ``__init__`` with current values of hyper-parameters (result of get_params)
Not affected by the reset are:
object attributes containing double-underscores
class and object methods, class attributes
"""
# retrieve parameters to copy them later
params = self.get_params(deep=False)
# delete all object attributes in self
attrs = [attr for attr in dir(self) if "__" not in attr]
cls_attrs = [attr for attr in dir(type(self))]
self_attrs = set(attrs).difference(cls_attrs)
for attr in self_attrs:
delattr(self, attr)
# run init with a copy of parameters self had at the start
self.__init__(**params)
return self
def clone(self):
"""
Obtain a clone of the object with same hyper-parameters.
A clone is a different object without shared references, in post-init state.
This function is equivalent to returning sklearn.clone of self.
Equal in value to ``type(self)(**self.get_params(deep=False))``.
Returns
-------
instance of ``type(self)``, clone of self (see above)
"""
return clone(self)
@classmethod
def _get_init_signature(cls):
"""Get init sigature of cls, for use in parameter inspection.
Returns
-------
list of inspect Parameter objects (including defaults)
Raises
------
RuntimeError if cls has varargs in ``__init__``
"""
# fetch the constructor or the original constructor before
# deprecation wrapping if any
init = getattr(cls.__init__, "deprecated_original", cls.__init__)
if init is object.__init__:
# No explicit constructor to introspect
return []
# introspect the constructor arguments to find the model parameters
# to represent
init_signature = inspect.signature(init)
# Consider the constructor parameters excluding 'self'
parameters = [
p
for p in init_signature.parameters.values()
if p.name != "self" and p.kind != p.VAR_KEYWORD
]
for p in parameters:
if p.kind == p.VAR_POSITIONAL:
raise RuntimeError(
"scikit-learn compatible estimators should always "
"specify their parameters in the signature"
" of their __init__ (no varargs)."
" %s with constructor %s doesn't "
" follow this convention." % (cls, init_signature)
)
return parameters
@classmethod
def get_param_names(cls):
"""
Get parameter names for the object.
Returns
-------
param_names: list of str, alphabetically sorted list of parameter names of cls
"""
parameters = cls._get_init_signature()
param_names = sorted([p.name for p in parameters])
return param_names
@classmethod
def get_param_defaults(cls):
"""
Get parameter defaults for the object.
Returns
-------
default_dict: dict with str keys
keys are all parameters of cls that have a default defined in __init__
values are the defaults, as defined in __init__.
"""
parameters = cls._get_init_signature()
default_dict = {
x.name: x.default for x in parameters if x.default != inspect._empty
}
return default_dict
def set_params(self, **params):
"""
Set the parameters of this object.
The method works on simple estimators as well as on nested objects.
The latter have parameters of the form ``<component>__<parameter>`` so that it's
possible to update each component of a nested object.
Parameters
----------
**params : dict
BaseObject parameters
Returns
-------
self : reference to self (after parameters have been set)
"""
if not params:
# Simple optimization to gain speed (inspect is slow)
return self
valid_params = self.get_params(deep=True)
nested_params = defaultdict(dict) # grouped by prefix
for key, value in params.items():
key, delim, sub_key = key.partition("__")
if key not in valid_params:
raise ValueError(
"Invalid parameter %s for object %s. "
"Check the list of available parameters "
"with `object.get_params().keys()`." % (key, self)
)
if delim:
nested_params[key][sub_key] = value
else:
setattr(self, key, value)
valid_params[key] = value
self.reset()
# recurse in components
for key, sub_params in nested_params.items():
valid_params[key].set_params(**sub_params)
return self
@classmethod
def get_class_tags(cls):
"""
Get class tags from estimator class and all its parent classes.
Returns
-------
collected_tags : dict
Dictionary of tag name : tag value pairs. Collected from _tags
class attribute via nested inheritance. NOT overridden by dynamic
tags set by set_tags or mirror_tags.
"""
collected_tags = dict()
# We exclude the last two parent classes: sklearn.base.BaseEstimator and
# the basic Python object.
for parent_class in reversed(inspect.getmro(cls)[:-2]):
if hasattr(parent_class, "_tags"):
# Need the if here because mixins might not have _more_tags
# but might do redundant work in estimators
# (i.e. calling more tags on BaseEstimator multiple times)
more_tags = parent_class._tags
collected_tags.update(more_tags)
return deepcopy(collected_tags)
@classmethod
def get_class_tag(cls, tag_name, tag_value_default=None):
"""
Get tag value from estimator class (only class tags).
Parameters
----------
tag_name : str
Name of tag value.
tag_value_default : any type
Default/fallback value if tag is not found.
Returns
-------
tag_value :
Value of the `tag_name` tag in self. If not found, returns
`tag_value_default`.
See Also
--------
get_tag : Get a single tag from an object.
get_tags : Get all tags from an object.
get_class_tag : Get a single tag from a class.
Examples
--------
>>> from aeon.classification import DummyClassifier
>>> DummyClassifier.get_class_tag("capability:multivariate")
True
"""
collected_tags = cls.get_class_tags()
return collected_tags.get(tag_name, tag_value_default)
def get_tags(self):
"""
Get tags from estimator class.
Includes the dynamic tag overrides.
Returns
-------
dict
Dictionary of tag name : tag value pairs. Collected from _tags
class attribute via nested inheritance and then any overrides
and new tags from _tags_dynamic object attribute.
See Also
--------
get_tag : Get a single tag from an object.
get_clas_tags : Get all tags from a class.
get_class_tag : Get a single tag from a class.
Examples
--------
>>> from aeon.classification import DummyClassifier
>>> d = DummyClassifier()
>>> tags = d.get_tags()
"""
collected_tags = self.get_class_tags()
if hasattr(self, "_tags_dynamic"):
collected_tags.update(self._tags_dynamic)
return deepcopy(collected_tags)
def get_tag(self, tag_name, tag_value_default=None, raise_error=True):
"""
Get tag value from estimator class.
Uses dynamic tag overrides.
Parameters
----------
tag_name : str
Name of tag to be retrieved.
tag_value_default : any type, default=None
Default/fallback value if tag is not found.
raise_error : bool
Whether a ValueError is raised when the tag is not found.
Returns
-------
tag_value :
Value of the `tag_name` tag in self. If not found, returns an error if
raise_error is True, otherwise it returns `tag_value_default`.
Raises
------
ValueError if raise_error is True i.e. if tag_name is not in self.get_tags(
).keys()
See Also
--------
get_tags : Get all tags from an object.
get_clas_tags : Get all tags from a class.
get_class_tag : Get a single tag from a class.
Examples
--------
>>> from aeon.classification import DummyClassifier
>>> d = DummyClassifier()
>>> d.get_tag("capability:multivariate")
True
"""
collected_tags = self.get_tags()
tag_value = collected_tags.get(tag_name, tag_value_default)
if raise_error and tag_name not in collected_tags.keys():
raise ValueError(f"Tag with name {tag_name} could not be found.")
return tag_value
def set_tags(self, **tag_dict):
"""
Set dynamic tags to given values.
Parameters
----------
**tag_dict : dict
Dictionary of tag name : tag value pairs.
Returns
-------
Self :
Reference to self.
Notes
-----
Changes object state by setting tag values in tag_dict as dynamic tags
in self.
"""
tag_update = deepcopy(tag_dict)
if hasattr(self, "_tags_dynamic"):
self._tags_dynamic.update(tag_update)
else:
self._tags_dynamic = tag_update
return self
def clone_tags(self, estimator, tag_names=None):
"""
Clone/mirror tags from another estimator as dynamic override.
Parameters
----------
estimator : object
Estimator inheriting from :class:BaseEstimator.
tag_names : str or list of str, default = None
Names of tags to clone. If None then all tags in estimator are used
as `tag_names`.
Returns
-------
Self :
Reference to self.
Notes
-----
Changes object state by setting tag values in tag_set from estimator as
dynamic tags in self.
"""
tags_est = deepcopy(estimator.get_tags())
# if tag_set is not passed, default is all tags in estimator
if tag_names is None:
tag_names = tags_est.keys()
else:
# if tag_set is passed, intersect keys with tags in estimator
if not isinstance(tag_names, list):
tag_names = [tag_names]
tag_names = [key for key in tag_names if key in tags_est.keys()]
update_dict = {key: tags_est[key] for key in tag_names}
self.set_tags(**update_dict)
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`.
"""
# default parameters = empty dict
return {}
@classmethod
def create_test_instance(cls, parameter_set="default"):
"""
Construct Estimator instance if possible.
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
-------
instance : instance of the class with default parameters.
Notes
-----
`get_test_params` can return dict or list of dict.
This function takes first or single dict that get_test_params returns, and
constructs the object with that.
"""
if "parameter_set" in inspect.getfullargspec(cls.get_test_params).args:
params = cls.get_test_params(parameter_set=parameter_set)
else:
params = cls.get_test_params()
if isinstance(params, list):
if isinstance(params[0], dict):
params = params[0]
else:
raise TypeError(
"get_test_params should either return a dict or list of dict."
)
elif isinstance(params, dict):
pass
else:
raise TypeError(
"get_test_params should either return a dict or list of dict."
)
return cls(**params)
@classmethod
def create_test_instances_and_names(cls, parameter_set="default"):
"""
Create list of all test instances and a list of names for them.
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
-------
objs : list of instances of cls
i-th instance is cls(**cls.get_test_params()[i]).
names : list of str, same length as objs
i-th element is name of i-th instance of obj in tests
convention is {cls.__name__}-{i} if more than one instance
otherwise {cls.__name__}.
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.
"""
if "parameter_set" in inspect.getfullargspec(cls.get_test_params).args:
param_list = cls.get_test_params(parameter_set=parameter_set)
else:
param_list = cls.get_test_params()
objs = []
if not isinstance(param_list, (dict, list)):
raise RuntimeError(
f"Error in {cls.__name__}.get_test_params, "
"return must be param dict for class, or list thereof"
)
if isinstance(param_list, dict):
param_list = [param_list]
for params in param_list:
if not isinstance(params, dict):
raise RuntimeError(
f"Error in {cls.__name__}.get_test_params, "
"return must be param dict for class, or list thereof"
)
objs += [cls(**params)]
num_instances = len(param_list)
if num_instances > 1:
names = [cls.__name__ + "-" + str(i) for i in range(num_instances)]
else:
names = [cls.__name__]
return objs, names
@classmethod
def _has_implementation_of(cls, method):
"""
Check if method has a concrete implementation in this class.
This assumes that having an implementation is equivalent to
one or more overrides of `method` in the method resolution order.
Parameters
----------
method : str
name of method to check implementation of.
Returns
-------
bool, whether method has implementation in cls
True if cls.method has been overridden at least once in
the inheritance tree (according to method resolution order).
"""
# walk through method resolution order and inspect methods
# of classes and direct parents, "adjacent" classes in mro
mro = inspect.getmro(cls)
# collect all methods that are not none
methods = [getattr(c, method, None) for c in mro]
methods = [m for m in methods if m is not None]
for i in range(len(methods) - 1):
# the method has been overridden once iff
# at least two of the methods collected are not equal
# equivalently: some two adjacent methods are not equal
overridden = methods[i] != methods[i + 1]
if overridden:
return True
return False
def is_composite(self):
"""
Check if the object is composite.
A composite object is an object which contains objects, as parameters.
Called on an instance, since this may differ by instance.
Returns
-------
composite: bool
Whether self contains a parameter which is BaseObject.
"""
# walk through method resolution order and inspect methods
# of classes and direct parents, "adjacent" classes in mro
params = self.get_params(deep=False)
composite = any(isinstance(x, BaseObject) for x in params.values())
return composite
def _components(self, base_class=None):
"""
Return references to all state changing BaseObject type attributes.
This *excludes* the blue-print-like components passed in the __init__.
Caution: this method returns *references* and not *copies*.
Writing to the reference will change the respective attribute of self.
Parameters
----------
base_class : class, optional, default=None, must be subclass of BaseObject
if None, behaves the same as `base_class=BaseObject`
if not None, return dict collects descendants of `base_class`.
Returns
-------
dict with key = attribute name, value = reference to attribute.
dict contains all attributes of `self` that inherit from `base_class`, and:
whose names do not contain the string "__", e.g., hidden attributes
are not class attributes, and are not hyper-parameters (`__init__` args).
"""
if base_class is None:
base_class = BaseObject
if base_class is not None and not inspect.isclass(base_class):
raise TypeError(f"base_class must be a class, but found {type(base_class)}")
# if base_class is not None and not issubclass(base_class, BaseObject):
# raise TypeError("base_class must be a subclass of BaseObject")
# retrieve parameter names to exclude them later
param_names = self.get_params(deep=False).keys()
# retrieve all attributes that are BaseObject descendants
attrs = [attr for attr in dir(self) if "__" not in attr]
cls_attrs = [attr for attr in dir(type(self))]
self_attrs = set(attrs).difference(cls_attrs).difference(param_names)
comp_dict = {x: getattr(self, x) for x in self_attrs}
comp_dict = {x: y for (x, y) in comp_dict.items() if isinstance(y, base_class)}
return comp_dict
def save(self, path=None):
"""
Save serialized self to bytes-like object or to (.zip) file.
Behaviour:
if `path` is None, returns an in-memory serialized self
if `path` is a file location, stores self at that location as a zip file
saved files are zip files with following contents:
_metadata - contains class of self, i.e., type(self)
_obj - serialized self. This class uses the default serialization (pickle).
Parameters
----------
path : None or file location (str or Path).
if None, self is saved to an in-memory object
if file location, self is saved to that file location. If:
path="estimator" then a zip file `estimator.zip` will be made at cwd.
path="/home/stored/estimator" then a zip file `estimator.zip` will be
stored in `/home/stored/`.
Returns
-------
if `path` is None - in-memory serialized self
if `path` is file location - ZipFile with reference to the file.
"""
import pickle
import shutil
from pathlib import Path
from zipfile import ZipFile
if path is None:
return (type(self), pickle.dumps(self))
if not isinstance(path, (str, Path)):
raise TypeError(
"`path` is expected to either be a string or a Path object "
f"but found of type:{type(path)}."
)
path = Path(path) if isinstance(path, str) else path
path.mkdir()
pickle.dump(type(self), open(path / "_metadata", "wb"))
pickle.dump(self, open(path / "_obj", "wb"))
shutil.make_archive(base_name=path, format="zip", root_dir=path)
shutil.rmtree(path)
return ZipFile(path.with_name(f"{path.stem}.zip"))
@classmethod
def load_from_serial(cls, serial):
"""
Load object from serialized memory container.
Parameters
----------
serial : object
First element of output of `cls.save(None)`.
Returns
-------
deserialized self resulting in output `serial`, of `cls.save(None)`.
"""
import pickle
return pickle.loads(serial)
@classmethod
def load_from_path(cls, serial):
"""
Load object from file location.
Parameters
----------
serial : object
Result of ZipFile(path).open("object).
Returns
-------
deserialized self resulting in output at `path`, of `cls.save(path)`
"""
import pickle
from zipfile import ZipFile
with ZipFile(serial, "r") as file:
return pickle.loads(file.open("_obj").read())
class TagAliaserMixin:
"""
Mixin class for tag aliasing and deprecation of old tags.
To deprecate tags, add the TagAliaserMixin to BaseObject or BaseEstimator.
alias_dict contains the deprecated tags, and supports removal and renaming.
For removal, add an entry "old_tag_name": ""
For renaming, add an entry "old_tag_name": "new_tag_name"
deprecate_dict contains the version number of renaming or removal.
the keys in deprecate_dict should be the same as in alias_dict.
values in deprecate_dict should be strings, the version of removal/renaming.
The class will ensure that new tags alias old tags and vice versa, during
the deprecation period. Informative warnings will be raised whenever the
deprecated tags are being accessed.
When removing tags, ensure to remove the removed tags from this class.
If no tags are deprecated anymore (e.g., all deprecated tags are removed/renamed),
ensure toremove this class as a parent of BaseObject or BaseEstimator.
"""
def __init__(self):
super().__init__()
@classmethod
def get_class_tags(cls):
"""
Get class tags from estimator class and all its parent classes.
Get the tags relating to the class not a particular object.
Returns
-------
collected_tags : dict
Dictionary of tag name : tag value pairs. Collected from _tags
class attribute via nested inheritance. NOT overridden by dynamic
tags set by set_tags or mirror_tags.
See Also
--------
get_tag : Get a single tag from an object.
get_clas_tags : Get all tags from a class.
get_tags : Get all tags from an object.
Examples
--------
>>> from aeon.classification import DummyClassifier
>>> tags = DummyClassifier.get_class_tags()
"""
collected_tags = super().get_class_tags()
collected_tags = cls._complete_dict(collected_tags)
return collected_tags
@classmethod
def get_class_tag(cls, tag_name, tag_value_default=None):
"""
Get tag value from estimator class (only class tags).
Parameters
----------
tag_name : str
Name of tag value.
tag_value_default : any type
Default/fallback value if tag is not found.
Returns
-------
tag_value :
Value of the `tag_name` tag in self. If not found, returns
`tag_value_default`.
See Also
--------
get_tag : Get a single tag from an object.
get_clas_tags : Get all tags from a class.
get_tags : Get all tags from an object.
Examples
--------
>>> from aeon.classification import DummyClassifier
>>> DummyClassifier.get_class_tag("capability:multivariate")
True
"""
cls._deprecate_tag_warn([tag_name])
return super().get_class_tag(
tag_name=tag_name, tag_value_default=tag_value_default
)
def get_tags(self):
"""
Get tags from estimator class and dynamic tag overrides.
Returns
-------
collected_tags : dict
Dictionary of tag name : tag value pairs. Collected from _tags
class attribute via nested inheritance and then any overrides
and new tags from _tags_dynamic object attribute.
"""
collected_tags = super().get_tags()
collected_tags = self._complete_dict(collected_tags)
return collected_tags
def get_tag(self, tag_name, tag_value_default=None, raise_error=True):
"""
Get tag value from estimator class and dynamic tag overrides.
Parameters
----------
tag_name : str
Name of tag to be retrieved.
tag_value_default : any type, default=None
Default/fallback value if tag is not found.
raise_error : bool
whether a ValueError is raised when the tag is not found.
Returns
-------
string or None
Value of the `tag_name` tag in self. If not found, returns an error if
raise_error is True, otherwise it returns `tag_value_default`.
Raises
------
ValueError if raise_error is True i.e. if tag_name is not in self.get_tags(
).keys()
"""
self._deprecate_tag_warn([tag_name])
return super().get_tag(
tag_name=tag_name,
tag_value_default=tag_value_default,
raise_error=raise_error,
)
def set_tags(self, **tag_dict):
"""
Set dynamic tags to given values.
Parameters
----------
tag_dict : dict
Dictionary of tag name : tag value pairs.
Returns
-------
Self :
Reference to self.
Notes
-----
Changes object state by settting tag values in tag_dict as dynamic tags
in self.
"""
self._deprecate_tag_warn(tag_dict.keys())
tag_dict = self._complete_dict(tag_dict)
super().set_tags(**tag_dict)
return self
@classmethod
def _complete_dict(cls, tag_dict):
"""Add all aliased and aliasing tags to the dictionary."""
alias_dict = cls.alias_dict
deprecated_tags = set(tag_dict.keys()).intersection(alias_dict.keys())
new_tags = set(tag_dict.keys()).intersection(alias_dict.values())
if len(deprecated_tags) > 0 or len(new_tags) > 0:
new_tag_dict = deepcopy(tag_dict)
# for all tag strings being set, write the value
# to all tags that could *be aliased by* the string
# and all tags that could be *aliasing* the string
# this way we ensure upwards and downwards compatibility
for old_tag, new_tag in alias_dict.items():
for tag in tag_dict:
if tag == old_tag and new_tag != "":
new_tag_dict[new_tag] = tag_dict[tag]
if tag == new_tag:
new_tag_dict[old_tag] = tag_dict[tag]
return new_tag_dict
else:
return tag_dict
@classmethod
def _deprecate_tag_warn(cls, tags):
"""
Print warning message for tag deprecation.
Parameters
----------
tags : list of str.
Raises
------
DeprecationWarning for each tag in tags that is aliased by cls.alias_dict.
"""
for tag_name in tags:
if tag_name in cls.alias_dict.keys():
version = cls.deprecate_dict[tag_name]
new_tag = cls.alias_dict[tag_name]
msg = f"tag {tag_name!r} will be removed in aeon version {version}"
if new_tag != "":
msg += (
f" and replaced by {new_tag!r}, please use {new_tag!r} instead"
)
else:
msg += ', please remove code that access or sets "{tag_name}"'
warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
class BaseEstimator(BaseObject):
"""Base class for defining estimators in aeon.
Extends aeon's BaseObject to include basic functionality for fittable estimators.
"""
def __init__(self):
self._is_fitted = False
super().__init__()
@property
def is_fitted(self):
"""Whether ``fit`` has been called."""
return self._is_fitted
def check_is_fitted(self):
"""
Check if the estimator has been fitted.
Raises
------
NotFittedError
If the estimator has not been fitted yet.
"""
if not self.is_fitted:
raise NotFittedError(
f"This instance of {self.__class__.__name__} has not "
f"been fitted yet; please call `fit` first."