scikit-base 0.4.6__py3-none-any.whl → 0.5.1__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.
Files changed (60) hide show
  1. docs/source/conf.py +299 -299
  2. {scikit_base-0.4.6.dist-info → scikit_base-0.5.1.dist-info}/LICENSE +29 -29
  3. {scikit_base-0.4.6.dist-info → scikit_base-0.5.1.dist-info}/METADATA +160 -159
  4. scikit_base-0.5.1.dist-info/RECORD +58 -0
  5. {scikit_base-0.4.6.dist-info → scikit_base-0.5.1.dist-info}/WHEEL +1 -1
  6. scikit_base-0.5.1.dist-info/top_level.txt +5 -0
  7. {scikit_base-0.4.6.dist-info → scikit_base-0.5.1.dist-info}/zip-safe +1 -1
  8. skbase/__init__.py +14 -14
  9. skbase/_exceptions.py +31 -31
  10. skbase/_nopytest_tests.py +35 -35
  11. skbase/base/__init__.py +20 -20
  12. skbase/base/_base.py +1249 -1249
  13. skbase/base/_meta.py +883 -871
  14. skbase/base/_pretty_printing/__init__.py +11 -11
  15. skbase/base/_pretty_printing/_object_html_repr.py +392 -392
  16. skbase/base/_pretty_printing/_pprint.py +412 -412
  17. skbase/base/_tagmanager.py +217 -217
  18. skbase/lookup/__init__.py +31 -31
  19. skbase/lookup/_lookup.py +1009 -1009
  20. skbase/lookup/tests/__init__.py +2 -2
  21. skbase/lookup/tests/test_lookup.py +991 -991
  22. skbase/testing/__init__.py +12 -12
  23. skbase/testing/test_all_objects.py +852 -856
  24. skbase/testing/utils/__init__.py +5 -5
  25. skbase/testing/utils/_conditional_fixtures.py +209 -209
  26. skbase/testing/utils/_dependencies.py +15 -15
  27. skbase/testing/utils/deep_equals.py +15 -15
  28. skbase/testing/utils/inspect.py +30 -30
  29. skbase/testing/utils/tests/__init__.py +2 -2
  30. skbase/testing/utils/tests/test_check_dependencies.py +49 -49
  31. skbase/testing/utils/tests/test_deep_equals.py +66 -66
  32. skbase/tests/__init__.py +2 -2
  33. skbase/tests/conftest.py +273 -273
  34. skbase/tests/mock_package/__init__.py +5 -5
  35. skbase/tests/mock_package/test_mock_package.py +74 -74
  36. skbase/tests/test_base.py +1202 -1202
  37. skbase/tests/test_baseestimator.py +130 -130
  38. skbase/tests/test_exceptions.py +23 -23
  39. skbase/tests/test_meta.py +170 -131
  40. skbase/utils/__init__.py +21 -21
  41. skbase/utils/_check.py +53 -53
  42. skbase/utils/_iter.py +238 -238
  43. skbase/utils/_nested_iter.py +180 -180
  44. skbase/utils/_utils.py +91 -91
  45. skbase/utils/deep_equals.py +358 -358
  46. skbase/utils/dependencies/__init__.py +11 -11
  47. skbase/utils/dependencies/_dependencies.py +253 -253
  48. skbase/utils/tests/__init__.py +4 -4
  49. skbase/utils/tests/test_check.py +24 -24
  50. skbase/utils/tests/test_iter.py +127 -127
  51. skbase/utils/tests/test_nested_iter.py +84 -84
  52. skbase/utils/tests/test_utils.py +37 -37
  53. skbase/validate/__init__.py +22 -22
  54. skbase/validate/_named_objects.py +403 -403
  55. skbase/validate/_types.py +345 -345
  56. skbase/validate/tests/__init__.py +2 -2
  57. skbase/validate/tests/test_iterable_named_objects.py +200 -200
  58. skbase/validate/tests/test_type_validations.py +370 -370
  59. scikit_base-0.4.6.dist-info/RECORD +0 -58
  60. scikit_base-0.4.6.dist-info/top_level.txt +0 -2
