scikit-base 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- docs/source/conf.py +299 -0
- scikit_base-0.3.0.dist-info/LICENSE +29 -0
- scikit_base-0.3.0.dist-info/METADATA +157 -0
- scikit_base-0.3.0.dist-info/RECORD +37 -0
- scikit_base-0.3.0.dist-info/WHEEL +5 -0
- scikit_base-0.3.0.dist-info/top_level.txt +2 -0
- scikit_base-0.3.0.dist-info/zip-safe +1 -0
- skbase/__init__.py +14 -0
- skbase/_exceptions.py +31 -0
- skbase/base/__init__.py +19 -0
- skbase/base/_base.py +981 -0
- skbase/base/_meta.py +591 -0
- skbase/lookup/__init__.py +31 -0
- skbase/lookup/_lookup.py +1005 -0
- skbase/lookup/tests/__init__.py +2 -0
- skbase/lookup/tests/test_lookup.py +991 -0
- skbase/testing/__init__.py +12 -0
- skbase/testing/test_all_objects.py +796 -0
- skbase/testing/utils/__init__.py +5 -0
- skbase/testing/utils/_conditional_fixtures.py +202 -0
- skbase/testing/utils/_dependencies.py +254 -0
- skbase/testing/utils/deep_equals.py +337 -0
- skbase/testing/utils/inspect.py +30 -0
- skbase/testing/utils/tests/__init__.py +2 -0
- skbase/testing/utils/tests/test_check_dependencies.py +49 -0
- skbase/testing/utils/tests/test_deep_equals.py +63 -0
- skbase/tests/__init__.py +2 -0
- skbase/tests/conftest.py +178 -0
- skbase/tests/mock_package/__init__.py +5 -0
- skbase/tests/mock_package/test_mock_package.py +74 -0
- skbase/tests/test_base.py +1069 -0
- skbase/tests/test_baseestimator.py +126 -0
- skbase/tests/test_exceptions.py +23 -0
- skbase/utils/__init__.py +10 -0
- skbase/utils/_nested_iter.py +95 -0
- skbase/validate/__init__.py +8 -0
- skbase/validate/_types.py +106 -0
skbase/base/_base.py
ADDED
@@ -0,0 +1,981 @@
|
|
1
|
+
# -*- coding: utf-8 -*-
|
2
|
+
# copyright: skbase developers, BSD-3-Clause License (see LICENSE file)
|
3
|
+
# Elements of BaseObject re-use code developed in scikit-learn. These elements
|
4
|
+
# are copyrighted by the scikit-learn developers, BSD-3-Clause License. For
|
5
|
+
# conditions see https://github.com/scikit-learn/scikit-learn/blob/main/COPYING
|
6
|
+
"""Base class template for objects and fittable objects.
|
7
|
+
|
8
|
+
templates in this module:
|
9
|
+
|
10
|
+
BaseObject - object with parameters and tags
|
11
|
+
BaseEstimator - BaseObject that can be fitted
|
12
|
+
|
13
|
+
Interface specifications below.
|
14
|
+
|
15
|
+
---
|
16
|
+
|
17
|
+
class name: BaseObject
|
18
|
+
|
19
|
+
Parameter inspection and setter methods
|
20
|
+
inspect parameter values - get_params()
|
21
|
+
setting parameter values - set_params(**params)
|
22
|
+
list of parameter names - get_param_names()
|
23
|
+
dict of parameter defaults - get_param_defaults()
|
24
|
+
|
25
|
+
Tag inspection and setter methods
|
26
|
+
inspect tags (all) - get_tags()
|
27
|
+
inspect tags (one tag) - get_tag(tag_name: str, tag_value_default=None)
|
28
|
+
inspect tags (class method) - get_class_tags()
|
29
|
+
inspect tags (one tag, class) - get_class_tag(tag_name:str, tag_value_default=None)
|
30
|
+
setting dynamic tags - set_tag(**tag_dict: dict)
|
31
|
+
set/clone dynamic tags - clone_tags(estimator, tag_names=None)
|
32
|
+
|
33
|
+
Blueprinting: resetting and cloning, post-init state with same hyper-parameters
|
34
|
+
reset estimator to post-init - reset()
|
35
|
+
cloneestimator (copy&reset) - clone()
|
36
|
+
|
37
|
+
Testing with default parameters methods
|
38
|
+
getting default parameters (all sets) - get_test_params()
|
39
|
+
get one test instance with default parameters - create_test_instance()
|
40
|
+
get list of all test instances plus name list - create_test_instances_and_names()
|
41
|
+
---
|
42
|
+
|
43
|
+
class name: BaseEstimator
|
44
|
+
|
45
|
+
Provides all interface points of BaseObject, plus:
|
46
|
+
|
47
|
+
Parameter inspection:
|
48
|
+
fitted parameter inspection - get_fitted_params()
|
49
|
+
|
50
|
+
State:
|
51
|
+
fitted model/strategy - by convention, any attributes ending in "_"
|
52
|
+
fitted state flag - is_fitted (property)
|
53
|
+
fitted state check - check_is_fitted (raises error if not is_fitted)
|
54
|
+
"""
|
55
|
+
import inspect
|
56
|
+
import warnings
|
57
|
+
from collections import defaultdict
|
58
|
+
from copy import deepcopy
|
59
|
+
from typing import List
|
60
|
+
|
61
|
+
from sklearn import clone
|
62
|
+
from sklearn.base import BaseEstimator as _BaseEstimator
|
63
|
+
|
64
|
+
from skbase._exceptions import NotFittedError
|
65
|
+
|
66
|
+
__author__: List[str] = ["mloning", "RNKuhns", "fkiraly"]
|
67
|
+
__all__: List[str] = ["BaseEstimator", "BaseObject"]
|
68
|
+
|
69
|
+
|
70
|
+
class BaseObject(_BaseEstimator):
|
71
|
+
"""Base class for parametric objects with sktime style tag interface.
|
72
|
+
|
73
|
+
Extends scikit-learn's BaseEstimator to include sktime style interface for tags.
|
74
|
+
"""
|
75
|
+
|
76
|
+
def __init__(self):
|
77
|
+
self._tags_dynamic = {}
|
78
|
+
super(BaseObject, self).__init__()
|
79
|
+
|
80
|
+
def __eq__(self, other):
|
81
|
+
"""Equality dunder. Checks equal class and parameters.
|
82
|
+
|
83
|
+
Returns True iff result of get_params(deep=False)
|
84
|
+
results in equal parameter sets.
|
85
|
+
|
86
|
+
Nested BaseObject descendants from get_params are compared via __eq__ as well.
|
87
|
+
"""
|
88
|
+
from skbase.testing.utils.deep_equals import deep_equals
|
89
|
+
|
90
|
+
if not isinstance(other, BaseObject):
|
91
|
+
return False
|
92
|
+
|
93
|
+
self_params = self.get_params(deep=False)
|
94
|
+
other_params = other.get_params(deep=False)
|
95
|
+
|
96
|
+
return deep_equals(self_params, other_params)
|
97
|
+
|
98
|
+
def reset(self):
|
99
|
+
"""Reset the object to a clean post-init state.
|
100
|
+
|
101
|
+
Using reset, runs __init__ with current values of hyper-parameters
|
102
|
+
(result of get_params). This Removes any object attributes, except:
|
103
|
+
|
104
|
+
- hyper-parameters = arguments of __init__
|
105
|
+
- object attributes containing double-underscores, i.e., the string "__"
|
106
|
+
|
107
|
+
Class and object methods, and class attributes are also unaffected.
|
108
|
+
|
109
|
+
Returns
|
110
|
+
-------
|
111
|
+
self
|
112
|
+
Instance of class reset to a clean post-init state but retaining
|
113
|
+
the current hyper-parameter values.
|
114
|
+
|
115
|
+
Notes
|
116
|
+
-----
|
117
|
+
Equivalent to sklearn.clone but overwrites self. After self.reset()
|
118
|
+
call, self is equal in value to `type(self)(**self.get_params(deep=False))`
|
119
|
+
"""
|
120
|
+
# retrieve parameters to copy them later
|
121
|
+
params = self.get_params(deep=False)
|
122
|
+
|
123
|
+
# delete all object attributes in self
|
124
|
+
attrs = [attr for attr in dir(self) if "__" not in attr]
|
125
|
+
cls_attrs = list(dir(type(self)))
|
126
|
+
self_attrs = set(attrs).difference(cls_attrs)
|
127
|
+
for attr in self_attrs:
|
128
|
+
delattr(self, attr)
|
129
|
+
|
130
|
+
# run init with a copy of parameters self had at the start
|
131
|
+
self.__init__(**params)
|
132
|
+
|
133
|
+
return self
|
134
|
+
|
135
|
+
def clone(self):
|
136
|
+
"""Obtain a clone of the object with same hyper-parameters.
|
137
|
+
|
138
|
+
A clone is a different object without shared references, in post-init state.
|
139
|
+
This function is equivalent to returning sklearn.clone of self.
|
140
|
+
|
141
|
+
Notes
|
142
|
+
-----
|
143
|
+
Also equal in value to `type(self)(**self.get_params(deep=False))`.
|
144
|
+
"""
|
145
|
+
return clone(self)
|
146
|
+
|
147
|
+
@classmethod
|
148
|
+
def _get_init_signature(cls):
|
149
|
+
"""Get class init sigature.
|
150
|
+
|
151
|
+
Useful in parameter inspection.
|
152
|
+
|
153
|
+
Returns
|
154
|
+
-------
|
155
|
+
List
|
156
|
+
The inspected parameter objects (including defaults).
|
157
|
+
|
158
|
+
Raises
|
159
|
+
------
|
160
|
+
RuntimeError if cls has varargs in __init__.
|
161
|
+
"""
|
162
|
+
# fetch the constructor or the original constructor before
|
163
|
+
# deprecation wrapping if any
|
164
|
+
init = getattr(cls.__init__, "deprecated_original", cls.__init__)
|
165
|
+
if init is object.__init__:
|
166
|
+
# No explicit constructor to introspect
|
167
|
+
return []
|
168
|
+
|
169
|
+
# introspect the constructor arguments to find the model parameters
|
170
|
+
# to represent
|
171
|
+
init_signature = inspect.signature(init)
|
172
|
+
|
173
|
+
# Consider the constructor parameters excluding 'self'
|
174
|
+
parameters = [
|
175
|
+
p
|
176
|
+
for p in init_signature.parameters.values()
|
177
|
+
if p.name != "self" and p.kind != p.VAR_KEYWORD
|
178
|
+
]
|
179
|
+
for p in parameters:
|
180
|
+
if p.kind == p.VAR_POSITIONAL:
|
181
|
+
raise RuntimeError(
|
182
|
+
"scikit-learn compatible estimators should always "
|
183
|
+
"specify their parameters in the signature"
|
184
|
+
" of their __init__ (no varargs)."
|
185
|
+
" %s with constructor %s doesn't "
|
186
|
+
" follow this convention." % (cls, init_signature)
|
187
|
+
)
|
188
|
+
return parameters
|
189
|
+
|
190
|
+
@classmethod
|
191
|
+
def get_param_names(cls):
|
192
|
+
"""Get object's parameter names.
|
193
|
+
|
194
|
+
Returns
|
195
|
+
-------
|
196
|
+
param_names: list[str]
|
197
|
+
Alphabetically sorted list of parameter names of cls.
|
198
|
+
"""
|
199
|
+
parameters = cls._get_init_signature()
|
200
|
+
param_names = sorted([p.name for p in parameters])
|
201
|
+
return param_names
|
202
|
+
|
203
|
+
@classmethod
|
204
|
+
def get_param_defaults(cls):
|
205
|
+
"""Get object's parameter defaults.
|
206
|
+
|
207
|
+
Returns
|
208
|
+
-------
|
209
|
+
default_dict: dict[str, Any]
|
210
|
+
Keys are all parameters of cls that have a default defined in __init__
|
211
|
+
values are the defaults, as defined in __init__.
|
212
|
+
"""
|
213
|
+
parameters = cls._get_init_signature()
|
214
|
+
default_dict = {
|
215
|
+
x.name: x.default for x in parameters if x.default != inspect._empty
|
216
|
+
}
|
217
|
+
return default_dict
|
218
|
+
|
219
|
+
def set_params(self, **params):
|
220
|
+
"""Set the parameters of this object.
|
221
|
+
|
222
|
+
The method works on simple estimators as well as on nested objects.
|
223
|
+
The latter have parameters of the form ``<component>__<parameter>`` so
|
224
|
+
that it's possible to update each component of a nested object.
|
225
|
+
|
226
|
+
Parameters
|
227
|
+
----------
|
228
|
+
**params : dict
|
229
|
+
BaseObject parameters.
|
230
|
+
|
231
|
+
Returns
|
232
|
+
-------
|
233
|
+
self
|
234
|
+
Reference to self (after parameters have been set).
|
235
|
+
"""
|
236
|
+
if not params:
|
237
|
+
# Simple optimization to gain speed (inspect is slow)
|
238
|
+
return self
|
239
|
+
valid_params = self.get_params(deep=True)
|
240
|
+
|
241
|
+
nested_params = defaultdict(dict) # grouped by prefix
|
242
|
+
for key, value in params.items():
|
243
|
+
key, delim, sub_key = key.partition("__")
|
244
|
+
if key not in valid_params:
|
245
|
+
raise ValueError(
|
246
|
+
"Invalid parameter %s for object %s. "
|
247
|
+
"Check the list of available parameters "
|
248
|
+
"with `object.get_params().keys()`." % (key, self)
|
249
|
+
)
|
250
|
+
|
251
|
+
if delim:
|
252
|
+
nested_params[key][sub_key] = value
|
253
|
+
else:
|
254
|
+
setattr(self, key, value)
|
255
|
+
valid_params[key] = value
|
256
|
+
|
257
|
+
self.reset()
|
258
|
+
|
259
|
+
# recurse in components
|
260
|
+
for key, sub_params in nested_params.items():
|
261
|
+
valid_params[key].set_params(**sub_params)
|
262
|
+
|
263
|
+
return self
|
264
|
+
|
265
|
+
@classmethod
|
266
|
+
def get_class_tags(cls):
|
267
|
+
"""Get class tags from the class and all its parent classes.
|
268
|
+
|
269
|
+
Retrieves tag: value pairs from _tags class attribute. Does not return
|
270
|
+
information from dynamic tags (set via set_tags or clone_tags)
|
271
|
+
that are defined on instances.
|
272
|
+
|
273
|
+
Returns
|
274
|
+
-------
|
275
|
+
collected_tags : dict
|
276
|
+
Dictionary of class tag name: tag value pairs. Collected from _tags
|
277
|
+
class attribute via nested inheritance.
|
278
|
+
"""
|
279
|
+
collected_tags = {}
|
280
|
+
|
281
|
+
# We exclude the last two parent classes: sklearn.base.BaseEstimator and
|
282
|
+
# the basic Python object.
|
283
|
+
for parent_class in reversed(inspect.getmro(cls)[:-2]):
|
284
|
+
if hasattr(parent_class, "_tags"):
|
285
|
+
# Need the if here because mixins might not have _more_tags
|
286
|
+
# but might do redundant work in estimators
|
287
|
+
# (i.e. calling more tags on BaseEstimator multiple times)
|
288
|
+
more_tags = parent_class._tags
|
289
|
+
collected_tags.update(more_tags)
|
290
|
+
|
291
|
+
return deepcopy(collected_tags)
|
292
|
+
|
293
|
+
@classmethod
|
294
|
+
def get_class_tag(cls, tag_name, tag_value_default=None):
|
295
|
+
"""Get a class tag's value.
|
296
|
+
|
297
|
+
Does not return information from dynamic tags (set via set_tags or clone_tags)
|
298
|
+
that are defined on instances.
|
299
|
+
|
300
|
+
Parameters
|
301
|
+
----------
|
302
|
+
tag_name : str
|
303
|
+
Name of tag value.
|
304
|
+
tag_value_default : any
|
305
|
+
Default/fallback value if tag is not found.
|
306
|
+
|
307
|
+
Returns
|
308
|
+
-------
|
309
|
+
tag_value :
|
310
|
+
Value of the `tag_name` tag in self. If not found, returns
|
311
|
+
`tag_value_default`.
|
312
|
+
"""
|
313
|
+
collected_tags = cls.get_class_tags()
|
314
|
+
|
315
|
+
return collected_tags.get(tag_name, tag_value_default)
|
316
|
+
|
317
|
+
def get_tags(self):
|
318
|
+
"""Get tags from estimator class and dynamic tag overrides.
|
319
|
+
|
320
|
+
Returns
|
321
|
+
-------
|
322
|
+
collected_tags : dict
|
323
|
+
Dictionary of tag name : tag value pairs. Collected from _tags
|
324
|
+
class attribute via nested inheritance and then any overrides
|
325
|
+
and new tags from _tags_dynamic object attribute.
|
326
|
+
"""
|
327
|
+
collected_tags = self.get_class_tags()
|
328
|
+
|
329
|
+
if hasattr(self, "_tags_dynamic"):
|
330
|
+
collected_tags.update(self._tags_dynamic)
|
331
|
+
|
332
|
+
return deepcopy(collected_tags)
|
333
|
+
|
334
|
+
def get_tag(self, tag_name, tag_value_default=None, raise_error=True):
|
335
|
+
"""Get tag value from estimator class and dynamic tag overrides.
|
336
|
+
|
337
|
+
Parameters
|
338
|
+
----------
|
339
|
+
tag_name : str
|
340
|
+
Name of tag to be retrieved
|
341
|
+
tag_value_default : any type, optional; default=None
|
342
|
+
Default/fallback value if tag is not found
|
343
|
+
raise_error : bool
|
344
|
+
whether a ValueError is raised when the tag is not found
|
345
|
+
|
346
|
+
Returns
|
347
|
+
-------
|
348
|
+
tag_value : Any
|
349
|
+
Value of the `tag_name` tag in self. If not found, returns an error if
|
350
|
+
`raise_error` is True, otherwise it returns `tag_value_default`.
|
351
|
+
|
352
|
+
Raises
|
353
|
+
------
|
354
|
+
ValueError if raise_error is True i.e. if `tag_name` is not in
|
355
|
+
self.get_tags().keys()
|
356
|
+
"""
|
357
|
+
collected_tags = self.get_tags()
|
358
|
+
|
359
|
+
tag_value = collected_tags.get(tag_name, tag_value_default)
|
360
|
+
|
361
|
+
if raise_error and tag_name not in collected_tags.keys():
|
362
|
+
raise ValueError(f"Tag with name {tag_name} could not be found.")
|
363
|
+
|
364
|
+
return tag_value
|
365
|
+
|
366
|
+
def set_tags(self, **tag_dict):
|
367
|
+
"""Set dynamic tags to given values.
|
368
|
+
|
369
|
+
Parameters
|
370
|
+
----------
|
371
|
+
**tag_dict : dict
|
372
|
+
Dictionary of tag name: tag value pairs.
|
373
|
+
|
374
|
+
Returns
|
375
|
+
-------
|
376
|
+
Self
|
377
|
+
Reference to self.
|
378
|
+
|
379
|
+
Notes
|
380
|
+
-----
|
381
|
+
Changes object state by settting tag values in tag_dict as dynamic tags in self.
|
382
|
+
"""
|
383
|
+
tag_update = deepcopy(tag_dict)
|
384
|
+
if hasattr(self, "_tags_dynamic"):
|
385
|
+
self._tags_dynamic.update(tag_update)
|
386
|
+
else:
|
387
|
+
self._tags_dynamic = tag_update
|
388
|
+
|
389
|
+
return self
|
390
|
+
|
391
|
+
def clone_tags(self, estimator, tag_names=None):
|
392
|
+
"""Clone tags from another estimator as dynamic override.
|
393
|
+
|
394
|
+
Parameters
|
395
|
+
----------
|
396
|
+
estimator : estimator inheriting from :class:BaseEstimator
|
397
|
+
tag_names : str or list of str, default = None
|
398
|
+
Names of tags to clone. If None then all tags in estimator are used
|
399
|
+
as `tag_names`.
|
400
|
+
|
401
|
+
Returns
|
402
|
+
-------
|
403
|
+
Self :
|
404
|
+
Reference to self.
|
405
|
+
|
406
|
+
Notes
|
407
|
+
-----
|
408
|
+
Changes object state by setting tag values in tag_set from estimator as
|
409
|
+
dynamic tags in self.
|
410
|
+
"""
|
411
|
+
tags_est = deepcopy(estimator.get_tags())
|
412
|
+
|
413
|
+
# if tag_set is not passed, default is all tags in estimator
|
414
|
+
if tag_names is None:
|
415
|
+
tag_names = tags_est.keys()
|
416
|
+
else:
|
417
|
+
# if tag_set is passed, intersect keys with tags in estimator
|
418
|
+
if not isinstance(tag_names, list):
|
419
|
+
tag_names = [tag_names]
|
420
|
+
tag_names = [key for key in tag_names if key in tags_est.keys()]
|
421
|
+
|
422
|
+
update_dict = {key: tags_est[key] for key in tag_names}
|
423
|
+
|
424
|
+
self.set_tags(**update_dict)
|
425
|
+
|
426
|
+
return self
|
427
|
+
|
428
|
+
@classmethod
|
429
|
+
def get_test_params(cls, parameter_set="default"):
|
430
|
+
"""Return testing parameter settings for the estimator.
|
431
|
+
|
432
|
+
Parameters
|
433
|
+
----------
|
434
|
+
parameter_set : str, default="default"
|
435
|
+
Name of the set of test parameters to return, for use in tests. If no
|
436
|
+
special parameters are defined for a value, will return `"default"` set.
|
437
|
+
|
438
|
+
Returns
|
439
|
+
-------
|
440
|
+
params : dict or list of dict, default = {}
|
441
|
+
Parameters to create testing instances of the class
|
442
|
+
Each dict are parameters to construct an "interesting" test instance, i.e.,
|
443
|
+
`MyClass(**params)` or `MyClass(**params[i])` creates a valid test instance.
|
444
|
+
`create_test_instance` uses the first (or only) dictionary in `params`
|
445
|
+
"""
|
446
|
+
# if non-default parameters are required, but none have been found, raise error
|
447
|
+
if hasattr(cls, "_required_parameters"):
|
448
|
+
required_parameters = getattr(cls, "_required_parameters", [])
|
449
|
+
if len(required_parameters) > 0:
|
450
|
+
raise ValueError(
|
451
|
+
f"Estimator: {cls} requires "
|
452
|
+
f"non-default parameters for construction, "
|
453
|
+
f"but none were given. Please set them "
|
454
|
+
f"as given in the extension template"
|
455
|
+
)
|
456
|
+
|
457
|
+
# construct with parameter configuration for testing, otherwise construct with
|
458
|
+
# default parameters (empty dict)
|
459
|
+
params = {}
|
460
|
+
return params
|
461
|
+
|
462
|
+
@classmethod
|
463
|
+
def create_test_instance(cls, parameter_set="default"):
|
464
|
+
"""Construct Estimator instance if possible.
|
465
|
+
|
466
|
+
Parameters
|
467
|
+
----------
|
468
|
+
parameter_set : str, default="default"
|
469
|
+
Name of the set of test parameters to return, for use in tests. If no
|
470
|
+
special parameters are defined for a value, will return `"default"` set.
|
471
|
+
|
472
|
+
Returns
|
473
|
+
-------
|
474
|
+
instance : instance of the class with default parameters
|
475
|
+
|
476
|
+
Notes
|
477
|
+
-----
|
478
|
+
`get_test_params` can return dict or list of dict.
|
479
|
+
This function takes first or single dict that get_test_params returns, and
|
480
|
+
constructs the object with that.
|
481
|
+
"""
|
482
|
+
if "parameter_set" in inspect.getfullargspec(cls.get_test_params).args:
|
483
|
+
params = cls.get_test_params(parameter_set=parameter_set)
|
484
|
+
else:
|
485
|
+
params = cls.get_test_params()
|
486
|
+
|
487
|
+
if isinstance(params, list) and isinstance(params[0], dict):
|
488
|
+
params = params[0]
|
489
|
+
elif isinstance(params, dict):
|
490
|
+
pass
|
491
|
+
else:
|
492
|
+
raise TypeError(
|
493
|
+
"get_test_params should either return a dict or list of dict."
|
494
|
+
)
|
495
|
+
|
496
|
+
return cls(**params)
|
497
|
+
|
498
|
+
@classmethod
|
499
|
+
def create_test_instances_and_names(cls, parameter_set="default"):
|
500
|
+
"""Create list of all test instances and a list of names for them.
|
501
|
+
|
502
|
+
Parameters
|
503
|
+
----------
|
504
|
+
parameter_set : str, default="default"
|
505
|
+
Name of the set of test parameters to return, for use in tests. If no
|
506
|
+
special parameters are defined for a value, will return `"default"` set.
|
507
|
+
|
508
|
+
Returns
|
509
|
+
-------
|
510
|
+
objs : list of instances of cls
|
511
|
+
i-th instance is cls(**cls.get_test_params()[i])
|
512
|
+
names : list of str, same length as objs
|
513
|
+
i-th element is name of i-th instance of obj in tests
|
514
|
+
convention is {cls.__name__}-{i} if more than one instance
|
515
|
+
otherwise {cls.__name__}
|
516
|
+
parameter_set : str, default="default"
|
517
|
+
Name of the set of test parameters to return, for use in tests. If no
|
518
|
+
special parameters are defined for a value, will return `"default"` set.
|
519
|
+
"""
|
520
|
+
if "parameter_set" in inspect.getfullargspec(cls.get_test_params).args:
|
521
|
+
param_list = cls.get_test_params(parameter_set=parameter_set)
|
522
|
+
else:
|
523
|
+
param_list = cls.get_test_params()
|
524
|
+
|
525
|
+
objs = []
|
526
|
+
if not isinstance(param_list, (dict, list)):
|
527
|
+
raise RuntimeError(
|
528
|
+
f"Error in {cls.__name__}.get_test_params, "
|
529
|
+
"return must be param dict for class, or list thereof"
|
530
|
+
)
|
531
|
+
if isinstance(param_list, dict):
|
532
|
+
param_list = [param_list]
|
533
|
+
for params in param_list:
|
534
|
+
if not isinstance(params, dict):
|
535
|
+
raise RuntimeError(
|
536
|
+
f"Error in {cls.__name__}.get_test_params, "
|
537
|
+
"return must be param dict for class, or list thereof"
|
538
|
+
)
|
539
|
+
objs += [cls(**params)]
|
540
|
+
|
541
|
+
num_instances = len(param_list)
|
542
|
+
if num_instances > 1:
|
543
|
+
names = [cls.__name__ + "-" + str(i) for i in range(num_instances)]
|
544
|
+
else:
|
545
|
+
names = [cls.__name__]
|
546
|
+
|
547
|
+
return objs, names
|
548
|
+
|
549
|
+
@classmethod
|
550
|
+
def _has_implementation_of(cls, method):
|
551
|
+
"""Check if method has a concrete implementation in this class.
|
552
|
+
|
553
|
+
This assumes that having an implementation is equivalent to
|
554
|
+
one or more overrides of `method` in the method resolution order.
|
555
|
+
|
556
|
+
Parameters
|
557
|
+
----------
|
558
|
+
method : str, name of method to check implementation of
|
559
|
+
|
560
|
+
Returns
|
561
|
+
-------
|
562
|
+
bool, whether method has implementation in cls
|
563
|
+
True if cls.method has been overridden at least once in
|
564
|
+
the inheritance tree (according to method resolution order)
|
565
|
+
"""
|
566
|
+
# walk through method resolution order and inspect methods
|
567
|
+
# of classes and direct parents, "adjacent" classes in mro
|
568
|
+
mro = inspect.getmro(cls)
|
569
|
+
# collect all methods that are not none
|
570
|
+
methods = [getattr(c, method, None) for c in mro]
|
571
|
+
methods = [m for m in methods if m is not None]
|
572
|
+
|
573
|
+
for i in range(len(methods) - 1):
|
574
|
+
# the method has been overridden once iff
|
575
|
+
# at least two of the methods collected are not equal
|
576
|
+
# equivalently: some two adjacent methods are not equal
|
577
|
+
overridden = methods[i] != methods[i + 1]
|
578
|
+
if overridden:
|
579
|
+
return True
|
580
|
+
|
581
|
+
return False
|
582
|
+
|
583
|
+
def is_composite(self):
|
584
|
+
"""Check if the object is composed of other BaseObjects.
|
585
|
+
|
586
|
+
A composite object is an object which contains objects, as parameters.
|
587
|
+
Called on an instance, since this may differ by instance.
|
588
|
+
|
589
|
+
Returns
|
590
|
+
-------
|
591
|
+
composite: bool
|
592
|
+
Whether an object has any parameters whose values
|
593
|
+
are BaseObjects.
|
594
|
+
"""
|
595
|
+
# walk through method resolution order and inspect methods
|
596
|
+
# of classes and direct parents, "adjacent" classes in mro
|
597
|
+
params = self.get_params(deep=False)
|
598
|
+
composite = any(isinstance(x, BaseObject) for x in params.values())
|
599
|
+
|
600
|
+
return composite
|
601
|
+
|
602
|
+
def _components(self, base_class=None):
|
603
|
+
"""Return references to all state changing BaseObject type attributes.
|
604
|
+
|
605
|
+
This *excludes* the blue-print-like components passed in the __init__.
|
606
|
+
|
607
|
+
Caution: this method returns *references* and not *copies*.
|
608
|
+
Writing to the reference will change the respective attribute of self.
|
609
|
+
|
610
|
+
Parameters
|
611
|
+
----------
|
612
|
+
base_class : class, optional, default=None, must be subclass of BaseObject
|
613
|
+
if not None, sub-sets return dict to only descendants of base_class
|
614
|
+
|
615
|
+
Returns
|
616
|
+
-------
|
617
|
+
dict with key = attribute name, value = reference to that BaseObject attribute
|
618
|
+
dict contains all attributes of self that inherit from BaseObjects, and:
|
619
|
+
whose names do not contain the string "__", e.g., hidden attributes
|
620
|
+
are not class attributes, and are not hyper-parameters (__init__ args)
|
621
|
+
"""
|
622
|
+
if base_class is None:
|
623
|
+
base_class = BaseObject
|
624
|
+
if base_class is not None and not inspect.isclass(base_class):
|
625
|
+
raise TypeError(f"base_class must be a class, but found {type(base_class)}")
|
626
|
+
if base_class is not None and not issubclass(base_class, BaseObject):
|
627
|
+
raise TypeError("base_class must be a subclass of BaseObject")
|
628
|
+
|
629
|
+
# retrieve parameter names to exclude them later
|
630
|
+
param_names = self.get_params(deep=False).keys()
|
631
|
+
|
632
|
+
# retrieve all attributes that are BaseObject descendants
|
633
|
+
attrs = [attr for attr in dir(self) if "__" not in attr]
|
634
|
+
cls_attrs = list(dir(type(self)))
|
635
|
+
self_attrs = set(attrs).difference(cls_attrs).difference(param_names)
|
636
|
+
|
637
|
+
comp_dict = {x: getattr(self, x) for x in self_attrs}
|
638
|
+
comp_dict = {x: y for (x, y) in comp_dict.items() if isinstance(y, base_class)}
|
639
|
+
|
640
|
+
return comp_dict
|
641
|
+
|
642
|
+
|
643
|
+
class TagAliaserMixin:
|
644
|
+
"""Mixin class for tag aliasing and deprecation of old tags.
|
645
|
+
|
646
|
+
To deprecate tags, add the TagAliaserMixin to BaseObject or BaseEstimator.
|
647
|
+
alias_dict contains the deprecated tags, and supports removal and renaming.
|
648
|
+
For removal, add an entry "old_tag_name": ""
|
649
|
+
For renaming, add an entry "old_tag_name": "new_tag_name"
|
650
|
+
deprecate_dict contains the version number of renaming or removal.
|
651
|
+
the keys in deprecate_dict should be the same as in alias_dict.
|
652
|
+
values in deprecate_dict should be strings, the version of removal/renaming.
|
653
|
+
|
654
|
+
The class will ensure that new tags alias old tags and vice versa, during
|
655
|
+
the deprecation period. Informative warnings will be raised whenever the
|
656
|
+
deprecated tags are being accessed.
|
657
|
+
|
658
|
+
When removing tags, ensure to remove the removed tags from this class.
|
659
|
+
If no tags are deprecated anymore (e.g., all deprecated tags are removed/renamed),
|
660
|
+
ensure toremove this class as a parent of BaseObject or BaseEstimator.
|
661
|
+
"""
|
662
|
+
|
663
|
+
# dictionary of aliases
|
664
|
+
# key = old tag; value = new tag, aliased by old tag
|
665
|
+
# override this in a child class
|
666
|
+
alias_dict = {"old_tag": "new_tag", "tag_to_remove": ""}
|
667
|
+
|
668
|
+
# dictionary of removal version
|
669
|
+
# key = old tag; value = version in which tag will be removed, as string
|
670
|
+
deprecate_dict = {"old_tag": "0.12.0", "tag_to_remove": "99.99.99"}
|
671
|
+
|
672
|
+
def __init__(self):
|
673
|
+
super(TagAliaserMixin, self).__init__()
|
674
|
+
|
675
|
+
@classmethod
|
676
|
+
def get_class_tags(cls):
|
677
|
+
"""Get class tags from estimator class and all its parent classes.
|
678
|
+
|
679
|
+
Returns
|
680
|
+
-------
|
681
|
+
collected_tags : dict
|
682
|
+
Dictionary of tag name : tag value pairs. Collected from _tags
|
683
|
+
class attribute via nested inheritance. NOT overridden by dynamic
|
684
|
+
tags set by set_tags or mirror_tags.
|
685
|
+
"""
|
686
|
+
collected_tags = super(TagAliaserMixin, cls).get_class_tags()
|
687
|
+
collected_tags = cls._complete_dict(collected_tags)
|
688
|
+
return collected_tags
|
689
|
+
|
690
|
+
@classmethod
|
691
|
+
def get_class_tag(cls, tag_name, tag_value_default=None):
|
692
|
+
"""Get tag value from estimator class (only class tags).
|
693
|
+
|
694
|
+
Parameters
|
695
|
+
----------
|
696
|
+
tag_name : str
|
697
|
+
Name of tag value.
|
698
|
+
tag_value_default : any type
|
699
|
+
Default/fallback value if tag is not found.
|
700
|
+
|
701
|
+
Returns
|
702
|
+
-------
|
703
|
+
tag_value :
|
704
|
+
Value of the `tag_name` tag in self. If not found, returns
|
705
|
+
`tag_value_default`.
|
706
|
+
"""
|
707
|
+
cls._deprecate_tag_warn([tag_name])
|
708
|
+
return super(TagAliaserMixin, cls).get_class_tag(
|
709
|
+
tag_name=tag_name, tag_value_default=tag_value_default
|
710
|
+
)
|
711
|
+
|
712
|
+
def get_tags(self):
|
713
|
+
"""Get tags from estimator class and dynamic tag overrides.
|
714
|
+
|
715
|
+
Returns
|
716
|
+
-------
|
717
|
+
collected_tags : dict
|
718
|
+
Dictionary of tag name : tag value pairs. Collected from _tags
|
719
|
+
class attribute via nested inheritance and then any overrides
|
720
|
+
and new tags from _tags_dynamic object attribute.
|
721
|
+
"""
|
722
|
+
collected_tags = super(TagAliaserMixin, self).get_tags()
|
723
|
+
collected_tags = self._complete_dict(collected_tags)
|
724
|
+
return collected_tags
|
725
|
+
|
726
|
+
def get_tag(self, tag_name, tag_value_default=None, raise_error=True):
|
727
|
+
"""Get tag value from estimator class and dynamic tag overrides.
|
728
|
+
|
729
|
+
Parameters
|
730
|
+
----------
|
731
|
+
tag_name : str
|
732
|
+
Name of tag to be retrieved
|
733
|
+
tag_value_default : any type, optional; default=None
|
734
|
+
Default/fallback value if tag is not found
|
735
|
+
raise_error : bool
|
736
|
+
whether a ValueError is raised when the tag is not found
|
737
|
+
|
738
|
+
Returns
|
739
|
+
-------
|
740
|
+
tag_value :
|
741
|
+
Value of the `tag_name` tag in self. If not found, returns an error if
|
742
|
+
raise_error is True, otherwise it returns `tag_value_default`.
|
743
|
+
|
744
|
+
Raises
|
745
|
+
------
|
746
|
+
ValueError if raise_error is True i.e. if tag_name is not in self.get_tags(
|
747
|
+
).keys()
|
748
|
+
"""
|
749
|
+
self._deprecate_tag_warn([tag_name])
|
750
|
+
return super(TagAliaserMixin, self).get_tag(
|
751
|
+
tag_name=tag_name,
|
752
|
+
tag_value_default=tag_value_default,
|
753
|
+
raise_error=raise_error,
|
754
|
+
)
|
755
|
+
|
756
|
+
def set_tags(self, **tag_dict):
|
757
|
+
"""Set dynamic tags to given values.
|
758
|
+
|
759
|
+
Parameters
|
760
|
+
----------
|
761
|
+
tag_dict : dict
|
762
|
+
Dictionary of tag name : tag value pairs.
|
763
|
+
|
764
|
+
Returns
|
765
|
+
-------
|
766
|
+
Self :
|
767
|
+
Reference to self.
|
768
|
+
|
769
|
+
Notes
|
770
|
+
-----
|
771
|
+
Changes object state by settting tag values in tag_dict as dynamic tags
|
772
|
+
in self.
|
773
|
+
"""
|
774
|
+
self._deprecate_tag_warn(tag_dict.keys())
|
775
|
+
|
776
|
+
tag_dict = self._complete_dict(tag_dict)
|
777
|
+
super(TagAliaserMixin, self).set_tags(**tag_dict)
|
778
|
+
return self
|
779
|
+
|
780
|
+
@classmethod
|
781
|
+
def _complete_dict(cls, tag_dict):
|
782
|
+
"""Add all aliased and aliasing tags to the dictionary."""
|
783
|
+
alias_dict = cls.alias_dict
|
784
|
+
deprecated_tags = set(tag_dict.keys()).intersection(alias_dict.keys())
|
785
|
+
new_tags = set(tag_dict.keys()).intersection(alias_dict.values())
|
786
|
+
|
787
|
+
if len(deprecated_tags) > 0 or len(new_tags) > 0:
|
788
|
+
new_tag_dict = deepcopy(tag_dict)
|
789
|
+
# for all tag strings being set, write the value
|
790
|
+
# to all tags that could *be aliased by* the string
|
791
|
+
# and all tags that could be *aliasing* the string
|
792
|
+
# this way we ensure upwards and downwards compatibility
|
793
|
+
for old_tag, new_tag in alias_dict.items():
|
794
|
+
for tag in tag_dict:
|
795
|
+
if tag == old_tag and new_tag != "":
|
796
|
+
new_tag_dict[new_tag] = tag_dict[tag]
|
797
|
+
if tag == new_tag:
|
798
|
+
new_tag_dict[old_tag] = tag_dict[tag]
|
799
|
+
return new_tag_dict
|
800
|
+
else:
|
801
|
+
return tag_dict
|
802
|
+
|
803
|
+
@classmethod
|
804
|
+
def _deprecate_tag_warn(cls, tags):
|
805
|
+
"""Print warning message for tag deprecation.
|
806
|
+
|
807
|
+
Parameters
|
808
|
+
----------
|
809
|
+
tags : list of str
|
810
|
+
|
811
|
+
Raises
|
812
|
+
------
|
813
|
+
DeprecationWarning for each tag in tags that is aliased by cls.alias_dict
|
814
|
+
"""
|
815
|
+
for tag_name in tags:
|
816
|
+
if tag_name in cls.alias_dict.keys():
|
817
|
+
version = cls.deprecate_dict[tag_name]
|
818
|
+
new_tag = cls.alias_dict[tag_name]
|
819
|
+
msg = f'tag "{tag_name}" will be removed in sktime version {version}'
|
820
|
+
if new_tag != "":
|
821
|
+
msg += (
|
822
|
+
f' and replaced by "{new_tag}", please use "{new_tag}" instead'
|
823
|
+
)
|
824
|
+
else:
|
825
|
+
msg += ', please remove code that access or sets "{tag_name}"'
|
826
|
+
warnings.warn(msg, category=DeprecationWarning)
|
827
|
+
|
828
|
+
|
829
|
+
class BaseEstimator(BaseObject):
|
830
|
+
"""Base class for estimators with scikit-learn and sktime design patterns.
|
831
|
+
|
832
|
+
Extends BaseObject to include basic functionality for fittable estimators.
|
833
|
+
"""
|
834
|
+
|
835
|
+
# tuple of non-BaseObject classes that count as nested objects
|
836
|
+
# get_fitted_params will retrieve parameters from these, too
|
837
|
+
# override in descendant class - common choice: BaseEstimator from sklearn
|
838
|
+
GET_FITTED_PARAMS_NESTING = ()
|
839
|
+
|
840
|
+
def __init__(self):
|
841
|
+
"""Construct BaseEstimator."""
|
842
|
+
self._is_fitted = False
|
843
|
+
super(BaseEstimator, self).__init__()
|
844
|
+
|
845
|
+
@property
|
846
|
+
def is_fitted(self):
|
847
|
+
"""Whether `fit` has been called.
|
848
|
+
|
849
|
+
Inspects object's `_is_fitted` attribute that should initialize to False
|
850
|
+
during object construction, and be set to True in calls to an object's
|
851
|
+
`fit` method.
|
852
|
+
|
853
|
+
Returns
|
854
|
+
-------
|
855
|
+
bool
|
856
|
+
Whether the estimator has been `fit`.
|
857
|
+
"""
|
858
|
+
return self._is_fitted
|
859
|
+
|
860
|
+
def check_is_fitted(self):
|
861
|
+
"""Check if the estimator has been fitted.
|
862
|
+
|
863
|
+
Inspects object's `_is_fitted` attribute that should initialize to False
|
864
|
+
during object construction, and be set to True in calls to an object's
|
865
|
+
`fit` method.
|
866
|
+
|
867
|
+
Raises
|
868
|
+
------
|
869
|
+
NotFittedError
|
870
|
+
If the estimator has not been fitted yet.
|
871
|
+
"""
|
872
|
+
if not self.is_fitted:
|
873
|
+
raise NotFittedError(
|
874
|
+
f"This instance of {self.__class__.__name__} has not been fitted yet. "
|
875
|
+
f"Please call `fit` first."
|
876
|
+
)
|
877
|
+
|
878
|
+
def get_fitted_params(self):
|
879
|
+
"""Get fitted parameters.
|
880
|
+
|
881
|
+
State required:
|
882
|
+
Requires state to be "fitted".
|
883
|
+
|
884
|
+
Returns
|
885
|
+
-------
|
886
|
+
fitted_params : dict of fitted parameters, keys are str names of parameters
|
887
|
+
parameters of components are indexed as [componentname]__[paramname]
|
888
|
+
"""
|
889
|
+
if not self.is_fitted:
|
890
|
+
raise NotFittedError(
|
891
|
+
f"estimator of type {type(self).__name__} has not been "
|
892
|
+
"fitted yet, please call fit on data before get_fitted_params"
|
893
|
+
)
|
894
|
+
|
895
|
+
fitted_params = {}
|
896
|
+
|
897
|
+
def sh(x):
|
898
|
+
"""Shorthand to remove all underscores at end of a string."""
|
899
|
+
if x.endswith("_"):
|
900
|
+
return sh(x[:-1])
|
901
|
+
else:
|
902
|
+
return x
|
903
|
+
|
904
|
+
# add all nested parameters from components that are skbase BaseEstimator
|
905
|
+
c_dict = self._components()
|
906
|
+
for c, comp in c_dict.items():
|
907
|
+
if isinstance(comp, BaseEstimator) and comp._is_fitted:
|
908
|
+
c_f_params = comp.get_fitted_params()
|
909
|
+
c_f_params = {f"{sh(c)}__{k}": v for k, v in c_f_params.items()}
|
910
|
+
fitted_params.update(c_f_params)
|
911
|
+
|
912
|
+
# add non-nested fitted params of self
|
913
|
+
fitted_params.update(self._get_fitted_params())
|
914
|
+
|
915
|
+
# add all nested parameters from components that are sklearn estimators
|
916
|
+
# we do this recursively as we have to reach into nested sklearn estimators
|
917
|
+
any_components_left_to_process = True
|
918
|
+
old_new_params = fitted_params
|
919
|
+
# this loop recursively and iteratively processes components inside components
|
920
|
+
while any_components_left_to_process:
|
921
|
+
new_params = {}
|
922
|
+
for c, comp in old_new_params.items():
|
923
|
+
if isinstance(comp, self.GET_FITTED_PARAMS_NESTING):
|
924
|
+
c_f_params = self._get_fitted_params_default(comp)
|
925
|
+
c_f_params = {f"{sh(c)}__{k}": v for k, v in c_f_params.items()}
|
926
|
+
new_params.update(c_f_params)
|
927
|
+
fitted_params.update(new_params)
|
928
|
+
old_new_params = new_params.copy()
|
929
|
+
n_new_params = len(new_params)
|
930
|
+
any_components_left_to_process = n_new_params > 0
|
931
|
+
|
932
|
+
return fitted_params
|
933
|
+
|
934
|
+
def _get_fitted_params_default(self, obj=None):
|
935
|
+
"""Obtain fitted params of object, per sklearn convention.
|
936
|
+
|
937
|
+
Extracts a dict with {paramstr : paramvalue} contents,
|
938
|
+
where paramstr are all string names of "fitted parameters".
|
939
|
+
|
940
|
+
A "fitted attribute" of obj is one that ends in "_" but does not start with "_".
|
941
|
+
"fitted parameters" are names of fitted attributes, minus the "_" at the end.
|
942
|
+
|
943
|
+
Parameters
|
944
|
+
----------
|
945
|
+
obj : any object, optional, default=self
|
946
|
+
|
947
|
+
Returns
|
948
|
+
-------
|
949
|
+
fitted_params : dict with str keys
|
950
|
+
fitted parameters, keyed by names of fitted parameter
|
951
|
+
"""
|
952
|
+
obj = obj if obj else self
|
953
|
+
|
954
|
+
# default retrieves all self attributes ending in "_"
|
955
|
+
# and returns them with keys that have the "_" removed
|
956
|
+
#
|
957
|
+
# get all attributes ending in "_", exclude any that start with "_" (private)
|
958
|
+
fitted_params = [
|
959
|
+
attr for attr in dir(obj) if attr.endswith("_") and not attr.startswith("_")
|
960
|
+
]
|
961
|
+
# remove the "_" at the end
|
962
|
+
fitted_param_dict = {
|
963
|
+
p[:-1]: getattr(obj, p) for p in fitted_params if hasattr(obj, p)
|
964
|
+
}
|
965
|
+
|
966
|
+
return fitted_param_dict
|
967
|
+
|
968
|
+
def _get_fitted_params(self):
|
969
|
+
"""Get fitted parameters.
|
970
|
+
|
971
|
+
private _get_fitted_params, called from get_fitted_params
|
972
|
+
|
973
|
+
State required:
|
974
|
+
Requires state to be "fitted".
|
975
|
+
|
976
|
+
Returns
|
977
|
+
-------
|
978
|
+
fitted_params : dict with str keys
|
979
|
+
fitted parameters, keyed by names of fitted parameter
|
980
|
+
"""
|
981
|
+
return self._get_fitted_params_default()
|