skbase/base/_base.py CHANGED
@@ -1,1249 +1,1249 @@
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 re
57
- import warnings
58
- from collections import defaultdict
59
- from copy import deepcopy
60
- from typing import List
61
-
62
- from skbase._exceptions import NotFittedError
63
- from skbase.base._pretty_printing._object_html_repr import _object_html_repr
64
- from skbase.base._tagmanager import _FlagManager
65
-
66
- __author__: List[str] = ["mloning", "RNKuhns", "fkiraly"]
67
- __all__: List[str] = ["BaseEstimator", "BaseObject"]
68
-
69
-
70
- class BaseObject(_FlagManager):
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
- _config = {
77
- "display": "diagram",
78
- "print_changed_only": True,
79
- "check_clone": False, # whether to execute validity checks in clone
80
- }
81
-
82
- def __init__(self):
83
- """Construct BaseObject."""
84
- self._init_flags(flag_attr_name="_tags")
85
- self._init_flags(flag_attr_name="_config")
86
- super(BaseObject, self).__init__()
87
-
88
- def __eq__(self, other):
89
- """Equality dunder. Checks equal class and parameters.
90
-
91
- Returns True iff result of get_params(deep=False)
92
- results in equal parameter sets.
93
-
94
- Nested BaseObject descendants from get_params are compared via __eq__ as well.
95
- """
96
- from skbase.utils.deep_equals import deep_equals
97
-
98
- if not isinstance(other, BaseObject):
99
- return False
100
-
101
- self_params = self.get_params(deep=False)
102
- other_params = other.get_params(deep=False)
103
-
104
- return deep_equals(self_params, other_params)
105
-
106
- def reset(self):
107
- """Reset the object to a clean post-init state.
108
-
109
- Using reset, runs __init__ with current values of hyper-parameters
110
- (result of get_params). This Removes any object attributes, except:
111
-
112
- - hyper-parameters = arguments of __init__
113
- - object attributes containing double-underscores, i.e., the string "__"
114
-
115
- Class and object methods, and class attributes are also unaffected.
116
-
117
- Returns
118
- -------
119
- self
120
- Instance of class reset to a clean post-init state but retaining
121
- the current hyper-parameter values.
122
-
123
- Notes
124
- -----
125
- Equivalent to sklearn.clone but overwrites self. After self.reset()
126
- call, self is equal in value to `type(self)(**self.get_params(deep=False))`
127
- """
128
- # retrieve parameters to copy them later
129
- params = self.get_params(deep=False)
130
-
131
- # delete all object attributes in self
132
- attrs = [attr for attr in dir(self) if "__" not in attr]
133
- cls_attrs = list(dir(type(self)))
134
- self_attrs = set(attrs).difference(cls_attrs)
135
- for attr in self_attrs:
136
- delattr(self, attr)
137
-
138
- # run init with a copy of parameters self had at the start
139
- self.__init__(**params)
140
-
141
- return self
142
-
143
- def clone(self):
144
- """Obtain a clone of the object with same hyper-parameters.
145
-
146
- A clone is a different object without shared references, in post-init state.
147
- This function is equivalent to returning sklearn.clone of self.
148
-
149
- Raises
150
- ------
151
- RuntimeError if the clone is non-conforming, due to faulty ``__init__``.
152
-
153
- Notes
154
- -----
155
- If successful, equal in value to ``type(self)(**self.get_params(deep=False))``.
156
- """
157
- self_params = self.get_params(deep=False)
158
- self_clone = self._clone(self)
159
-
160
- # if checking the clone is turned off, return now
161
- if not self.get_config()["check_clone"]:
162
- return self_clone
163
-
164
- from skbase.utils.deep_equals import deep_equals
165
-
166
- # check that all attributes are written to the clone
167
- for attrname in self_params.keys():
168
- if not hasattr(self_clone, attrname):
169
- raise RuntimeError(
170
- f"error in {self}.clone, __init__ must write all arguments "
171
- f"to self and not mutate them, but {attrname} was not found. "
172
- f"Please check __init__ of {self}."
173
- )
174
-
175
- clone_attrs = {attr: getattr(self_clone, attr) for attr in self_params.keys()}
176
-
177
- # check equality of parameters post-clone and pre-clone
178
- clone_attrs_valid, msg = deep_equals(self_params, clone_attrs, return_msg=True)
179
- if not clone_attrs_valid:
180
- raise RuntimeError(
181
- f"error in {self}.clone, __init__ must write all arguments "
182
- f"to self and not mutate them, but this is not the case. "
183
- f"Error on equality check of arguments (x) vs parameters (y): {msg}"
184
- )
185
-
186
- return self_clone
187
-
188
- # copied from sklearn
189
- def _clone(self, estimator, *, safe=True):
190
- """Construct a new unfitted estimator with the same parameters.
191
-
192
- Clone does a deep copy of the model in an estimator
193
- without actually copying attached data. It returns a new estimator
194
- with the same parameters that has not been fitted on any data.
195
-
196
- Parameters
197
- ----------
198
- estimator : {list, tuple, set} of estimator instance or a single \
199
- estimator instance
200
- The estimator or group of estimators to be cloned.
201
- safe : bool, default=True
202
- If safe is False, clone will fall back to a deep copy on objects
203
- that are not estimators.
204
-
205
- Returns
206
- -------
207
- estimator : object
208
- The deep copy of the input, an estimator if input is an estimator.
209
-
210
- Notes
211
- -----
212
- If the estimator's `random_state` parameter is an integer (or if the
213
- estimator doesn't have a `random_state` parameter), an *exact clone* is
214
- returned: the clone and the original estimator will give the exact same
215
- results. Otherwise, *statistical clone* is returned: the clone might
216
- return different results from the original estimator. More details can be
217
- found in :ref:`randomness`.
218
- """
219
- estimator_type = type(estimator)
220
- # XXX: not handling dictionaries
221
- if estimator_type in (list, tuple, set, frozenset):
222
- return estimator_type([self._clone(e, safe=safe) for e in estimator])
223
- elif not hasattr(estimator, "get_params") or isinstance(estimator, type):
224
- if not safe:
225
- return deepcopy(estimator)
226
- else:
227
- if isinstance(estimator, type):
228
- raise TypeError(
229
- "Cannot clone object. "
230
- + "You should provide an instance of "
231
- + "scikit-learn estimator instead of a class."
232
- )
233
- else:
234
- raise TypeError(
235
- "Cannot clone object '%s' (type %s): "
236
- "it does not seem to be a scikit-learn "
237
- "estimator as it does not implement a "
238
- "'get_params' method." % (repr(estimator), type(estimator))
239
- )
240
-
241
- klass = estimator.__class__
242
- new_object_params = estimator.get_params(deep=False)
243
- for name, param in new_object_params.items():
244
- new_object_params[name] = self._clone(param, safe=False)
245
- new_object = klass(**new_object_params)
246
- params_set = new_object.get_params(deep=False)
247
-
248
- # quick sanity check of the parameters of the clone
249
- for name in new_object_params:
250
- param1 = new_object_params[name]
251
- param2 = params_set[name]
252
- if param1 is not param2:
253
- raise RuntimeError(
254
- "Cannot clone object %s, as the constructor "
255
- "either does not set or modifies parameter %s" % (estimator, name)
256
- )
257
- return new_object
258
-
259
- @classmethod
260
- def _get_init_signature(cls):
261
- """Get class init sigature.
262
-
263
- Useful in parameter inspection.
264
-
265
- Returns
266
- -------
267
- List
268
- The inspected parameter objects (including defaults).
269
-
270
- Raises
271
- ------
272
- RuntimeError if cls has varargs in __init__.
273
- """
274
- # fetch the constructor or the original constructor before
275
- # deprecation wrapping if any
276
- init = getattr(cls.__init__, "deprecated_original", cls.__init__)
277
- if init is object.__init__:
278
- # No explicit constructor to introspect
279
- return []
280
-
281
- # introspect the constructor arguments to find the model parameters
282
- # to represent
283
- init_signature = inspect.signature(init)
284
-
285
- # Consider the constructor parameters excluding 'self'
286
- parameters = [
287
- p
288
- for p in init_signature.parameters.values()
289
- if p.name != "self" and p.kind != p.VAR_KEYWORD
290
- ]
291
- for p in parameters:
292
- if p.kind == p.VAR_POSITIONAL:
293
- raise RuntimeError(
294
- "scikit-learn compatible estimators should always "
295
- "specify their parameters in the signature"
296
- " of their __init__ (no varargs)."
297
- " %s with constructor %s doesn't "
298
- " follow this convention." % (cls, init_signature)
299
- )
300
- return parameters
301
-
302
- @classmethod
303
- def get_param_names(cls):
304
- """Get object's parameter names.
305
-
306
- Returns
307
- -------
308
- param_names: list[str]
309
- Alphabetically sorted list of parameter names of cls.
310
- """
311
- parameters = cls._get_init_signature()
312
- param_names = sorted([p.name for p in parameters])
313
- return param_names
314
-
315
- @classmethod
316
- def get_param_defaults(cls):
317
- """Get object's parameter defaults.
318
-
319
- Returns
320
- -------
321
- default_dict: dict[str, Any]
322
- Keys are all parameters of cls that have a default defined in __init__
323
- values are the defaults, as defined in __init__.
324
- """
325
- parameters = cls._get_init_signature()
326
- default_dict = {
327
- x.name: x.default for x in parameters if x.default != inspect._empty
328
- }
329
- return default_dict
330
-
331
- def get_params(self, deep=True):
332
- """Get a dict of parameters values for this object.
333
-
334
- Parameters
335
- ----------
336
- deep : bool, default=True
337
- Whether to return parameters of components.
338
-
339
- * If True, will return a dict of parameter name : value for this object,
340
- including parameters of components (= BaseObject-valued parameters).
341
- * If False, will return a dict of parameter name : value for this object,
342
- but not include parameters of components.
343
-
344
- Returns
345
- -------
346
- params : dict with str-valued keys
347
- Dictionary of parameters, paramname : paramvalue
348
- keys-value pairs include:
349
-
350
- * always: all parameters of this object, as via `get_param_names`
351
- values are parameter value for that key, of this object
352
- values are always identical to values passed at construction
353
- * if `deep=True`, also contains keys/value pairs of component parameters
354
- parameters of components are indexed as `[componentname]__[paramname]`
355
- all parameters of `componentname` appear as `paramname` with its value
356
- * if `deep=True`, also contains arbitrary levels of component recursion,
357
- e.g., `[componentname]__[componentcomponentname]__[paramname]`, etc
358
- """
359
- params = {key: getattr(self, key) for key in self.get_param_names()}
360
-
361
- if deep:
362
- deep_params = {}
363
- for key, value in params.items():
364
- if hasattr(value, "get_params"):
365
- deep_items = value.get_params().items()
366
- deep_params.update({f"{key}__{k}": val for k, val in deep_items})
367
- params.update(deep_params)
368
-
369
- return params
370
-
371
- def set_params(self, **params):
372
- """Set the parameters of this object.
373
-
374
- The method works on simple estimators as well as on nested objects.
375
- The latter have parameters of the form ``<component>__<parameter>`` so
376
- that it's possible to update each component of a nested object.
377
-
378
- Parameters
379
- ----------
380
- **params : dict
381
- BaseObject parameters.
382
-
383
- Returns
384
- -------
385
- self
386
- Reference to self (after parameters have been set).
387
- """
388
- if not params:
389
- # Simple optimization to gain speed (inspect is slow)
390
- return self
391
- valid_params = self.get_params(deep=True)
392
-
393
- nested_params = defaultdict(dict) # grouped by prefix
394
- for key, value in params.items():
395
- key, delim, sub_key = key.partition("__")
396
- if key not in valid_params:
397
- raise ValueError(
398
- "Invalid parameter %s for object %s. "
399
- "Check the list of available parameters "
400
- "with `object.get_params().keys()`." % (key, self)
401
- )
402
-
403
- if delim:
404
- nested_params[key][sub_key] = value
405
- else:
406
- setattr(self, key, value)
407
- valid_params[key] = value
408
-
409
- self.reset()
410
-
411
- # recurse in components
412
- for key, sub_params in nested_params.items():
413
- valid_params[key].set_params(**sub_params)
414
-
415
- return self
416
-
417
- @classmethod
418
- def get_class_tags(cls):
419
- """Get class tags from the class and all its parent classes.
420
-
421
- Retrieves tag: value pairs from _tags class attribute. Does not return
422
- information from dynamic tags (set via set_tags or clone_tags)
423
- that are defined on instances.
424
-
425
- Returns
426
- -------
427
- collected_tags : dict
428
- Dictionary of class tag name: tag value pairs. Collected from _tags
429
- class attribute via nested inheritance.
430
- """
431
- return cls._get_class_flags(flag_attr_name="_tags")
432
-
433
- @classmethod
434
- def get_class_tag(cls, tag_name, tag_value_default=None):
435
- """Get a class tag's value.
436
-
437
- Does not return information from dynamic tags (set via set_tags or clone_tags)
438
- that are defined on instances.
439
-
440
- Parameters
441
- ----------
442
- tag_name : str
443
- Name of tag value.
444
- tag_value_default : any
445
- Default/fallback value if tag is not found.
446
-
447
- Returns
448
- -------
449
- tag_value :
450
- Value of the `tag_name` tag in self. If not found, returns
451
- `tag_value_default`.
452
- """
453
- return cls._get_class_flag(
454
- flag_name=tag_name,
455
- flag_value_default=tag_value_default,
456
- flag_attr_name="_tags",
457
- )
458
-
459
- def get_tags(self):
460
- """Get tags from estimator class and dynamic tag overrides.
461
-
462
- Returns
463
- -------
464
- collected_tags : dict
465
- Dictionary of tag name : tag value pairs. Collected from _tags
466
- class attribute via nested inheritance and then any overrides
467
- and new tags from _tags_dynamic object attribute.
468
- """
469
- return self._get_flags(flag_attr_name="_tags")
470
-
471
- def get_tag(self, tag_name, tag_value_default=None, raise_error=True):
472
- """Get tag value from estimator class and dynamic tag overrides.
473
-
474
- Parameters
475
- ----------
476
- tag_name : str
477
- Name of tag to be retrieved
478
- tag_value_default : any type, optional; default=None
479
- Default/fallback value if tag is not found
480
- raise_error : bool
481
- whether a ValueError is raised when the tag is not found
482
-
483
- Returns
484
- -------
485
- tag_value : Any
486
- Value of the `tag_name` tag in self. If not found, returns an error if
487
- `raise_error` is True, otherwise it returns `tag_value_default`.
488
-
489
- Raises
490
- ------
491
- ValueError if raise_error is True i.e. if `tag_name` is not in
492
- self.get_tags().keys()
493
- """
494
- return self._get_flag(
495
- flag_name=tag_name,
496
- flag_value_default=tag_value_default,
497
- raise_error=raise_error,
498
- flag_attr_name="_tags",
499
- )
500
-
501
- def set_tags(self, **tag_dict):
502
- """Set dynamic tags to given values.
503
-
504
- Parameters
505
- ----------
506
- **tag_dict : dict
507
- Dictionary of tag name: tag value pairs.
508
-
509
- Returns
510
- -------
511
- Self
512
- Reference to self.
513
-
514
- Notes
515
- -----
516
- Changes object state by settting tag values in tag_dict as dynamic tags in self.
517
- """
518
- self._set_flags(flag_attr_name="_tags", **tag_dict)
519
-
520
- return self
521
-
522
- def clone_tags(self, estimator, tag_names=None):
523
- """Clone tags from another estimator as dynamic override.
524
-
525
- Parameters
526
- ----------
527
- estimator : estimator inheriting from :class:BaseEstimator
528
- tag_names : str or list of str, default = None
529
- Names of tags to clone. If None then all tags in estimator are used
530
- as `tag_names`.
531
-
532
- Returns
533
- -------
534
- Self :
535
- Reference to self.
536
-
537
- Notes
538
- -----
539
- Changes object state by setting tag values in tag_set from estimator as
540
- dynamic tags in self.
541
- """
542
- self._clone_flags(
543
- estimator=estimator, flag_names=tag_names, flag_attr_name="_tags"
544
- )
545
-
546
- return self
547
-
548
- def get_config(self):
549
- """Get config flags for self.
550
-
551
- Returns
552
- -------
553
- config_dict : dict
554
- Dictionary of config name : config value pairs. Collected from _config
555
- class attribute via nested inheritance and then any overrides
556
- and new tags from _onfig_dynamic object attribute.
557
- """
558
- return self._get_flags(flag_attr_name="_config")
559
-
560
- def set_config(self, **config_dict):
561
- """Set config flags to given values.
562
-
563
- Parameters
564
- ----------
565
- config_dict : dict
566
- Dictionary of config name : config value pairs.
567
-
568
- Returns
569
- -------
570
- self : reference to self.
571
-
572
- Notes
573
- -----
574
- Changes object state, copies configs in config_dict to self._config_dynamic.
575
- """
576
- self._set_flags(flag_attr_name="_config", **config_dict)
577
-
578
- return self
579
-
580
- @classmethod
581
- def get_test_params(cls, parameter_set="default"):
582
- """Return testing parameter settings for the estimator.
583
-
584
- Parameters
585
- ----------
586
- parameter_set : str, default="default"
587
- Name of the set of test parameters to return, for use in tests. If no
588
- special parameters are defined for a value, will return `"default"` set.
589
-
590
- Returns
591
- -------
592
- params : dict or list of dict, default = {}
593
- Parameters to create testing instances of the class
594
- Each dict are parameters to construct an "interesting" test instance, i.e.,
595
- `MyClass(**params)` or `MyClass(**params[i])` creates a valid test instance.
596
- `create_test_instance` uses the first (or only) dictionary in `params`
597
- """
598
- # if non-default parameters are required, but none have been found, raise error
599
- if hasattr(cls, "_required_parameters"):
600
- required_parameters = getattr(cls, "_required_parameters", [])
601
- if len(required_parameters) > 0:
602
- raise ValueError(
603
- f"Estimator: {cls} requires "
604
- f"non-default parameters for construction, "
605
- f"but none were given. Please set them "
606
- f"as given in the extension template"
607
- )
608
-
609
- # construct with parameter configuration for testing, otherwise construct with
610
- # default parameters (empty dict)
611
- params = {}
612
- return params
613
-
614
- @classmethod
615
- def create_test_instance(cls, parameter_set="default"):
616
- """Construct Estimator instance if possible.
617
-
618
- Parameters
619
- ----------
620
- parameter_set : str, default="default"
621
- Name of the set of test parameters to return, for use in tests. If no
622
- special parameters are defined for a value, will return `"default"` set.
623
-
624
- Returns
625
- -------
626
- instance : instance of the class with default parameters
627
-
628
- Notes
629
- -----
630
- `get_test_params` can return dict or list of dict.
631
- This function takes first or single dict that get_test_params returns, and
632
- constructs the object with that.
633
- """
634
- if "parameter_set" in inspect.getfullargspec(cls.get_test_params).args:
635
- params = cls.get_test_params(parameter_set=parameter_set)
636
- else:
637
- params = cls.get_test_params()
638
-
639
- if isinstance(params, list) and isinstance(params[0], dict):
640
- params = params[0]
641
- elif isinstance(params, dict):
642
- pass
643
- else:
644
- raise TypeError(
645
- "get_test_params should either return a dict or list of dict."
646
- )
647
-
648
- return cls(**params)
649
-
650
- @classmethod
651
- def create_test_instances_and_names(cls, parameter_set="default"):
652
- """Create list of all test instances and a list of names for them.
653
-
654
- Parameters
655
- ----------
656
- parameter_set : str, default="default"
657
- Name of the set of test parameters to return, for use in tests. If no
658
- special parameters are defined for a value, will return `"default"` set.
659
-
660
- Returns
661
- -------
662
- objs : list of instances of cls
663
- i-th instance is cls(**cls.get_test_params()[i])
664
- names : list of str, same length as objs
665
- i-th element is name of i-th instance of obj in tests
666
- convention is {cls.__name__}-{i} if more than one instance
667
- otherwise {cls.__name__}
668
- parameter_set : str, default="default"
669
- Name of the set of test parameters to return, for use in tests. If no
670
- special parameters are defined for a value, will return `"default"` set.
671
- """
672
- if "parameter_set" in inspect.getfullargspec(cls.get_test_params).args:
673
- param_list = cls.get_test_params(parameter_set=parameter_set)
674
- else:
675
- param_list = cls.get_test_params()
676
-
677
- objs = []
678
- if not isinstance(param_list, (dict, list)):
679
- raise RuntimeError(
680
- f"Error in {cls.__name__}.get_test_params, "
681
- "return must be param dict for class, or list thereof"
682
- )
683
- if isinstance(param_list, dict):
684
- param_list = [param_list]
685
- for params in param_list:
686
- if not isinstance(params, dict):
687
- raise RuntimeError(
688
- f"Error in {cls.__name__}.get_test_params, "
689
- "return must be param dict for class, or list thereof"
690
- )
691
- objs += [cls(**params)]
692
-
693
- num_instances = len(param_list)
694
- if num_instances > 1:
695
- names = [cls.__name__ + "-" + str(i) for i in range(num_instances)]
696
- else:
697
- names = [cls.__name__]
698
-
699
- return objs, names
700
-
701
- @classmethod
702
- def _has_implementation_of(cls, method):
703
- """Check if method has a concrete implementation in this class.
704
-
705
- This assumes that having an implementation is equivalent to
706
- one or more overrides of `method` in the method resolution order.
707
-
708
- Parameters
709
- ----------
710
- method : str, name of method to check implementation of
711
-
712
- Returns
713
- -------
714
- bool, whether method has implementation in cls
715
- True if cls.method has been overridden at least once in
716
- the inheritance tree (according to method resolution order)
717
- """
718
- # walk through method resolution order and inspect methods
719
- # of classes and direct parents, "adjacent" classes in mro
720
- mro = inspect.getmro(cls)
721
- # collect all methods that are not none
722
- methods = [getattr(c, method, None) for c in mro]
723
- methods = [m for m in methods if m is not None]
724
-
725
- for i in range(len(methods) - 1):
726
- # the method has been overridden once iff
727
- # at least two of the methods collected are not equal
728
- # equivalently: some two adjacent methods are not equal
729
- overridden = methods[i] != methods[i + 1]
730
- if overridden:
731
- return True
732
-
733
- return False
734
-
735
- def is_composite(self):
736
- """Check if the object is composed of other BaseObjects.
737
-
738
- A composite object is an object which contains objects, as parameters.
739
- Called on an instance, since this may differ by instance.
740
-
741
- Returns
742
- -------
743
- composite: bool
744
- Whether an object has any parameters whose values
745
- are BaseObjects.
746
- """
747
- # walk through method resolution order and inspect methods
748
- # of classes and direct parents, "adjacent" classes in mro
749
- params = self.get_params(deep=False)
750
- composite = any(isinstance(x, BaseObject) for x in params.values())
751
-
752
- return composite
753
-
754
- def _components(self, base_class=None):
755
- """Return references to all state changing BaseObject type attributes.
756
-
757
- This *excludes* the blue-print-like components passed in the __init__.
758
-
759
- Caution: this method returns *references* and not *copies*.
760
- Writing to the reference will change the respective attribute of self.
761
-
762
- Parameters
763
- ----------
764
- base_class : class, optional, default=None, must be subclass of BaseObject
765
- if not None, sub-sets return dict to only descendants of base_class
766
-
767
- Returns
768
- -------
769
- dict with key = attribute name, value = reference to that BaseObject attribute
770
- dict contains all attributes of self that inherit from BaseObjects, and:
771
- whose names do not contain the string "__", e.g., hidden attributes
772
- are not class attributes, and are not hyper-parameters (__init__ args)
773
- """
774
- if base_class is None:
775
- base_class = BaseObject
776
- if base_class is not None and not inspect.isclass(base_class):
777
- raise TypeError(f"base_class must be a class, but found {type(base_class)}")
778
- if base_class is not None and not issubclass(base_class, BaseObject):
779
- raise TypeError("base_class must be a subclass of BaseObject")
780
-
781
- # retrieve parameter names to exclude them later
782
- param_names = self.get_params(deep=False).keys()
783
-
784
- # retrieve all attributes that are BaseObject descendants
785
- attrs = [attr for attr in dir(self) if "__" not in attr]
786
- cls_attrs = list(dir(type(self)))
787
- self_attrs = set(attrs).difference(cls_attrs).difference(param_names)
788
-
789
- comp_dict = {x: getattr(self, x) for x in self_attrs}
790
- comp_dict = {x: y for (x, y) in comp_dict.items() if isinstance(y, base_class)}
791
-
792
- return comp_dict
793
-
794
- def __repr__(self, n_char_max: int = 700):
795
- """Represent class as string.
796
-
797
- This follows the scikit-learn implementation for the string representation
798
- of parameterized objects.
799
-
800
- Parameters
801
- ----------
802
- n_char_max : int
803
- Maximum (approximate) number of non-blank characters to render. This
804
- can be useful in testing.
805
- """
806
- from skbase.base._pretty_printing._pprint import _BaseObjectPrettyPrinter
807
-
808
- n_max_elements_to_show = 30 # number of elements to show in sequences
809
- # use ellipsis for sequences with a lot of elements
810
- pp = _BaseObjectPrettyPrinter(
811
- compact=True,
812
- indent=1,
813
- indent_at_name=True,
814
- n_max_elements_to_show=n_max_elements_to_show,
815
- changed_only=self.get_config()["print_changed_only"],
816
- )
817
-
818
- repr_ = pp.pformat(self)
819
-
820
- # Use bruteforce ellipsis when there are a lot of non-blank characters
821
- n_nonblank = len("".join(repr_.split()))
822
- if n_nonblank > n_char_max:
823
- lim = n_char_max // 2 # apprx number of chars to keep on both ends
824
- regex = r"^(\s*\S){%d}" % lim
825
- # The regex '^(\s*\S){%d}' matches from the start of the string
826
- # until the nth non-blank character:
827
- # - ^ matches the start of string
828
- # - (pattern){n} matches n repetitions of pattern
829
- # - \s*\S matches a non-blank char following zero or more blanks
830
- left_match = re.match(regex, repr_)
831
- right_match = re.match(regex, repr_[::-1])
832
- left_lim = left_match.end() if left_match is not None else 0
833
- right_lim = right_match.end() if right_match is not None else 0
834
-
835
- if "\n" in repr_[left_lim:-right_lim]:
836
- # The left side and right side aren't on the same line.
837
- # To avoid weird cuts, e.g.:
838
- # categoric...ore',
839
- # we need to start the right side with an appropriate newline
840
- # character so that it renders properly as:
841
- # categoric...
842
- # handle_unknown='ignore',
843
- # so we add [^\n]*\n which matches until the next \n
844
- regex += r"[^\n]*\n"
845
- right_match = re.match(regex, repr_[::-1])
846
- right_lim = right_match.end() if right_match is not None else 0
847
-
848
- ellipsis = "..."
849
- if left_lim + len(ellipsis) < len(repr_) - right_lim:
850
- # Only add ellipsis if it results in a shorter repr
851
- repr_ = repr_[:left_lim] + "..." + repr_[-right_lim:]
852
-
853
- return repr_
854
-
855
- @property
856
- def _repr_html_(self):
857
- """HTML representation of BaseObject.
858
-
859
- This is redundant with the logic of `_repr_mimebundle_`. The latter
860
- should be favorted in the long term, `_repr_html_` is only
861
- implemented for consumers who do not interpret `_repr_mimbundle_`.
862
- """
863
- if self.get_config()["display"] != "diagram":
864
- raise AttributeError(
865
- "_repr_html_ is only defined when the "
866
- "`display` configuration option is set to 'diagram'."
867
- )
868
- return self._repr_html_inner
869
-
870
- def _repr_html_inner(self):
871
- """Return HTML representation of class.
872
-
873
- This function is returned by the @property `_repr_html_` to make
874
- `hasattr(BaseObject, "_repr_html_") return `True` or `False` depending
875
- on `self.get_config()["display"]`.
876
- """
877
- return _object_html_repr(self)
878
-
879
- def _repr_mimebundle_(self, **kwargs):
880
- """Mime bundle used by jupyter kernels to display instances of BaseObject."""
881
- output = {"text/plain": repr(self)}
882
- if self.get_config()["display"] == "diagram":
883
- output["text/html"] = _object_html_repr(self)
884
- return output
885
-
886
-
887
- class TagAliaserMixin:
888
- """Mixin class for tag aliasing and deprecation of old tags.
889
-
890
- To deprecate tags, add the TagAliaserMixin to BaseObject or BaseEstimator.
891
- alias_dict contains the deprecated tags, and supports removal and renaming.
892
- For removal, add an entry "old_tag_name": ""
893
- For renaming, add an entry "old_tag_name": "new_tag_name"
894
- deprecate_dict contains the version number of renaming or removal.
895
- the keys in deprecate_dict should be the same as in alias_dict.
896
- values in deprecate_dict should be strings, the version of removal/renaming.
897
-
898
- The class will ensure that new tags alias old tags and vice versa, during
899
- the deprecation period. Informative warnings will be raised whenever the
900
- deprecated tags are being accessed.
901
-
902
- When removing tags, ensure to remove the removed tags from this class.
903
- If no tags are deprecated anymore (e.g., all deprecated tags are removed/renamed),
904
- ensure toremove this class as a parent of BaseObject or BaseEstimator.
905
- """
906
-
907
- # dictionary of aliases
908
- # key = old tag; value = new tag, aliased by old tag
909
- # override this in a child class
910
- alias_dict = {"old_tag": "new_tag", "tag_to_remove": ""}
911
-
912
- # dictionary of removal version
913
- # key = old tag; value = version in which tag will be removed, as string
914
- deprecate_dict = {"old_tag": "0.12.0", "tag_to_remove": "99.99.99"}
915
-
916
- def __init__(self):
917
- """Construct TagAliaserMixin."""
918
- super(TagAliaserMixin, self).__init__()
919
-
920
- @classmethod
921
- def get_class_tags(cls):
922
- """Get class tags from estimator class and all its parent classes.
923
-
924
- Returns
925
- -------
926
- collected_tags : dict
927
- Dictionary of tag name : tag value pairs. Collected from _tags
928
- class attribute via nested inheritance. NOT overridden by dynamic
929
- tags set by set_tags or mirror_tags.
930
- """
931
- collected_tags = super(TagAliaserMixin, cls).get_class_tags()
932
- collected_tags = cls._complete_dict(collected_tags)
933
- return collected_tags
934
-
935
- @classmethod
936
- def get_class_tag(cls, tag_name, tag_value_default=None):
937
- """Get tag value from estimator class (only class tags).
938
-
939
- Parameters
940
- ----------
941
- tag_name : str
942
- Name of tag value.
943
- tag_value_default : any type
944
- Default/fallback value if tag is not found.
945
-
946
- Returns
947
- -------
948
- tag_value :
949
- Value of the `tag_name` tag in self. If not found, returns
950
- `tag_value_default`.
951
- """
952
- cls._deprecate_tag_warn([tag_name])
953
- return super(TagAliaserMixin, cls).get_class_tag(
954
- tag_name=tag_name, tag_value_default=tag_value_default
955
- )
956
-
957
- def get_tags(self):
958
- """Get tags from estimator class and dynamic tag overrides.
959
-
960
- Returns
961
- -------
962
- collected_tags : dict
963
- Dictionary of tag name : tag value pairs. Collected from _tags
964
- class attribute via nested inheritance and then any overrides
965
- and new tags from _tags_dynamic object attribute.
966
- """
967
- collected_tags = super(TagAliaserMixin, self).get_tags()
968
- collected_tags = self._complete_dict(collected_tags)
969
- return collected_tags
970
-
971
- def get_tag(self, tag_name, tag_value_default=None, raise_error=True):
972
- """Get tag value from estimator class and dynamic tag overrides.
973
-
974
- Parameters
975
- ----------
976
- tag_name : str
977
- Name of tag to be retrieved
978
- tag_value_default : any type, optional; default=None
979
- Default/fallback value if tag is not found
980
- raise_error : bool
981
- whether a ValueError is raised when the tag is not found
982
-
983
- Returns
984
- -------
985
- tag_value :
986
- Value of the `tag_name` tag in self. If not found, returns an error if
987
- raise_error is True, otherwise it returns `tag_value_default`.
988
-
989
- Raises
990
- ------
991
- ValueError if raise_error is True i.e. if tag_name is not in self.get_tags(
992
- ).keys()
993
- """
994
- self._deprecate_tag_warn([tag_name])
995
- return super(TagAliaserMixin, self).get_tag(
996
- tag_name=tag_name,
997
- tag_value_default=tag_value_default,
998
- raise_error=raise_error,
999
- )
1000
-
1001
- def set_tags(self, **tag_dict):
1002
- """Set dynamic tags to given values.
1003
-
1004
- Parameters
1005
- ----------
1006
- tag_dict : dict
1007
- Dictionary of tag name : tag value pairs.
1008
-
1009
- Returns
1010
- -------
1011
- Self :
1012
- Reference to self.
1013
-
1014
- Notes
1015
- -----
1016
- Changes object state by settting tag values in tag_dict as dynamic tags
1017
- in self.
1018
- """
1019
- self._deprecate_tag_warn(tag_dict.keys())
1020
-
1021
- tag_dict = self._complete_dict(tag_dict)
1022
- super(TagAliaserMixin, self).set_tags(**tag_dict)
1023
- return self
1024
-
1025
- @classmethod
1026
- def _complete_dict(cls, tag_dict):
1027
- """Add all aliased and aliasing tags to the dictionary."""
1028
- alias_dict = cls.alias_dict
1029
- deprecated_tags = set(tag_dict.keys()).intersection(alias_dict.keys())
1030
- new_tags = set(tag_dict.keys()).intersection(alias_dict.values())
1031
-
1032
- if len(deprecated_tags) > 0 or len(new_tags) > 0:
1033
- new_tag_dict = deepcopy(tag_dict)
1034
- # for all tag strings being set, write the value
1035
- # to all tags that could *be aliased by* the string
1036
- # and all tags that could be *aliasing* the string
1037
- # this way we ensure upwards and downwards compatibility
1038
- for old_tag, new_tag in alias_dict.items():
1039
- for tag in tag_dict:
1040
- if tag == old_tag and new_tag != "":
1041
- new_tag_dict[new_tag] = tag_dict[tag]
1042
- if tag == new_tag:
1043
- new_tag_dict[old_tag] = tag_dict[tag]
1044
- return new_tag_dict
1045
- else:
1046
- return tag_dict
1047
-
1048
- @classmethod
1049
- def _deprecate_tag_warn(cls, tags):
1050
- """Print warning message for tag deprecation.
1051
-
1052
- Parameters
1053
- ----------
1054
- tags : list of str
1055
-
1056
- Raises
1057
- ------
1058
- DeprecationWarning for each tag in tags that is aliased by cls.alias_dict
1059
- """
1060
- for tag_name in tags:
1061
- if tag_name in cls.alias_dict.keys():
1062
- version = cls.deprecate_dict[tag_name]
1063
- new_tag = cls.alias_dict[tag_name]
1064
- msg = f"tag {tag_name!r} will be removed in sktime version {version}"
1065
- if new_tag != "":
1066
- msg += (
1067
- f" and replaced by {new_tag!r}, please use {new_tag!r} instead"
1068
- )
1069
- else:
1070
- msg += ", please remove code that access or sets {tag_name!r}"
1071
- warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
1072
-
1073
-
1074
- class BaseEstimator(BaseObject):
1075
- """Base class for estimators with scikit-learn and sktime design patterns.
1076
-
1077
- Extends BaseObject to include basic functionality for fittable estimators.
1078
- """
1079
-
1080
- # tuple of non-BaseObject classes that count as nested objects
1081
- # get_fitted_params will retrieve parameters from these, too
1082
- # override in descendant class - common choice: BaseEstimator from sklearn
1083
- GET_FITTED_PARAMS_NESTING = ()
1084
-
1085
- def __init__(self):
1086
- """Construct BaseEstimator."""
1087
- self._is_fitted = False
1088
- super(BaseEstimator, self).__init__()
1089
-
1090
- @property
1091
- def is_fitted(self):
1092
- """Whether `fit` has been called.
1093
-
1094
- Inspects object's `_is_fitted` attribute that should initialize to False
1095
- during object construction, and be set to True in calls to an object's
1096
- `fit` method.
1097
-
1098
- Returns
1099
- -------
1100
- bool
1101
- Whether the estimator has been `fit`.
1102
- """
1103
- return self._is_fitted
1104
-
1105
- def check_is_fitted(self):
1106
- """Check if the estimator has been fitted.
1107
-
1108
- Inspects object's `_is_fitted` attribute that should initialize to False
1109
- during object construction, and be set to True in calls to an object's
1110
- `fit` method.
1111
-
1112
- Raises
1113
- ------
1114
- NotFittedError
1115
- If the estimator has not been fitted yet.
1116
- """
1117
- if not self.is_fitted:
1118
- raise NotFittedError(
1119
- f"This instance of {self.__class__.__name__} has not been fitted yet. "
1120
- f"Please call `fit` first."
1121
- )
1122
-
1123
- def get_fitted_params(self, deep=True):
1124
- """Get fitted parameters.
1125
-
1126
- State required:
1127
- Requires state to be "fitted".
1128
-
1129
- Parameters
1130
- ----------
1131
- deep : bool, default=True
1132
- Whether to return fitted parameters of components.
1133
-
1134
- * If True, will return a dict of parameter name : value for this object,
1135
- including fitted parameters of fittable components
1136
- (= BaseEstimator-valued parameters).
1137
- * If False, will return a dict of parameter name : value for this object,
1138
- but not include fitted parameters of components.
1139
-
1140
- Returns
1141
- -------
1142
- fitted_params : dict with str-valued keys
1143
- Dictionary of fitted parameters, paramname : paramvalue
1144
- keys-value pairs include:
1145
-
1146
- * always: all fitted parameters of this object, as via `get_param_names`
1147
- values are fitted parameter value for that key, of this object
1148
- * if `deep=True`, also contains keys/value pairs of component parameters
1149
- parameters of components are indexed as `[componentname]__[paramname]`
1150
- all parameters of `componentname` appear as `paramname` with its value
1151
- * if `deep=True`, also contains arbitrary levels of component recursion,
1152
- e.g., `[componentname]__[componentcomponentname]__[paramname]`, etc
1153
- """
1154
- if not self.is_fitted:
1155
- raise NotFittedError(
1156
- f"estimator of type {type(self).__name__} has not been "
1157
- "fitted yet, please call fit on data before get_fitted_params"
1158
- )
1159
-
1160
- # collect non-nested fitted params of self
1161
- fitted_params = self._get_fitted_params()
1162
-
1163
- # the rest is only for nested parameters
1164
- # so, if deep=False, we simply return here
1165
- if not deep:
1166
- return fitted_params
1167
-
1168
- def sh(x):
1169
- """Shorthand to remove all underscores at end of a string."""
1170
- if x.endswith("_"):
1171
- return sh(x[:-1])
1172
- else:
1173
- return x
1174
-
1175
- # add all nested parameters from components that are skbase BaseEstimator
1176
- c_dict = self._components()
1177
- for c, comp in c_dict.items():
1178
- if isinstance(comp, BaseEstimator) and comp._is_fitted:
1179
- c_f_params = comp.get_fitted_params(deep=deep)
1180
- c_f_params = {f"{sh(c)}__{k}": v for k, v in c_f_params.items()}
1181
- fitted_params.update(c_f_params)
1182
-
1183
- # add all nested parameters from components that are sklearn estimators
1184
- # we do this recursively as we have to reach into nested sklearn estimators
1185
- any_components_left_to_process = True
1186
- old_new_params = fitted_params
1187
- # this loop recursively and iteratively processes components inside components
1188
- while any_components_left_to_process:
1189
- new_params = {}
1190
- for c, comp in old_new_params.items():
1191
- if isinstance(comp, self.GET_FITTED_PARAMS_NESTING):
1192
- c_f_params = self._get_fitted_params_default(comp)
1193
- c_f_params = {f"{sh(c)}__{k}": v for k, v in c_f_params.items()}
1194
- new_params.update(c_f_params)
1195
- fitted_params.update(new_params)
1196
- old_new_params = new_params.copy()
1197
- n_new_params = len(new_params)
1198
- any_components_left_to_process = n_new_params > 0
1199
-
1200
- return fitted_params
1201
-
1202
- def _get_fitted_params_default(self, obj=None):
1203
- """Obtain fitted params of object, per sklearn convention.
1204
-
1205
- Extracts a dict with {paramstr : paramvalue} contents,
1206
- where paramstr are all string names of "fitted parameters".
1207
-
1208
- A "fitted attribute" of obj is one that ends in "_" but does not start with "_".
1209
- "fitted parameters" are names of fitted attributes, minus the "_" at the end.
1210
-
1211
- Parameters
1212
- ----------
1213
- obj : any object, optional, default=self
1214
-
1215
- Returns
1216
- -------
1217
- fitted_params : dict with str keys
1218
- fitted parameters, keyed by names of fitted parameter
1219
- """
1220
- obj = obj if obj else self
1221
-
1222
- # default retrieves all self attributes ending in "_"
1223
- # and returns them with keys that have the "_" removed
1224
- #
1225
- # get all attributes ending in "_", exclude any that start with "_" (private)
1226
- fitted_params = [
1227
- attr for attr in dir(obj) if attr.endswith("_") and not attr.startswith("_")
1228
- ]
1229
- # remove the "_" at the end
1230
- fitted_param_dict = {
1231
- p[:-1]: getattr(obj, p) for p in fitted_params if hasattr(obj, p)
1232
- }
1233
-
1234
- return fitted_param_dict
1235
-
1236
- def _get_fitted_params(self):
1237
- """Get fitted parameters.
1238
-
1239
- private _get_fitted_params, called from get_fitted_params
1240
-
1241
- State required:
1242
- Requires state to be "fitted".
1243
-
1244
- Returns
1245
- -------
1246
- fitted_params : dict with str keys
1247
- fitted parameters, keyed by names of fitted parameter
1248
- """
1249
- return self._get_fitted_params_default()
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 re
57
+ import warnings
58
+ from collections import defaultdict
59
+ from copy import deepcopy
60
+ from typing import List
61
+
62
+ from skbase._exceptions import NotFittedError
63
+ from skbase.base._pretty_printing._object_html_repr import _object_html_repr
64
+ from skbase.base._tagmanager import _FlagManager
65
+
66
+ __author__: List[str] = ["mloning", "RNKuhns", "fkiraly"]
67
+ __all__: List[str] = ["BaseEstimator", "BaseObject"]
68
+
69
+
70
+ class BaseObject(_FlagManager):
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
+ _config = {
77
+ "display": "diagram",
78
+ "print_changed_only": True,
79
+ "check_clone": False, # whether to execute validity checks in clone
80
+ }
81
+
82
+ def __init__(self):
83
+ """Construct BaseObject."""
84
+ self._init_flags(flag_attr_name="_tags")
85
+ self._init_flags(flag_attr_name="_config")
86
+ super(BaseObject, self).__init__()
87
+
88
+ def __eq__(self, other):
89
+ """Equality dunder. Checks equal class and parameters.
90
+
91
+ Returns True iff result of get_params(deep=False)
92
+ results in equal parameter sets.
93
+
94
+ Nested BaseObject descendants from get_params are compared via __eq__ as well.
95
+ """
96
+ from skbase.utils.deep_equals import deep_equals
97
+
98
+ if not isinstance(other, BaseObject):
99
+ return False
100
+
101
+ self_params = self.get_params(deep=False)
102
+ other_params = other.get_params(deep=False)
103
+
104
+ return deep_equals(self_params, other_params)
105
+
106
+ def reset(self):
107
+ """Reset the object to a clean post-init state.
108
+
109
+ Using reset, runs __init__ with current values of hyper-parameters
110
+ (result of get_params). This Removes any object attributes, except:
111
+
112
+ - hyper-parameters = arguments of __init__
113
+ - object attributes containing double-underscores, i.e., the string "__"
114
+
115
+ Class and object methods, and class attributes are also unaffected.
116
+
117
+ Returns
118
+ -------
119
+ self
120
+ Instance of class reset to a clean post-init state but retaining
121
+ the current hyper-parameter values.
122
+
123
+ Notes
124
+ -----
125
+ Equivalent to sklearn.clone but overwrites self. After self.reset()
126
+ call, self is equal in value to `type(self)(**self.get_params(deep=False))`
127
+ """
128
+ # retrieve parameters to copy them later
129
+ params = self.get_params(deep=False)
130
+
131
+ # delete all object attributes in self
132
+ attrs = [attr for attr in dir(self) if "__" not in attr]
133
+ cls_attrs = list(dir(type(self)))
134
+ self_attrs = set(attrs).difference(cls_attrs)
135
+ for attr in self_attrs:
136
+ delattr(self, attr)
137
+
138
+ # run init with a copy of parameters self had at the start
139
+ self.__init__(**params)
140
+
141
+ return self
142
+
143
+ def clone(self):
144
+ """Obtain a clone of the object with same hyper-parameters.
145
+
146
+ A clone is a different object without shared references, in post-init state.
147
+ This function is equivalent to returning sklearn.clone of self.
148
+
149
+ Raises
150
+ ------
151
+ RuntimeError if the clone is non-conforming, due to faulty ``__init__``.
152
+
153
+ Notes
154
+ -----
155
+ If successful, equal in value to ``type(self)(**self.get_params(deep=False))``.
156
+ """
157
+ self_params = self.get_params(deep=False)
158
+ self_clone = self._clone(self)
159
+
160
+ # if checking the clone is turned off, return now
161
+ if not self.get_config()["check_clone"]:
162
+ return self_clone
163
+
164
+ from skbase.utils.deep_equals import deep_equals
165
+
166
+ # check that all attributes are written to the clone
167
+ for attrname in self_params.keys():
168
+ if not hasattr(self_clone, attrname):
169
+ raise RuntimeError(
170
+ f"error in {self}.clone, __init__ must write all arguments "
171
+ f"to self and not mutate them, but {attrname} was not found. "
172
+ f"Please check __init__ of {self}."
173
+ )
174
+
175
+ clone_attrs = {attr: getattr(self_clone, attr) for attr in self_params.keys()}
176
+
177
+ # check equality of parameters post-clone and pre-clone
178
+ clone_attrs_valid, msg = deep_equals(self_params, clone_attrs, return_msg=True)
179
+ if not clone_attrs_valid:
180
+ raise RuntimeError(
181
+ f"error in {self}.clone, __init__ must write all arguments "
182
+ f"to self and not mutate them, but this is not the case. "
183
+ f"Error on equality check of arguments (x) vs parameters (y): {msg}"
184
+ )
185
+
186
+ return self_clone
187
+
188
+ # copied from sklearn
189
+ def _clone(self, estimator, *, safe=True):
190
+ """Construct a new unfitted estimator with the same parameters.
191
+
192
+ Clone does a deep copy of the model in an estimator
193
+ without actually copying attached data. It returns a new estimator
194
+ with the same parameters that has not been fitted on any data.
195
+
196
+ Parameters
197
+ ----------
198
+ estimator : {list, tuple, set} of estimator instance or a single \
199
+ estimator instance
200
+ The estimator or group of estimators to be cloned.
201
+ safe : bool, default=True
202
+ If safe is False, clone will fall back to a deep copy on objects
203
+ that are not estimators.
204
+
205
+ Returns
206
+ -------
207
+ estimator : object
208
+ The deep copy of the input, an estimator if input is an estimator.
209
+
210
+ Notes
211
+ -----
212
+ If the estimator's `random_state` parameter is an integer (or if the
213
+ estimator doesn't have a `random_state` parameter), an *exact clone* is
214
+ returned: the clone and the original estimator will give the exact same
215
+ results. Otherwise, *statistical clone* is returned: the clone might
216
+ return different results from the original estimator. More details can be
217
+ found in :ref:`randomness`.
218
+ """
219
+ estimator_type = type(estimator)
220
+ # XXX: not handling dictionaries
221
+ if estimator_type in (list, tuple, set, frozenset):
222
+ return estimator_type([self._clone(e, safe=safe) for e in estimator])
223
+ elif not hasattr(estimator, "get_params") or isinstance(estimator, type):
224
+ if not safe:
225
+ return deepcopy(estimator)
226
+ else:
227
+ if isinstance(estimator, type):
228
+ raise TypeError(
229
+ "Cannot clone object. "
230
+ + "You should provide an instance of "
231
+ + "scikit-learn estimator instead of a class."
232
+ )
233
+ else:
234
+ raise TypeError(
235
+ "Cannot clone object '%s' (type %s): "
236
+ "it does not seem to be a scikit-learn "
237
+ "estimator as it does not implement a "
238
+ "'get_params' method." % (repr(estimator), type(estimator))
239
+ )
240
+
241
+ klass = estimator.__class__
242
+ new_object_params = estimator.get_params(deep=False)
243
+ for name, param in new_object_params.items():
244
+ new_object_params[name] = self._clone(param, safe=False)
245
+ new_object = klass(**new_object_params)
246
+ params_set = new_object.get_params(deep=False)
247
+
248
+ # quick sanity check of the parameters of the clone
249
+ for name in new_object_params:
250
+ param1 = new_object_params[name]
251
+ param2 = params_set[name]
252
+ if param1 is not param2:
253
+ raise RuntimeError(
254
+ "Cannot clone object %s, as the constructor "
255
+ "either does not set or modifies parameter %s" % (estimator, name)
256
+ )
257
+ return new_object
258
+
259
+ @classmethod
260
+ def _get_init_signature(cls):
261
+ """Get class init sigature.
262
+
263
+ Useful in parameter inspection.
264
+
265
+ Returns
266
+ -------
267
+ List
268
+ The inspected parameter objects (including defaults).
269
+
270
+ Raises
271
+ ------
272
+ RuntimeError if cls has varargs in __init__.
273
+ """
274
+ # fetch the constructor or the original constructor before
275
+ # deprecation wrapping if any
276
+ init = getattr(cls.__init__, "deprecated_original", cls.__init__)
277
+ if init is object.__init__:
278
+ # No explicit constructor to introspect
279
+ return []
280
+
281
+ # introspect the constructor arguments to find the model parameters
282
+ # to represent
283
+ init_signature = inspect.signature(init)
284
+
285
+ # Consider the constructor parameters excluding 'self'
286
+ parameters = [
287
+ p
288
+ for p in init_signature.parameters.values()
289
+ if p.name != "self" and p.kind != p.VAR_KEYWORD
290
+ ]
291
+ for p in parameters:
292
+ if p.kind == p.VAR_POSITIONAL:
293
+ raise RuntimeError(
294
+ "scikit-learn compatible estimators should always "
295
+ "specify their parameters in the signature"
296
+ " of their __init__ (no varargs)."
297
+ " %s with constructor %s doesn't "
298
+ " follow this convention." % (cls, init_signature)
299
+ )
300
+ return parameters
301
+
302
+ @classmethod
303
+ def get_param_names(cls):
304
+ """Get object's parameter names.
305
+
306
+ Returns
307
+ -------
308
+ param_names: list[str]
309
+ Alphabetically sorted list of parameter names of cls.
310
+ """
311
+ parameters = cls._get_init_signature()
312
+ param_names = sorted([p.name for p in parameters])
313
+ return param_names
314
+
315
+ @classmethod
316
+ def get_param_defaults(cls):
317
+ """Get object's parameter defaults.
318
+
319
+ Returns
320
+ -------
321
+ default_dict: dict[str, Any]
322
+ Keys are all parameters of cls that have a default defined in __init__
323
+ values are the defaults, as defined in __init__.
324
+ """
325
+ parameters = cls._get_init_signature()
326
+ default_dict = {
327
+ x.name: x.default for x in parameters if x.default != inspect._empty
328
+ }
329
+ return default_dict
330
+
331
+ def get_params(self, deep=True):
332
+ """Get a dict of parameters values for this object.
333
+
334
+ Parameters
335
+ ----------
336
+ deep : bool, default=True
337
+ Whether to return parameters of components.
338
+
339
+ * If True, will return a dict of parameter name : value for this object,
340
+ including parameters of components (= BaseObject-valued parameters).
341
+ * If False, will return a dict of parameter name : value for this object,
342
+ but not include parameters of components.
343
+
344
+ Returns
345
+ -------
346
+ params : dict with str-valued keys
347
+ Dictionary of parameters, paramname : paramvalue
348
+ keys-value pairs include:
349
+
350
+ * always: all parameters of this object, as via `get_param_names`
351
+ values are parameter value for that key, of this object
352
+ values are always identical to values passed at construction
353
+ * if `deep=True`, also contains keys/value pairs of component parameters
354
+ parameters of components are indexed as `[componentname]__[paramname]`
355
+ all parameters of `componentname` appear as `paramname` with its value
356
+ * if `deep=True`, also contains arbitrary levels of component recursion,
357
+ e.g., `[componentname]__[componentcomponentname]__[paramname]`, etc
358
+ """
359
+ params = {key: getattr(self, key) for key in self.get_param_names()}
360
+
361
+ if deep:
362
+ deep_params = {}
363
+ for key, value in params.items():
364
+ if hasattr(value, "get_params"):
365
+ deep_items = value.get_params().items()
366
+ deep_params.update({f"{key}__{k}": val for k, val in deep_items})
367
+ params.update(deep_params)
368
+
369
+ return params
370
+
371
+ def set_params(self, **params):
372
+ """Set the parameters of this object.
373
+
374
+ The method works on simple estimators as well as on nested objects.
375
+ The latter have parameters of the form ``<component>__<parameter>`` so
376
+ that it's possible to update each component of a nested object.
377
+
378
+ Parameters
379
+ ----------
380
+ **params : dict
381
+ BaseObject parameters.
382
+
383
+ Returns
384
+ -------
385
+ self
386
+ Reference to self (after parameters have been set).
387
+ """
388
+ if not params:
389
+ # Simple optimization to gain speed (inspect is slow)
390
+ return self
391
+ valid_params = self.get_params(deep=True)
392
+
393
+ nested_params = defaultdict(dict) # grouped by prefix
394
+ for key, value in params.items():
395
+ key, delim, sub_key = key.partition("__")
396
+ if key not in valid_params:
397
+ raise ValueError(
398
+ "Invalid parameter %s for object %s. "
399
+ "Check the list of available parameters "
400
+ "with `object.get_params().keys()`." % (key, self)
401
+ )
402
+
403
+ if delim:
404
+ nested_params[key][sub_key] = value
405
+ else:
406
+ setattr(self, key, value)
407
+ valid_params[key] = value
408
+
409
+ self.reset()
410
+
411
+ # recurse in components
412
+ for key, sub_params in nested_params.items():
413
+ valid_params[key].set_params(**sub_params)
414
+
415
+ return self
416
+
417
+ @classmethod
418
+ def get_class_tags(cls):
419
+ """Get class tags from the class and all its parent classes.
420
+
421
+ Retrieves tag: value pairs from _tags class attribute. Does not return
422
+ information from dynamic tags (set via set_tags or clone_tags)
423
+ that are defined on instances.
424
+
425
+ Returns
426
+ -------
427
+ collected_tags : dict
428
+ Dictionary of class tag name: tag value pairs. Collected from _tags
429
+ class attribute via nested inheritance.
430
+ """
431
+ return cls._get_class_flags(flag_attr_name="_tags")
432
+
433
+ @classmethod
434
+ def get_class_tag(cls, tag_name, tag_value_default=None):
435
+ """Get a class tag's value.
436
+
437
+ Does not return information from dynamic tags (set via set_tags or clone_tags)
438
+ that are defined on instances.
439
+
440
+ Parameters
441
+ ----------
442
+ tag_name : str
443
+ Name of tag value.
444
+ tag_value_default : any
445
+ Default/fallback value if tag is not found.
446
+
447
+ Returns
448
+ -------
449
+ tag_value :
450
+ Value of the `tag_name` tag in self. If not found, returns
451
+ `tag_value_default`.
452
+ """
453
+ return cls._get_class_flag(
454
+ flag_name=tag_name,
455
+ flag_value_default=tag_value_default,
456
+ flag_attr_name="_tags",
457
+ )
458
+
459
+ def get_tags(self):
460
+ """Get tags from estimator class and dynamic tag overrides.
461
+
462
+ Returns
463
+ -------
464
+ collected_tags : dict
465
+ Dictionary of tag name : tag value pairs. Collected from _tags
466
+ class attribute via nested inheritance and then any overrides
467
+ and new tags from _tags_dynamic object attribute.
468
+ """
469
+ return self._get_flags(flag_attr_name="_tags")
470
+
471
+ def get_tag(self, tag_name, tag_value_default=None, raise_error=True):
472
+ """Get tag value from estimator class and dynamic tag overrides.
473
+
474
+ Parameters
475
+ ----------
476
+ tag_name : str
477
+ Name of tag to be retrieved
478
+ tag_value_default : any type, optional; default=None
479
+ Default/fallback value if tag is not found
480
+ raise_error : bool
481
+ whether a ValueError is raised when the tag is not found
482
+
483
+ Returns
484
+ -------
485
+ tag_value : Any
486
+ Value of the `tag_name` tag in self. If not found, returns an error if
487
+ `raise_error` is True, otherwise it returns `tag_value_default`.
488
+
489
+ Raises
490
+ ------
491
+ ValueError if raise_error is True i.e. if `tag_name` is not in
492
+ self.get_tags().keys()
493
+ """
494
+ return self._get_flag(
495
+ flag_name=tag_name,
496
+ flag_value_default=tag_value_default,
497
+ raise_error=raise_error,
498
+ flag_attr_name="_tags",
499
+ )
500
+
501
+ def set_tags(self, **tag_dict):
502
+ """Set dynamic tags to given values.
503
+
504
+ Parameters
505
+ ----------
506
+ **tag_dict : dict
507
+ Dictionary of tag name: tag value pairs.
508
+
509
+ Returns
510
+ -------
511
+ Self
512
+ Reference to self.
513
+
514
+ Notes
515
+ -----
516
+ Changes object state by settting tag values in tag_dict as dynamic tags in self.
517
+ """
518
+ self._set_flags(flag_attr_name="_tags", **tag_dict)
519
+
520
+ return self
521
+
522
+ def clone_tags(self, estimator, tag_names=None):
523
+ """Clone tags from another estimator as dynamic override.
524
+
525
+ Parameters
526
+ ----------
527
+ estimator : estimator inheriting from :class:BaseEstimator
528
+ tag_names : str or list of str, default = None
529
+ Names of tags to clone. If None then all tags in estimator are used
530
+ as `tag_names`.
531
+
532
+ Returns
533
+ -------
534
+ Self :
535
+ Reference to self.
536
+
537
+ Notes
538
+ -----
539
+ Changes object state by setting tag values in tag_set from estimator as
540
+ dynamic tags in self.
541
+ """
542
+ self._clone_flags(
543
+ estimator=estimator, flag_names=tag_names, flag_attr_name="_tags"
544
+ )
545
+
546
+ return self
547
+
548
+ def get_config(self):
549
+ """Get config flags for self.
550
+
551
+ Returns
552
+ -------
553
+ config_dict : dict
554
+ Dictionary of config name : config value pairs. Collected from _config
555
+ class attribute via nested inheritance and then any overrides
556
+ and new tags from _onfig_dynamic object attribute.
557
+ """
558
+ return self._get_flags(flag_attr_name="_config")
559
+
560
+ def set_config(self, **config_dict):
561
+ """Set config flags to given values.
562
+
563
+ Parameters
564
+ ----------
565
+ config_dict : dict
566
+ Dictionary of config name : config value pairs.
567
+
568
+ Returns
569
+ -------
570
+ self : reference to self.
571
+
572
+ Notes
573
+ -----
574
+ Changes object state, copies configs in config_dict to self._config_dynamic.
575
+ """
576
+ self._set_flags(flag_attr_name="_config", **config_dict)
577
+
578
+ return self
579
+
580
+ @classmethod
581
+ def get_test_params(cls, parameter_set="default"):
582
+ """Return testing parameter settings for the estimator.
583
+
584
+ Parameters
585
+ ----------
586
+ parameter_set : str, default="default"
587
+ Name of the set of test parameters to return, for use in tests. If no
588
+ special parameters are defined for a value, will return `"default"` set.
589
+
590
+ Returns
591
+ -------
592
+ params : dict or list of dict, default = {}
593
+ Parameters to create testing instances of the class
594
+ Each dict are parameters to construct an "interesting" test instance, i.e.,
595
+ `MyClass(**params)` or `MyClass(**params[i])` creates a valid test instance.
596
+ `create_test_instance` uses the first (or only) dictionary in `params`
597
+ """
598
+ # if non-default parameters are required, but none have been found, raise error
599
+ if hasattr(cls, "_required_parameters"):
600
+ required_parameters = getattr(cls, "_required_parameters", [])
601
+ if len(required_parameters) > 0:
602
+ raise ValueError(
603
+ f"Estimator: {cls} requires "
604
+ f"non-default parameters for construction, "
605
+ f"but none were given. Please set them "
606
+ f"as given in the extension template"
607
+ )
608
+
609
+ # construct with parameter configuration for testing, otherwise construct with
610
+ # default parameters (empty dict)
611
+ params = {}
612
+ return params
613
+
614
+ @classmethod
615
+ def create_test_instance(cls, parameter_set="default"):
616
+ """Construct Estimator instance if possible.
617
+
618
+ Parameters
619
+ ----------
620
+ parameter_set : str, default="default"
621
+ Name of the set of test parameters to return, for use in tests. If no
622
+ special parameters are defined for a value, will return `"default"` set.
623
+
624
+ Returns
625
+ -------
626
+ instance : instance of the class with default parameters
627
+
628
+ Notes
629
+ -----
630
+ `get_test_params` can return dict or list of dict.
631
+ This function takes first or single dict that get_test_params returns, and
632
+ constructs the object with that.
633
+ """
634
+ if "parameter_set" in inspect.getfullargspec(cls.get_test_params).args:
635
+ params = cls.get_test_params(parameter_set=parameter_set)
636
+ else:
637
+ params = cls.get_test_params()
638
+
639
+ if isinstance(params, list) and isinstance(params[0], dict):
640
+ params = params[0]
641
+ elif isinstance(params, dict):
642
+ pass
643
+ else:
644
+ raise TypeError(
645
+ "get_test_params should either return a dict or list of dict."
646
+ )
647
+
648
+ return cls(**params)
649
+
650
+ @classmethod
651
+ def create_test_instances_and_names(cls, parameter_set="default"):
652
+ """Create list of all test instances and a list of names for them.
653
+
654
+ Parameters
655
+ ----------
656
+ parameter_set : str, default="default"
657
+ Name of the set of test parameters to return, for use in tests. If no
658
+ special parameters are defined for a value, will return `"default"` set.
659
+
660
+ Returns
661
+ -------
662
+ objs : list of instances of cls
663
+ i-th instance is cls(**cls.get_test_params()[i])
664
+ names : list of str, same length as objs
665
+ i-th element is name of i-th instance of obj in tests
666
+ convention is {cls.__name__}-{i} if more than one instance
667
+ otherwise {cls.__name__}
668
+ parameter_set : str, default="default"
669
+ Name of the set of test parameters to return, for use in tests. If no
670
+ special parameters are defined for a value, will return `"default"` set.
671
+ """
672
+ if "parameter_set" in inspect.getfullargspec(cls.get_test_params).args:
673
+ param_list = cls.get_test_params(parameter_set=parameter_set)
674
+ else:
675
+ param_list = cls.get_test_params()
676
+
677
+ objs = []
678
+ if not isinstance(param_list, (dict, list)):
679
+ raise RuntimeError(
680
+ f"Error in {cls.__name__}.get_test_params, "
681
+ "return must be param dict for class, or list thereof"
682
+ )
683
+ if isinstance(param_list, dict):
684
+ param_list = [param_list]
685
+ for params in param_list:
686
+ if not isinstance(params, dict):
687
+ raise RuntimeError(
688
+ f"Error in {cls.__name__}.get_test_params, "
689
+ "return must be param dict for class, or list thereof"
690
+ )
691
+ objs += [cls(**params)]
692
+
693
+ num_instances = len(param_list)
694
+ if num_instances > 1:
695
+ names = [cls.__name__ + "-" + str(i) for i in range(num_instances)]
696
+ else:
697
+ names = [cls.__name__]
698
+
699
+ return objs, names
700
+
701
+ @classmethod
702
+ def _has_implementation_of(cls, method):
703
+ """Check if method has a concrete implementation in this class.
704
+
705
+ This assumes that having an implementation is equivalent to
706
+ one or more overrides of `method` in the method resolution order.
707
+
708
+ Parameters
709
+ ----------
710
+ method : str, name of method to check implementation of
711
+
712
+ Returns
713
+ -------
714
+ bool, whether method has implementation in cls
715
+ True if cls.method has been overridden at least once in
716
+ the inheritance tree (according to method resolution order)
717
+ """
718
+ # walk through method resolution order and inspect methods
719
+ # of classes and direct parents, "adjacent" classes in mro
720
+ mro = inspect.getmro(cls)
721
+ # collect all methods that are not none
722
+ methods = [getattr(c, method, None) for c in mro]
723
+ methods = [m for m in methods if m is not None]
724
+
725
+ for i in range(len(methods) - 1):
726
+ # the method has been overridden once iff
727
+ # at least two of the methods collected are not equal
728
+ # equivalently: some two adjacent methods are not equal
729
+ overridden = methods[i] != methods[i + 1]
730
+ if overridden:
731
+ return True
732
+
733
+ return False
734
+
735
+ def is_composite(self):
736
+ """Check if the object is composed of other BaseObjects.
737
+
738
+ A composite object is an object which contains objects, as parameters.
739
+ Called on an instance, since this may differ by instance.
740
+
741
+ Returns
742
+ -------
743
+ composite: bool
744
+ Whether an object has any parameters whose values
745
+ are BaseObjects.
746
+ """
747
+ # walk through method resolution order and inspect methods
748
+ # of classes and direct parents, "adjacent" classes in mro
749
+ params = self.get_params(deep=False)
750
+ composite = any(isinstance(x, BaseObject) for x in params.values())
751
+
752
+ return composite
753
+
754
+ def _components(self, base_class=None):
755
+ """Return references to all state changing BaseObject type attributes.
756
+
757
+ This *excludes* the blue-print-like components passed in the __init__.
758
+
759
+ Caution: this method returns *references* and not *copies*.
760
+ Writing to the reference will change the respective attribute of self.
761
+
762
+ Parameters
763
+ ----------
764
+ base_class : class, optional, default=None, must be subclass of BaseObject
765
+ if not None, sub-sets return dict to only descendants of base_class
766
+
767
+ Returns
768
+ -------
769
+ dict with key = attribute name, value = reference to that BaseObject attribute
770
+ dict contains all attributes of self that inherit from BaseObjects, and:
771
+ whose names do not contain the string "__", e.g., hidden attributes
772
+ are not class attributes, and are not hyper-parameters (__init__ args)
773
+ """
774
+ if base_class is None:
775
+ base_class = BaseObject
776
+ if base_class is not None and not inspect.isclass(base_class):
777
+ raise TypeError(f"base_class must be a class, but found {type(base_class)}")
778
+ if base_class is not None and not issubclass(base_class, BaseObject):
779
+ raise TypeError("base_class must be a subclass of BaseObject")
780
+
781
+ # retrieve parameter names to exclude them later
782
+ param_names = self.get_params(deep=False).keys()
783
+
784
+ # retrieve all attributes that are BaseObject descendants
785
+ attrs = [attr for attr in dir(self) if "__" not in attr]
786
+ cls_attrs = list(dir(type(self)))
787
+ self_attrs = set(attrs).difference(cls_attrs).difference(param_names)
788
+
789
+ comp_dict = {x: getattr(self, x) for x in self_attrs}
790
+ comp_dict = {x: y for (x, y) in comp_dict.items() if isinstance(y, base_class)}
791
+
792
+ return comp_dict
793
+
794
+ def __repr__(self, n_char_max: int = 700):
795
+ """Represent class as string.
796
+
797
+ This follows the scikit-learn implementation for the string representation
798
+ of parameterized objects.
799
+
800
+ Parameters
801
+ ----------
802
+ n_char_max : int
803
+ Maximum (approximate) number of non-blank characters to render. This
804
+ can be useful in testing.
805
+ """
806
+ from skbase.base._pretty_printing._pprint import _BaseObjectPrettyPrinter
807
+
808
+ n_max_elements_to_show = 30 # number of elements to show in sequences
809
+ # use ellipsis for sequences with a lot of elements
810
+ pp = _BaseObjectPrettyPrinter(
811
+ compact=True,
812
+ indent=1,
813
+ indent_at_name=True,
814
+ n_max_elements_to_show=n_max_elements_to_show,
815
+ changed_only=self.get_config()["print_changed_only"],
816
+ )
817
+
818
+ repr_ = pp.pformat(self)
819
+
820
+ # Use bruteforce ellipsis when there are a lot of non-blank characters
821
+ n_nonblank = len("".join(repr_.split()))
822
+ if n_nonblank > n_char_max:
823
+ lim = n_char_max // 2 # apprx number of chars to keep on both ends
824
+ regex = r"^(\s*\S){%d}" % lim
825
+ # The regex '^(\s*\S){%d}' matches from the start of the string
826
+ # until the nth non-blank character:
827
+ # - ^ matches the start of string
828
+ # - (pattern){n} matches n repetitions of pattern
829
+ # - \s*\S matches a non-blank char following zero or more blanks
830
+ left_match = re.match(regex, repr_)
831
+ right_match = re.match(regex, repr_[::-1])
832
+ left_lim = left_match.end() if left_match is not None else 0
833
+ right_lim = right_match.end() if right_match is not None else 0
834
+
835
+ if "\n" in repr_[left_lim:-right_lim]:
836
+ # The left side and right side aren't on the same line.
837
+ # To avoid weird cuts, e.g.:
838
+ # categoric...ore',
839
+ # we need to start the right side with an appropriate newline
840
+ # character so that it renders properly as:
841
+ # categoric...
842
+ # handle_unknown='ignore',
843
+ # so we add [^\n]*\n which matches until the next \n
844
+ regex += r"[^\n]*\n"
845
+ right_match = re.match(regex, repr_[::-1])
846
+ right_lim = right_match.end() if right_match is not None else 0
847
+
848
+ ellipsis = "..."
849
+ if left_lim + len(ellipsis) < len(repr_) - right_lim:
850
+ # Only add ellipsis if it results in a shorter repr
851
+ repr_ = repr_[:left_lim] + "..." + repr_[-right_lim:]
852
+
853
+ return repr_
854
+
855
+ @property
856
+ def _repr_html_(self):
857
+ """HTML representation of BaseObject.
858
+
859
+ This is redundant with the logic of `_repr_mimebundle_`. The latter
860
+ should be favorted in the long term, `_repr_html_` is only
861
+ implemented for consumers who do not interpret `_repr_mimbundle_`.
862
+ """
863
+ if self.get_config()["display"] != "diagram":
864
+ raise AttributeError(
865
+ "_repr_html_ is only defined when the "
866
+ "`display` configuration option is set to 'diagram'."
867
+ )
868
+ return self._repr_html_inner
869
+
870
+ def _repr_html_inner(self):
871
+ """Return HTML representation of class.
872
+
873
+ This function is returned by the @property `_repr_html_` to make
874
+ `hasattr(BaseObject, "_repr_html_") return `True` or `False` depending
875
+ on `self.get_config()["display"]`.
876
+ """
877
+ return _object_html_repr(self)
878
+
879
+ def _repr_mimebundle_(self, **kwargs):
880
+ """Mime bundle used by jupyter kernels to display instances of BaseObject."""
881
+ output = {"text/plain": repr(self)}
882
+ if self.get_config()["display"] == "diagram":
883
+ output["text/html"] = _object_html_repr(self)
884
+ return output
885
+
886
+
887
+ class TagAliaserMixin:
888
+ """Mixin class for tag aliasing and deprecation of old tags.
889
+
890
+ To deprecate tags, add the TagAliaserMixin to BaseObject or BaseEstimator.
891
+ alias_dict contains the deprecated tags, and supports removal and renaming.
892
+ For removal, add an entry "old_tag_name": ""
893
+ For renaming, add an entry "old_tag_name": "new_tag_name"
894
+ deprecate_dict contains the version number of renaming or removal.
895
+ the keys in deprecate_dict should be the same as in alias_dict.
896
+ values in deprecate_dict should be strings, the version of removal/renaming.
897
+
898
+ The class will ensure that new tags alias old tags and vice versa, during
899
+ the deprecation period. Informative warnings will be raised whenever the
900
+ deprecated tags are being accessed.
901
+
902
+ When removing tags, ensure to remove the removed tags from this class.
903
+ If no tags are deprecated anymore (e.g., all deprecated tags are removed/renamed),
904
+ ensure toremove this class as a parent of BaseObject or BaseEstimator.
905
+ """
906
+
907
+ # dictionary of aliases
908
+ # key = old tag; value = new tag, aliased by old tag
909
+ # override this in a child class
910
+ alias_dict = {"old_tag": "new_tag", "tag_to_remove": ""}
911
+
912
+ # dictionary of removal version
913
+ # key = old tag; value = version in which tag will be removed, as string
914
+ deprecate_dict = {"old_tag": "0.12.0", "tag_to_remove": "99.99.99"}
915
+
916
+ def __init__(self):
917
+ """Construct TagAliaserMixin."""
918
+ super(TagAliaserMixin, self).__init__()
919
+
920
+ @classmethod
921
+ def get_class_tags(cls):
922
+ """Get class tags from estimator class and all its parent classes.
923
+
924
+ Returns
925
+ -------
926
+ collected_tags : dict
927
+ Dictionary of tag name : tag value pairs. Collected from _tags
928
+ class attribute via nested inheritance. NOT overridden by dynamic
929
+ tags set by set_tags or mirror_tags.
930
+ """
931
+ collected_tags = super(TagAliaserMixin, cls).get_class_tags()
932
+ collected_tags = cls._complete_dict(collected_tags)
933
+ return collected_tags
934
+
935
+ @classmethod
936
+ def get_class_tag(cls, tag_name, tag_value_default=None):
937
+ """Get tag value from estimator class (only class tags).
938
+
939
+ Parameters
940
+ ----------
941
+ tag_name : str
942
+ Name of tag value.
943
+ tag_value_default : any type
944
+ Default/fallback value if tag is not found.
945
+
946
+ Returns
947
+ -------
948
+ tag_value :
949
+ Value of the `tag_name` tag in self. If not found, returns
950
+ `tag_value_default`.
951
+ """
952
+ cls._deprecate_tag_warn([tag_name])
953
+ return super(TagAliaserMixin, cls).get_class_tag(
954
+ tag_name=tag_name, tag_value_default=tag_value_default
955
+ )
956
+
957
+ def get_tags(self):
958
+ """Get tags from estimator class and dynamic tag overrides.
959
+
960
+ Returns
961
+ -------
962
+ collected_tags : dict
963
+ Dictionary of tag name : tag value pairs. Collected from _tags
964
+ class attribute via nested inheritance and then any overrides
965
+ and new tags from _tags_dynamic object attribute.
966
+ """
967
+ collected_tags = super(TagAliaserMixin, self).get_tags()
968
+ collected_tags = self._complete_dict(collected_tags)
969
+ return collected_tags
970
+
971
+ def get_tag(self, tag_name, tag_value_default=None, raise_error=True):
972
+ """Get tag value from estimator class and dynamic tag overrides.
973
+
974
+ Parameters
975
+ ----------
976
+ tag_name : str
977
+ Name of tag to be retrieved
978
+ tag_value_default : any type, optional; default=None
979
+ Default/fallback value if tag is not found
980
+ raise_error : bool
981
+ whether a ValueError is raised when the tag is not found
982
+
983
+ Returns
984
+ -------
985
+ tag_value :
986
+ Value of the `tag_name` tag in self. If not found, returns an error if
987
+ raise_error is True, otherwise it returns `tag_value_default`.
988
+
989
+ Raises
990
+ ------
991
+ ValueError if raise_error is True i.e. if tag_name is not in self.get_tags(
992
+ ).keys()
993
+ """
994
+ self._deprecate_tag_warn([tag_name])
995
+ return super(TagAliaserMixin, self).get_tag(
996
+ tag_name=tag_name,
997
+ tag_value_default=tag_value_default,
998
+ raise_error=raise_error,
999
+ )
1000
+
1001
+ def set_tags(self, **tag_dict):
1002
+ """Set dynamic tags to given values.
1003
+
1004
+ Parameters
1005
+ ----------
1006
+ tag_dict : dict
1007
+ Dictionary of tag name : tag value pairs.
1008
+
1009
+ Returns
1010
+ -------
1011
+ Self :
1012
+ Reference to self.
1013
+
1014
+ Notes
1015
+ -----
1016
+ Changes object state by settting tag values in tag_dict as dynamic tags
1017
+ in self.
1018
+ """
1019
+ self._deprecate_tag_warn(tag_dict.keys())
1020
+
1021
+ tag_dict = self._complete_dict(tag_dict)
1022
+ super(TagAliaserMixin, self).set_tags(**tag_dict)
1023
+ return self
1024
+
1025
+ @classmethod
1026
+ def _complete_dict(cls, tag_dict):
1027
+ """Add all aliased and aliasing tags to the dictionary."""
1028
+ alias_dict = cls.alias_dict
1029
+ deprecated_tags = set(tag_dict.keys()).intersection(alias_dict.keys())
1030
+ new_tags = set(tag_dict.keys()).intersection(alias_dict.values())
1031
+
1032
+ if len(deprecated_tags) > 0 or len(new_tags) > 0:
1033
+ new_tag_dict = deepcopy(tag_dict)
1034
+ # for all tag strings being set, write the value
1035
+ # to all tags that could *be aliased by* the string
1036
+ # and all tags that could be *aliasing* the string
1037
+ # this way we ensure upwards and downwards compatibility
1038
+ for old_tag, new_tag in alias_dict.items():
1039
+ for tag in tag_dict:
1040
+ if tag == old_tag and new_tag != "":
1041
+ new_tag_dict[new_tag] = tag_dict[tag]
1042
+ if tag == new_tag:
1043
+ new_tag_dict[old_tag] = tag_dict[tag]
1044
+ return new_tag_dict
1045
+ else:
1046
+ return tag_dict
1047
+
1048
+ @classmethod
1049
+ def _deprecate_tag_warn(cls, tags):
1050
+ """Print warning message for tag deprecation.
1051
+
1052
+ Parameters
1053
+ ----------
1054
+ tags : list of str
1055
+
1056
+ Raises
1057
+ ------
1058
+ DeprecationWarning for each tag in tags that is aliased by cls.alias_dict
1059
+ """
1060
+ for tag_name in tags:
1061
+ if tag_name in cls.alias_dict.keys():
1062
+ version = cls.deprecate_dict[tag_name]
1063
+ new_tag = cls.alias_dict[tag_name]
1064
+ msg = f"tag {tag_name!r} will be removed in sktime version {version}"
1065
+ if new_tag != "":
1066
+ msg += (
1067
+ f" and replaced by {new_tag!r}, please use {new_tag!r} instead"
1068
+ )
1069
+ else:
1070
+ msg += ", please remove code that access or sets {tag_name!r}"
1071
+ warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
1072
+
1073
+
1074
+ class BaseEstimator(BaseObject):
1075
+ """Base class for estimators with scikit-learn and sktime design patterns.
1076
+
1077
+ Extends BaseObject to include basic functionality for fittable estimators.
1078
+ """
1079
+
1080
+ # tuple of non-BaseObject classes that count as nested objects
1081
+ # get_fitted_params will retrieve parameters from these, too
1082
+ # override in descendant class - common choice: BaseEstimator from sklearn
1083
+ GET_FITTED_PARAMS_NESTING = ()
1084
+
1085
+ def __init__(self):
1086
+ """Construct BaseEstimator."""
1087
+ self._is_fitted = False
1088
+ super(BaseEstimator, self).__init__()
1089
+
1090
+ @property
1091
+ def is_fitted(self):
1092
+ """Whether `fit` has been called.
1093
+
1094
+ Inspects object's `_is_fitted` attribute that should initialize to False
1095
+ during object construction, and be set to True in calls to an object's
1096
+ `fit` method.
1097
+
1098
+ Returns
1099
+ -------
1100
+ bool
1101
+ Whether the estimator has been `fit`.
1102
+ """
1103
+ return self._is_fitted
1104
+
1105
+ def check_is_fitted(self):
1106
+ """Check if the estimator has been fitted.
1107
+
1108
+ Inspects object's `_is_fitted` attribute that should initialize to False
1109
+ during object construction, and be set to True in calls to an object's
1110
+ `fit` method.
1111
+
1112
+ Raises
1113
+ ------
1114
+ NotFittedError
1115
+ If the estimator has not been fitted yet.
1116
+ """
1117
+ if not self.is_fitted:
1118
+ raise NotFittedError(
1119
+ f"This instance of {self.__class__.__name__} has not been fitted yet. "
1120
+ f"Please call `fit` first."
1121
+ )
1122
+
1123
+ def get_fitted_params(self, deep=True):
1124
+ """Get fitted parameters.
1125
+
1126
+ State required:
1127
+ Requires state to be "fitted".
1128
+
1129
+ Parameters
1130
+ ----------
1131
+ deep : bool, default=True
1132
+ Whether to return fitted parameters of components.
1133
+
1134
+ * If True, will return a dict of parameter name : value for this object,
1135
+ including fitted parameters of fittable components
1136
+ (= BaseEstimator-valued parameters).
1137
+ * If False, will return a dict of parameter name : value for this object,
1138
+ but not include fitted parameters of components.
1139
+
1140
+ Returns
1141
+ -------
1142
+ fitted_params : dict with str-valued keys
1143
+ Dictionary of fitted parameters, paramname : paramvalue
1144
+ keys-value pairs include:
1145
+
1146
+ * always: all fitted parameters of this object, as via `get_param_names`
1147
+ values are fitted parameter value for that key, of this object
1148
+ * if `deep=True`, also contains keys/value pairs of component parameters
1149
+ parameters of components are indexed as `[componentname]__[paramname]`
1150
+ all parameters of `componentname` appear as `paramname` with its value
1151
+ * if `deep=True`, also contains arbitrary levels of component recursion,
1152
+ e.g., `[componentname]__[componentcomponentname]__[paramname]`, etc
1153
+ """
1154
+ if not self.is_fitted:
1155
+ raise NotFittedError(
1156
+ f"estimator of type {type(self).__name__} has not been "
1157
+ "fitted yet, please call fit on data before get_fitted_params"
1158
+ )
1159
+
1160
+ # collect non-nested fitted params of self
1161
+ fitted_params = self._get_fitted_params()
1162
+
1163
+ # the rest is only for nested parameters
1164
+ # so, if deep=False, we simply return here
1165
+ if not deep:
1166
+ return fitted_params
1167
+
1168
+ def sh(x):
1169
+ """Shorthand to remove all underscores at end of a string."""
1170
+ if x.endswith("_"):
1171
+ return sh(x[:-1])
1172
+ else:
1173
+ return x
1174
+
1175
+ # add all nested parameters from components that are skbase BaseEstimator
1176
+ c_dict = self._components()
1177
+ for c, comp in c_dict.items():
1178
+ if isinstance(comp, BaseEstimator) and comp._is_fitted:
1179
+ c_f_params = comp.get_fitted_params(deep=deep)
1180
+ c_f_params = {f"{sh(c)}__{k}": v for k, v in c_f_params.items()}
1181
+ fitted_params.update(c_f_params)
1182
+
1183
+ # add all nested parameters from components that are sklearn estimators
1184
+ # we do this recursively as we have to reach into nested sklearn estimators
1185
+ any_components_left_to_process = True
1186
+ old_new_params = fitted_params
1187
+ # this loop recursively and iteratively processes components inside components
1188
+ while any_components_left_to_process:
1189
+ new_params = {}
1190
+ for c, comp in old_new_params.items():
1191
+ if isinstance(comp, self.GET_FITTED_PARAMS_NESTING):
1192
+ c_f_params = self._get_fitted_params_default(comp)
1193
+ c_f_params = {f"{sh(c)}__{k}": v for k, v in c_f_params.items()}
1194
+ new_params.update(c_f_params)
1195
+ fitted_params.update(new_params)
1196
+ old_new_params = new_params.copy()
1197
+ n_new_params = len(new_params)
1198
+ any_components_left_to_process = n_new_params > 0
1199
+
1200
+ return fitted_params
1201
+
1202
+ def _get_fitted_params_default(self, obj=None):
1203
+ """Obtain fitted params of object, per sklearn convention.
1204
+
1205
+ Extracts a dict with {paramstr : paramvalue} contents,
1206
+ where paramstr are all string names of "fitted parameters".
1207
+
1208
+ A "fitted attribute" of obj is one that ends in "_" but does not start with "_".
1209
+ "fitted parameters" are names of fitted attributes, minus the "_" at the end.
1210
+
1211
+ Parameters
1212
+ ----------
1213
+ obj : any object, optional, default=self
1214
+
1215
+ Returns
1216
+ -------
1217
+ fitted_params : dict with str keys
1218
+ fitted parameters, keyed by names of fitted parameter
1219
+ """
1220
+ obj = obj if obj else self
1221
+
1222
+ # default retrieves all self attributes ending in "_"
1223
+ # and returns them with keys that have the "_" removed
1224
+ #
1225
+ # get all attributes ending in "_", exclude any that start with "_" (private)
1226
+ fitted_params = [
1227
+ attr for attr in dir(obj) if attr.endswith("_") and not attr.startswith("_")
1228
+ ]
1229
+ # remove the "_" at the end
1230
+ fitted_param_dict = {
1231
+ p[:-1]: getattr(obj, p) for p in fitted_params if hasattr(obj, p)
1232
+ }
1233
+
1234
+ return fitted_param_dict
1235
+
1236
+ def _get_fitted_params(self):
1237
+ """Get fitted parameters.
1238
+
1239
+ private _get_fitted_params, called from get_fitted_params
1240
+
1241
+ State required:
1242
+ Requires state to be "fitted".
1243
+
1244
+ Returns
1245
+ -------
1246
+ fitted_params : dict with str keys
1247
+ fitted parameters, keyed by names of fitted parameter
1248
+ """
1249
+ return self._get_fitted_params_default()