xtft 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- xtft/__init__.py +80 -0
- xtft/_configs.py +220 -0
- xtft/_deps.py +145 -0
- xtft/_dummies.py +119 -0
- xtft/_log.py +137 -0
- xtft/_log.yml +59 -0
- xtft/_optdeps.py +162 -0
- xtft/_util.py +44 -0
- xtft/api/bunch.py +721 -0
- xtft/api/docs.py +2690 -0
- xtft/api/property.py +2256 -0
- xtft/api/summary.py +180 -0
- xtft/api/types.py +256 -0
- xtft/api/util.py +5175 -0
- xtft/backends/__init__.py +31 -0
- xtft/backends/_framework.py +263 -0
- xtft/backends/array/base.py +138 -0
- xtft/backends/array/cupy.py +303 -0
- xtft/backends/array/dask.py +466 -0
- xtft/backends/array/devices.py +360 -0
- xtft/backends/array/nn.py +1270 -0
- xtft/backends/array/numpy.py +261 -0
- xtft/backends/array/scipy.py +245 -0
- xtft/backends/array/selector.py +1017 -0
- xtft/compat/__init__.py +41 -0
- xtft/compat/_config.py +199 -0
- xtft/compat/keras.py +925 -0
- xtft/compat/keras_fit.py +475 -0
- xtft/compat/kt.py +125 -0
- xtft/compat/numpy.py +98 -0
- xtft/compat/pandas.py +660 -0
- xtft/compat/scipy.py +393 -0
- xtft/compat/sklearn.py +1150 -0
- xtft/compat/tf.py +1182 -0
- xtft/compat/torch.py +99 -0
- xtft/compat/types.py +85 -0
- xtft/core/array_manager.py +4649 -0
- xtft/core/checks.py +7479 -0
- xtft/core/diagnose_q.py +2237 -0
- xtft/core/handlers.py +2685 -0
- xtft/core/io.py +2705 -0
- xtft/core/utils.py +3128 -0
- xtft/data/__init__.py +19 -0
- xtft/data/panel.py +549 -0
- xtft/data/seasonality.py +203 -0
- xtft/decorators.py +5154 -0
- xtft/evaluation/__init__.py +57 -0
- xtft/evaluation/bands.py +489 -0
- xtft/evaluation/conformal.py +637 -0
- xtft/evaluation/metrics.py +559 -0
- xtft/evaluation/stats.py +326 -0
- xtft/exceptions.py +336 -0
- xtft/metrics/__init__.py +32 -0
- xtft/metrics/_cas.py +470 -0
- xtft/metrics/_metrics.py +3500 -0
- xtft/metrics/_registry.py +217 -0
- xtft/nn/__init__.py +124 -0
- xtft/nn/tf/__init__.py +60 -0
- xtft/nn/tf/_shapes.py +1124 -0
- xtft/nn/tf/_tensor_validation.py +3845 -0
- xtft/nn/tf/_utils.py +7549 -0
- xtft/nn/tf/anomaly_detection.py +1065 -0
- xtft/nn/tf/calibration.py +312 -0
- xtft/nn/tf/callbacks.py +1317 -0
- xtft/nn/tf/components/__init__.py +154 -0
- xtft/nn/tf/components/_attention_utils.py +160 -0
- xtft/nn/tf/components/_config.py +207 -0
- xtft/nn/tf/components/_loss_utils.py +215 -0
- xtft/nn/tf/components/_temporal_utils.py +469 -0
- xtft/nn/tf/components/attention.py +1195 -0
- xtft/nn/tf/components/encoder_decoder.py +616 -0
- xtft/nn/tf/components/gating_norm.py +1081 -0
- xtft/nn/tf/components/heads.py +694 -0
- xtft/nn/tf/components/layer_utils.py +360 -0
- xtft/nn/tf/components/losses.py +940 -0
- xtft/nn/tf/components/masks.py +130 -0
- xtft/nn/tf/components/misc.py +1066 -0
- xtft/nn/tf/components/temporal.py +357 -0
- xtft/nn/tf/components/utils.py +243 -0
- xtft/nn/tf/custom_metrics.py +211 -0
- xtft/nn/tf/hybrid/__init__.py +11 -0
- xtft/nn/tf/hybrid/_base_extreme.py +636 -0
- xtft/nn/tf/hybrid/_super_xtft.py +677 -0
- xtft/nn/tf/hybrid/_xtft.py +607 -0
- xtft/nn/tf/hybrid/utils.py +852 -0
- xtft/nn/tf/keras_metrics.py +1313 -0
- xtft/nn/tf/keras_validator.py +643 -0
- xtft/nn/tf/losses.py +1139 -0
- xtft/nn/tf/transformers/__init__.py +10 -0
- xtft/nn/tf/transformers/_adj_tft.py +777 -0
- xtft/nn/tf/transformers/_tft.py +1060 -0
- xtft/nn/torch/__init__.py +16 -0
- xtft/nn/torch/layers/__init__.py +24 -0
- xtft/nn/torch/layers/attention.py +332 -0
- xtft/nn/torch/layers/grn.py +215 -0
- xtft/nn/torch/layers/missing.py +226 -0
- xtft/nn/torch/layers/multiresolution.py +348 -0
- xtft/nn/torch/layers/variable_selection.py +193 -0
- xtft/nn/torch/models/__init__.py +5 -0
- xtft/nn/torch/models/xtft.py +638 -0
- xtft/nn/torch/probabilistic/__init__.py +11 -0
- xtft/nn/torch/probabilistic/losses.py +139 -0
- xtft/nn/torch/probabilistic/quantile_head.py +154 -0
- xtft/nn/torch/trainer.py +357 -0
- xtft/utils/_array_api.py +183 -0
- xtft/utils/_dependency.py +187 -0
- xtft/utils/base_utils.py +1532 -0
- xtft/utils/calibrate.py +950 -0
- xtft/utils/data_utils.py +1278 -0
- xtft/utils/deps_utils.py +1401 -0
- xtft/utils/forecast_utils.py +4507 -0
- xtft/utils/generic_utils.py +4018 -0
- xtft/utils/io_utils.py +3465 -0
- xtft/utils/sequence_utils.py +1701 -0
- xtft/utils/shapes.py +1183 -0
- xtft/utils/sys_utils.py +3161 -0
- xtft/utils/ts_utils.py +4975 -0
- xtft/utils/validator.py +7647 -0
- xtft/utils/version.py +581 -0
- xtft-0.1.0.dist-info/METADATA +310 -0
- xtft-0.1.0.dist-info/RECORD +124 -0
- xtft-0.1.0.dist-info/WHEEL +5 -0
- xtft-0.1.0.dist-info/licenses/LICENSE +28 -0
- xtft-0.1.0.dist-info/top_level.txt +1 -0
xtft/__init__.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""xtft: covariate-aware probabilistic forecasting.
|
|
2
|
+
|
|
3
|
+
xtft provides the XTFT model family, a temporal fusion network
|
|
4
|
+
robust to level shift and missing inputs, with interchangeable
|
|
5
|
+
PyTorch (default) and TensorFlow/Keras implementations, together
|
|
6
|
+
with probabilistic metrics, conformal calibration (per-step and
|
|
7
|
+
whole-path), data utilities and benchmark tooling.
|
|
8
|
+
|
|
9
|
+
The public API is reachable in two levels:
|
|
10
|
+
|
|
11
|
+
* :mod:`xtft.nn`: the model (``XTFT``) and its training loop
|
|
12
|
+
(``TrainConfig``, ``fit``, ``predict``);
|
|
13
|
+
* :mod:`xtft.data`: panels, splits, scaling and windows;
|
|
14
|
+
* :mod:`xtft.evaluation`: metrics, conformal calibration and
|
|
15
|
+
statistical tests.
|
|
16
|
+
|
|
17
|
+
Choose the framework with :func:`xtft.set_backend` or the
|
|
18
|
+
``XTFT_BACKEND`` environment variable before importing models from
|
|
19
|
+
:mod:`xtft.nn`.
|
|
20
|
+
|
|
21
|
+
Examples
|
|
22
|
+
--------
|
|
23
|
+
>>> import xtft
|
|
24
|
+
>>> xtft.get_backend() in xtft.backends.SUPPORTED_BACKENDS
|
|
25
|
+
True
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import importlib
|
|
31
|
+
import logging
|
|
32
|
+
from importlib import metadata as _metadata
|
|
33
|
+
|
|
34
|
+
from . import backends
|
|
35
|
+
from .backends import (
|
|
36
|
+
available_backends,
|
|
37
|
+
get_backend,
|
|
38
|
+
set_backend,
|
|
39
|
+
use_backend,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
try:
|
|
43
|
+
# The installed distribution is the single source of the version
|
|
44
|
+
# (``version`` in pyproject.toml).
|
|
45
|
+
__version__ = _metadata.version("xtft")
|
|
46
|
+
except _metadata.PackageNotFoundError: # source tree, not installed
|
|
47
|
+
__version__ = "0+unknown"
|
|
48
|
+
|
|
49
|
+
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
|
50
|
+
|
|
51
|
+
# Subpackages imported on first attribute access, so that
|
|
52
|
+
# ``import xtft`` stays light and loads no deep-learning framework.
|
|
53
|
+
_LAZY_SUBMODULES = (
|
|
54
|
+
"api",
|
|
55
|
+
"compat",
|
|
56
|
+
"core",
|
|
57
|
+
"data",
|
|
58
|
+
"evaluation",
|
|
59
|
+
"metrics",
|
|
60
|
+
"nn",
|
|
61
|
+
"utils",
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
__all__ = [
|
|
65
|
+
"__version__",
|
|
66
|
+
"available_backends",
|
|
67
|
+
"backends",
|
|
68
|
+
"get_backend",
|
|
69
|
+
"set_backend",
|
|
70
|
+
"use_backend",
|
|
71
|
+
*_LAZY_SUBMODULES,
|
|
72
|
+
]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def __getattr__(name: str):
|
|
76
|
+
if name in _LAZY_SUBMODULES:
|
|
77
|
+
return importlib.import_module(f".{name}", __name__)
|
|
78
|
+
raise AttributeError(
|
|
79
|
+
f"module {__name__!r} has no attribute {name!r}"
|
|
80
|
+
)
|
xtft/_configs.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# License: BSD-3-Clause
|
|
3
|
+
# Author: LKouadio <etanoyau@gmail.com>
|
|
4
|
+
|
|
5
|
+
"""
|
|
6
|
+
Central configuration for backend-specific object mappings.
|
|
7
|
+
|
|
8
|
+
This module acts as the single source of truth for locating objects
|
|
9
|
+
within different backends like TensorFlow/Keras. It allows for a
|
|
10
|
+
clean separation of configuration from the logic in the dependency
|
|
11
|
+
loaders.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
_STANDARD_ALONE_MAP = {
|
|
15
|
+
'AUTOTUNE': ('tensorflow.data', 'AUTOTUNE'),
|
|
16
|
+
'Assert': ('tensorflow', 'Assert'),
|
|
17
|
+
'Dataset': ('tensorflow.data', 'Dataset'),
|
|
18
|
+
'GradientTape': ('tensorflow', 'GradientTape'),
|
|
19
|
+
'IndexedSlices': ('tensorflow', 'IndexedSlices'),
|
|
20
|
+
'Tensor': ('tensorflow', 'Tensor'),
|
|
21
|
+
'TensorShape': ('tensorflow', 'TensorShape'),
|
|
22
|
+
'Variable': ('tensorflow', 'Variable'),
|
|
23
|
+
|
|
24
|
+
'abs': ('tensorflow', 'abs'),
|
|
25
|
+
'activations': ('tensorflow.keras', 'activations'),
|
|
26
|
+
'add': ('tensorflow.math', 'add'),
|
|
27
|
+
'add_n': ('tensorflow.math', 'add_n'),
|
|
28
|
+
'argmin': ('tensorflow', 'argmin'),
|
|
29
|
+
'assert_equal': ('tensorflow', 'assert_equal'),
|
|
30
|
+
'autograph': ('tensorflow', 'autograph'),
|
|
31
|
+
'backend': ('tensorflow.keras', 'backend'),
|
|
32
|
+
'broadcast_to': ('tensorflow', 'broadcast_to'),
|
|
33
|
+
'bool': ('tensorflow', 'bool'),
|
|
34
|
+
'cast': ('tensorflow', 'cast'),
|
|
35
|
+
'clip_by_value':('tensorflow', 'clip_by_value'),
|
|
36
|
+
'clip_by_global_norm': ('tensorflow', 'clip_by_global_norm'),
|
|
37
|
+
'concat': ('tensorflow', 'concat'),
|
|
38
|
+
'cond': ('tensorflow', 'cond'),
|
|
39
|
+
'constant': ('tensorflow', 'constant'),
|
|
40
|
+
'control_dependencies': ('tensorflow', 'control_dependencies'),
|
|
41
|
+
'convert_to_tensor': ('tensorflow', 'convert_to_tensor'),
|
|
42
|
+
'cos': ('tensorflow', 'cos'),
|
|
43
|
+
'cumsum': ('tensorflow.math', 'cumsum'),
|
|
44
|
+
'debugging': ('tensorflow', 'debugging'),
|
|
45
|
+
'divide_no_nan': ('tensorflow.math', 'divide_no_nan'),
|
|
46
|
+
'errors': ('tensorflow', 'errors'),
|
|
47
|
+
'equal': ('tensorflow', 'equal'),
|
|
48
|
+
'erf': ('tensorflow.math', 'erf'),
|
|
49
|
+
'executing_eagerly': ('tensorflow', 'executing_eagerly'),
|
|
50
|
+
'exp': ('tensorflow', 'exp'),
|
|
51
|
+
'expand_dims': ('tensorflow', 'expand_dims'),
|
|
52
|
+
'experimental':('tensorflow.data', 'experimental'),
|
|
53
|
+
'fill': ('tensorflow', 'fill'),
|
|
54
|
+
'float32': ('tensorflow', 'float32'),
|
|
55
|
+
'float64': ('tensorflow', 'float64'),
|
|
56
|
+
'floordiv': ('tensorflow.math', 'floordiv'),
|
|
57
|
+
'gather': ('tensorflow', 'gather'),
|
|
58
|
+
'get_static_value': ('tensorflow', 'get_static_value'),
|
|
59
|
+
'greater': ('tensorflow', 'greater'),
|
|
60
|
+
'greater_equal': ('tensorflow', 'greater_equal'),
|
|
61
|
+
'identity': ('tensorflow', 'identity'),
|
|
62
|
+
'int32': ('tensorflow', 'int32'),
|
|
63
|
+
'int64': ('tensorflow', 'int64'),
|
|
64
|
+
'is_inf': ('tensorflow.math', 'is_inf'),
|
|
65
|
+
'is_nan': ('tensorflow.math', 'is_nan'),
|
|
66
|
+
'less': ('tensorflow', 'less'),
|
|
67
|
+
'less_equal': ('tensorflow', 'less_equal'),
|
|
68
|
+
'linalg': ('tensorflow', 'linalg'),
|
|
69
|
+
'log': ('tensorflow.math', 'log'),
|
|
70
|
+
'logical_and': ('tensorflow', 'logical_and'),
|
|
71
|
+
'logical_not': ('tensorflow', 'logical_not'),
|
|
72
|
+
'logical_or': ('tensorflow', 'logical_or'),
|
|
73
|
+
'math': ('tensorflow', 'math'),
|
|
74
|
+
'maximum': ('tensorflow.math', 'maximum'),
|
|
75
|
+
'minimum': ('tensorflow.math', 'minimum'),
|
|
76
|
+
'multiply': ('tensorflow', 'multiply'),
|
|
77
|
+
'name_scope': ('tensorflow', 'name_scope'),
|
|
78
|
+
'nest': ('tensorflow', 'nest'),
|
|
79
|
+
'newaxis': ('tensorflow', 'newaxis'),
|
|
80
|
+
'no_op': ('tensorflow', 'no_op'),
|
|
81
|
+
'nn': ('tensorflow', 'nn'),
|
|
82
|
+
'ones': ('tensorflow', 'ones'),
|
|
83
|
+
'ones_like':('tensorflow', 'ones_like'),
|
|
84
|
+
'pad': ('tensorflow', 'pad'),
|
|
85
|
+
'pow': ('tensorflow', 'pow'),
|
|
86
|
+
'print': ('tensorflow', 'print'),
|
|
87
|
+
'random': ('tensorflow', 'random'),
|
|
88
|
+
'range': ('tensorflow', 'range'),
|
|
89
|
+
'rank': ('tensorflow', 'rank'),
|
|
90
|
+
'reduce_any':('tensorflow', 'reduce_any'),
|
|
91
|
+
'reduce_all': ('tensorflow', 'reduce_all'),
|
|
92
|
+
'reduce_logsumexp':('tensorflow.math', 'reduce_logsumexp'),
|
|
93
|
+
'reduce_max': ('tensorflow', 'reduce_max'),
|
|
94
|
+
'reduce_mean': ('tensorflow', 'reduce_mean'),
|
|
95
|
+
'reduce_min': ('tensorflow', 'reduce_min'),
|
|
96
|
+
'reduce_sum': ('tensorflow', 'reduce_sum'),
|
|
97
|
+
'regularizers': ('tensorflow.keras', 'regularizers'),
|
|
98
|
+
'repeat': ('tensorflow', 'repeat'),
|
|
99
|
+
'reshape': ('tensorflow', 'reshape'),
|
|
100
|
+
'sequence_mask': ('tensorflow', 'sequence_mask'),
|
|
101
|
+
'set_seed': ('tensorflow.random', 'set_seed'),
|
|
102
|
+
'scan': ('tensorflow', 'scan'),
|
|
103
|
+
'shape': ('tensorflow', 'shape'),
|
|
104
|
+
'sigmoid': ('tensorflow.math', 'sigmoid'),
|
|
105
|
+
'sin': ('tensorflow', 'sin'),
|
|
106
|
+
'size': ('tensorflow', 'size'),
|
|
107
|
+
'softplus': ('tensorflow.math', 'softplus'),
|
|
108
|
+
'sort': ('tensorflow', 'sort'),
|
|
109
|
+
'string': ('tensorflow', 'string'),
|
|
110
|
+
'stop_gradient': ('tensorflow','stop_gradient' ),
|
|
111
|
+
'split': ('tensorflow', 'split'),
|
|
112
|
+
'squeeze': ('tensorflow', 'squeeze'),
|
|
113
|
+
'square': ('tensorflow.math', 'square'),
|
|
114
|
+
'sqrt': ('tensorflow', 'sqrt'),
|
|
115
|
+
'stack': ('tensorflow', 'stack'),
|
|
116
|
+
'subtract': ('tensorflow', 'subtract'),
|
|
117
|
+
'switch_case': ('tensorflow', 'switch_case'),
|
|
118
|
+
'tile': ('tensorflow', 'tile'),
|
|
119
|
+
'transpose': ('tensorflow', 'transpose'),
|
|
120
|
+
'unstack': ('tensorflow', 'unstack'),
|
|
121
|
+
'where': ('tensorflow', 'where'),
|
|
122
|
+
'zeros': ('tensorflow', 'zeros'),
|
|
123
|
+
'zeros_like': ('tensorflow', 'zeros_like'),
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
TENSORFLOW_CONFIG = {
|
|
127
|
+
**_STANDARD_ALONE_MAP,
|
|
128
|
+
'Activation': ('layers', 'Activation'),
|
|
129
|
+
'Adam': ('optimizers', 'Adam'),
|
|
130
|
+
'Add': ('layers', 'Add'),
|
|
131
|
+
'Attention': ('layers', 'Attention'),
|
|
132
|
+
'BatchNormalization': ('layers', 'BatchNormalization'),
|
|
133
|
+
'Bidirectional': ('layers', 'Bidirectional'),
|
|
134
|
+
'Callback': ('callbacks', 'Callback'),
|
|
135
|
+
'Concatenate': ('layers', 'Concatenate'),
|
|
136
|
+
'Constant': ('initializers', 'Constant'),
|
|
137
|
+
'Constraint': ('constraints', 'Constraint'),
|
|
138
|
+
'Conv1D': ('layers', 'Conv1D'),
|
|
139
|
+
'Conv2D': ('layers', 'Conv2D'),
|
|
140
|
+
'Dense': ('layers', 'Dense'),
|
|
141
|
+
'Dropout': ('layers', 'Dropout'),
|
|
142
|
+
'ELU': ('layers', 'ELU'),
|
|
143
|
+
'EarlyStopping': ('callbacks', 'EarlyStopping'),
|
|
144
|
+
'Embedding': ('layers', 'Embedding'),
|
|
145
|
+
'Flatten': ('layers', 'Flatten'),
|
|
146
|
+
'GlobalAveragePooling1D': ('layers', 'GlobalAveragePooling1D'),
|
|
147
|
+
'GlobalAveragePooling2D': ('layers', 'GlobalAveragePooling2D'),
|
|
148
|
+
'History': ('callbacks', 'History'),
|
|
149
|
+
'Input': ('layers', 'Input'),
|
|
150
|
+
'InputLayer': ('layers', 'InputLayer'),
|
|
151
|
+
'K': ('backend', 'K'),
|
|
152
|
+
'LSTM': ('layers', 'LSTM'),
|
|
153
|
+
'LSTMCell': ('layers', 'LSTMCell'),
|
|
154
|
+
'Layer': ('layers', 'Layer'),
|
|
155
|
+
'LayerNormalization': ('layers', 'LayerNormalization'),
|
|
156
|
+
'LearningRateScheduler': ('callbacks', 'LearningRateScheduler'),
|
|
157
|
+
'Loss': ('losses', 'Loss'),
|
|
158
|
+
'MaxPooling1D': ('layers', 'MaxPooling1D'),
|
|
159
|
+
'MaxPooling2D': ('layers', 'MaxPooling2D'),
|
|
160
|
+
'Mean': ('metrics', 'Mean'),
|
|
161
|
+
'MeanAbsoluteError': ('metrics', 'MeanAbsoluteError'),
|
|
162
|
+
'MeanSquaredError': ('losses', 'MeanSquaredError'),
|
|
163
|
+
'Metric': ('metrics', 'Metric'),
|
|
164
|
+
'Model': ('models', 'Model'),
|
|
165
|
+
'ModelCheckpoint': ('callbacks', 'ModelCheckpoint'),
|
|
166
|
+
'MultiHeadAttention': ('layers', 'MultiHeadAttention'),
|
|
167
|
+
'Optimizer': ('optimizers', 'Optimizer'),
|
|
168
|
+
'RMSprop': ('optimizers', 'RMSprop'),
|
|
169
|
+
'RandomNormal': ('initializers', 'RandomNormal'),
|
|
170
|
+
'Reduction': ('losses','Reduction' ),
|
|
171
|
+
'ReduceLROnPlateau': ('callbacks', 'ReduceLROnPlateau'),
|
|
172
|
+
'RepeatVector': ('layers', 'RepeatVector'),
|
|
173
|
+
'SGD': ('optimizers', 'SGD'),
|
|
174
|
+
'Sequential': ('models', 'Sequential'),
|
|
175
|
+
'Softmax': ('layers', 'Softmax'),
|
|
176
|
+
'TensorBoard': ('callbacks', 'TensorBoard'),
|
|
177
|
+
'TimeDistributed': ('layers', 'TimeDistributed'),
|
|
178
|
+
|
|
179
|
+
'binary_crossentropy': ('losses', 'binary_crossentropy'),
|
|
180
|
+
'categorical_crossentropy': ('losses', 'categorical_crossentropy'),
|
|
181
|
+
'cifar10': ('datasets', 'cifar10'),
|
|
182
|
+
'clone_model': ('models', 'clone_model'),
|
|
183
|
+
'custom_object_scope': ('utils', 'custom_object_scope'),
|
|
184
|
+
'deserialize_keras_object': (
|
|
185
|
+
('saving', 'deserialize_keras_object'),
|
|
186
|
+
('utils', 'deserialize_keras_object')
|
|
187
|
+
),
|
|
188
|
+
'get': ('losses', 'get'),
|
|
189
|
+
'glorot_uniform': ('initializers', 'glorot_uniform'),
|
|
190
|
+
'load_model': ('models', 'load_model'),
|
|
191
|
+
'mean_squared_error': ('losses', 'mean_squared_error'),
|
|
192
|
+
'mnist': ('datasets', 'mnist'),
|
|
193
|
+
'ones': ('backend', 'ones'),
|
|
194
|
+
'random_normal': ('initializers', 'random_normal'),
|
|
195
|
+
'register_keras_serializable': (
|
|
196
|
+
('saving', 'register_keras_serializable'),
|
|
197
|
+
('utils', 'register_keras_serializable')
|
|
198
|
+
),
|
|
199
|
+
'serialize_keras_object': (
|
|
200
|
+
('saving', 'serialize_keras_object'),
|
|
201
|
+
# ('utils', 'serialize_keras_object')
|
|
202
|
+
),
|
|
203
|
+
'sum': ('backend', 'sum'),
|
|
204
|
+
|
|
205
|
+
}
|
|
206
|
+
# Configuration for KerasTuner
|
|
207
|
+
KERAS_TUNER_CONFIG = {
|
|
208
|
+
'BayesianOptimization': ('keras_tuner', 'BayesianOptimization'),
|
|
209
|
+
'Hyperband': ('keras_tuner', 'Hyperband'),
|
|
210
|
+
'HyperModel': ('keras_tuner', 'HyperModel'),
|
|
211
|
+
'HyperParameters': ('keras_tuner', 'HyperParameters'),
|
|
212
|
+
'Objective': ('keras_tuner', 'Objective'),
|
|
213
|
+
'RandomSearch': ('keras_tuner', 'RandomSearch'),
|
|
214
|
+
'Tuner': ('keras_tuner', 'Tuner'),
|
|
215
|
+
'TunerCallback': (
|
|
216
|
+
('keras_tuner.src.engine.tuner_utils', 'TunerCallback'),
|
|
217
|
+
('keras_tuner.engine.tuner_utils', 'TunerCallback')
|
|
218
|
+
),
|
|
219
|
+
}
|
|
220
|
+
|
xtft/_deps.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# License: BSD-3-Clause
|
|
3
|
+
# Author: L. Kouadio <etanoyau@gmail.com>
|
|
4
|
+
|
|
5
|
+
"""
|
|
6
|
+
Provides centralized, robust utilities for checking and importing optional
|
|
7
|
+
heavy dependencies like TensorFlow and Keras Tuner.
|
|
8
|
+
|
|
9
|
+
This module acts as the single source of truth for dependency management,
|
|
10
|
+
allowing other parts of the library to gracefully handle cases where a
|
|
11
|
+
backend might not be installed.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
import importlib.util
|
|
15
|
+
import warnings
|
|
16
|
+
from typing import Dict, Optional, Literal
|
|
17
|
+
|
|
18
|
+
# --- Standardized Error and Warning Messages ---
|
|
19
|
+
|
|
20
|
+
_DEPENDENCY_MESSAGES = {
|
|
21
|
+
"tensorflow": (
|
|
22
|
+
"This feature requires a full TensorFlow installation,"
|
|
23
|
+
" but it was not found.\n\n"
|
|
24
|
+
"Please install TensorFlow by running:\n"
|
|
25
|
+
" pip install tensorflow\n\n"
|
|
26
|
+
"For more details, see: https://www.tensorflow.org/install"
|
|
27
|
+
),
|
|
28
|
+
"keras_tuner": (
|
|
29
|
+
"Hyperparameter tuning features require the `keras-tuner`"
|
|
30
|
+
" package, but it was not found.\n\n"
|
|
31
|
+
"Please install it by running:\n"
|
|
32
|
+
" pip install keras-tuner"
|
|
33
|
+
),
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
_KERAS_FALLBACK_WARNING = (
|
|
37
|
+
"Standalone Keras is installed but TensorFlow is not. While some "
|
|
38
|
+
"functionalities may work, the primary backend for `fusionlab-learn` "
|
|
39
|
+
"is `tensorflow.keras`. For full functionality and future "
|
|
40
|
+
"compatibility, it is highly recommended to install TensorFlow."
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
def check_backends(names: str) -> Dict[str, bool]:
|
|
44
|
+
"""
|
|
45
|
+
Checks for the presence of one or more specified packages.
|
|
46
|
+
|
|
47
|
+
This utility can check for a single package or multiple packages by
|
|
48
|
+
providing their names separated by '__'.
|
|
49
|
+
|
|
50
|
+
Parameters
|
|
51
|
+
----------
|
|
52
|
+
names : str
|
|
53
|
+
The name of the package(s) to check. For multiple packages,
|
|
54
|
+
separate the names with a double underscore, e.g.,
|
|
55
|
+
``'tensorflow__keras_tuner'``.
|
|
56
|
+
|
|
57
|
+
Returns
|
|
58
|
+
-------
|
|
59
|
+
dict
|
|
60
|
+
A dictionary where keys are the package names and values are
|
|
61
|
+
booleans indicating whether the package is installed.
|
|
62
|
+
|
|
63
|
+
Examples
|
|
64
|
+
--------
|
|
65
|
+
>>> from xtft._deps import check_backends
|
|
66
|
+
>>> check_backends('tensorflow')
|
|
67
|
+
{'tensorflow': True}
|
|
68
|
+
>>> check_backends('non_existent_package')
|
|
69
|
+
{'non_existent_package': False}
|
|
70
|
+
>>> check_backends('numpy__pandas')
|
|
71
|
+
{'numpy': True, 'pandas': True}
|
|
72
|
+
"""
|
|
73
|
+
package_list = [pkg.strip() for pkg in names.split('__')]
|
|
74
|
+
status = {
|
|
75
|
+
pkg: importlib.util.find_spec(pkg) is not None for pkg in package_list
|
|
76
|
+
}
|
|
77
|
+
return status
|
|
78
|
+
|
|
79
|
+
def import_dependencies(
|
|
80
|
+
name: str = 'tensorflow',
|
|
81
|
+
extra_msg: Optional[str] = None,
|
|
82
|
+
error: str = 'warn',
|
|
83
|
+
allow_keras_fallback: bool = True,
|
|
84
|
+
) -> Literal['KerasDependencies', 'DummyKerasDeps',
|
|
85
|
+
'KerasTunerDependencies','DummyKT']:
|
|
86
|
+
"""
|
|
87
|
+
Dynamically loads backend dependencies or returns a dummy object.
|
|
88
|
+
|
|
89
|
+
This factory function is the central point for accessing backend
|
|
90
|
+
functionality. It checks if the required package is installed and returns
|
|
91
|
+
either a real dependency loader class or a safe dummy placeholder.
|
|
92
|
+
|
|
93
|
+
Parameters
|
|
94
|
+
----------
|
|
95
|
+
name : {'tensorflow', 'keras_tuner'}, default='tensorflow'
|
|
96
|
+
The name of the core dependency to load.
|
|
97
|
+
extra_msg : str, optional
|
|
98
|
+
An additional message to append to any warnings or errors.
|
|
99
|
+
error : {'raise', 'warn', 'ignore'}, default='warn'
|
|
100
|
+
The policy for handling a missing dependency.
|
|
101
|
+
allow_keras_fallback : bool, default=True
|
|
102
|
+
If `name='tensorflow'` and it is not found, this flag allows
|
|
103
|
+
the function to check for a standalone `keras` installation
|
|
104
|
+
as a fallback. A warning will be issued if this occurs.
|
|
105
|
+
|
|
106
|
+
Returns
|
|
107
|
+
-------
|
|
108
|
+
Union[KerasDependencies, DummyKerasDeps, KerasTunerDependencies, DummyKT]
|
|
109
|
+
An instance of the appropriate real dependency loader or its
|
|
110
|
+
dummy counterpart.
|
|
111
|
+
"""
|
|
112
|
+
if name == 'tensorflow':
|
|
113
|
+
tf_found = check_backends('tensorflow')['tensorflow']
|
|
114
|
+
keras_found = check_backends('keras')['keras']
|
|
115
|
+
|
|
116
|
+
if tf_found:
|
|
117
|
+
from xtft.compat.tf import KerasDependencies
|
|
118
|
+
return KerasDependencies(extra_msg=extra_msg, error=error)
|
|
119
|
+
|
|
120
|
+
elif allow_keras_fallback and keras_found:
|
|
121
|
+
warnings.warn(_KERAS_FALLBACK_WARNING, UserWarning, stacklevel=2)
|
|
122
|
+
from xtft.compat.tf import KerasDependencies
|
|
123
|
+
return KerasDependencies(extra_msg=extra_msg, error=error)
|
|
124
|
+
|
|
125
|
+
else: # Neither TensorFlow nor Keras is found
|
|
126
|
+
from xtft._dummies import DummyKerasDeps
|
|
127
|
+
if extra_msg:
|
|
128
|
+
warnings.warn(str(extra_msg), ImportWarning, stacklevel=2)
|
|
129
|
+
return DummyKerasDeps()
|
|
130
|
+
|
|
131
|
+
elif name == 'keras_tuner':
|
|
132
|
+
if check_backends('keras_tuner')['keras_tuner']:
|
|
133
|
+
from xtft.compat.kt import KerasTunerDependencies
|
|
134
|
+
return KerasTunerDependencies(extra_msg=extra_msg, error=error)
|
|
135
|
+
else:
|
|
136
|
+
from xtft._dummies import DummyKT
|
|
137
|
+
if extra_msg:
|
|
138
|
+
warnings.warn(str(extra_msg), ImportWarning, stacklevel=2)
|
|
139
|
+
return DummyKT()
|
|
140
|
+
|
|
141
|
+
else:
|
|
142
|
+
raise ValueError(
|
|
143
|
+
f"Unsupported dependency name: '{name}'. "
|
|
144
|
+
"Choose from 'tensorflow' or 'keras_tuner'."
|
|
145
|
+
)
|
xtft/_dummies.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# License: BSD-3-Clause
|
|
3
|
+
# Author: LKouadio <etanoyau@gmail.com>
|
|
4
|
+
|
|
5
|
+
"""
|
|
6
|
+
This internal module provides placeholder "dummy" objects for optional
|
|
7
|
+
dependencies like TensorFlow, Keras, and KerasTuner.
|
|
8
|
+
|
|
9
|
+
It dynamically generates these dummies based on the central configuration
|
|
10
|
+
in `xtft._configs`, ensuring it is always in sync with the real
|
|
11
|
+
dependency loader.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
from xtft._configs import TENSORFLOW_CONFIG, KERAS_TUNER_CONFIG
|
|
18
|
+
except ImportError:
|
|
19
|
+
TENSORFLOW_CONFIG = {}
|
|
20
|
+
KERAS_TUNER_CONFIG = {}
|
|
21
|
+
|
|
22
|
+
class _DummyObject:
|
|
23
|
+
"""
|
|
24
|
+
A generic base class for all dummy objects. It raises a helpful
|
|
25
|
+
ImportError when instantiated or called, guiding the user to install
|
|
26
|
+
the missing package.
|
|
27
|
+
"""
|
|
28
|
+
_dependency_name = "A required package"
|
|
29
|
+
_is_callable = True
|
|
30
|
+
|
|
31
|
+
def __init__(self, *args, **kwargs):
|
|
32
|
+
# This __init__ is for dummy classes (e.g., Model, Dense).
|
|
33
|
+
# It raises an error upon instantiation.
|
|
34
|
+
if self._is_callable:
|
|
35
|
+
raise ImportError(
|
|
36
|
+
f"The `{self.__class__.__name__}` component"
|
|
37
|
+
f" requires {self._dependency_name},"
|
|
38
|
+
f" but it is not installed. Please install"
|
|
39
|
+
" it to use this feature."
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
def __call__(self, *args, **kwargs):
|
|
43
|
+
# This __call__ is for dummy functions (e.g., reduce_mean).
|
|
44
|
+
# It raises an error upon being called.
|
|
45
|
+
raise ImportError(
|
|
46
|
+
f"The `{self.__class__.__name__}` function"
|
|
47
|
+
f" requires {self._dependency_name},"
|
|
48
|
+
f" but it is not installed."
|
|
49
|
+
" Please install it to use this feature."
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
def _create_dummy(
|
|
53
|
+
name: str, dependency: str = "TensorFlow/Keras",
|
|
54
|
+
is_callable=True
|
|
55
|
+
):
|
|
56
|
+
"""
|
|
57
|
+
Factory function to create specific dummy classes on the
|
|
58
|
+
fly with tailored error messages.
|
|
59
|
+
"""
|
|
60
|
+
return type(
|
|
61
|
+
name,
|
|
62
|
+
(_DummyObject,),
|
|
63
|
+
{
|
|
64
|
+
"__doc__": f"Dummy placeholder for `{name}`. Requires {dependency}.",
|
|
65
|
+
"_dependency_name": dependency,
|
|
66
|
+
"_is_callable": is_callable
|
|
67
|
+
}
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
# --- Dummy Namespace for KerasTuner ---
|
|
71
|
+
class DummyKT:
|
|
72
|
+
"""
|
|
73
|
+
A dummy module to stand in for the `keras_tuner` package.
|
|
74
|
+
It dynamically creates dummy objects for its attributes
|
|
75
|
+
based on KERAS_TUNER_CONFIG.
|
|
76
|
+
"""
|
|
77
|
+
def __getattr__(self, name: str) -> Any:
|
|
78
|
+
if name in KERAS_TUNER_CONFIG:
|
|
79
|
+
# Most KerasTuner objects are classes.
|
|
80
|
+
return _create_dummy(name, "KerasTuner")()
|
|
81
|
+
# Allow access to generic objects for type checking if needed
|
|
82
|
+
if name == "HyperModel":
|
|
83
|
+
return object
|
|
84
|
+
|
|
85
|
+
raise AttributeError(
|
|
86
|
+
f"'DummyKT' has no attribute '{name}'. Please add it to the "
|
|
87
|
+
"KERAS_TUNER_CONFIG in `fusionlab/_configs.py`."
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
# --- Dummy Namespace for TensorFlow/Keras ---
|
|
91
|
+
class DummyKerasDeps:
|
|
92
|
+
"""
|
|
93
|
+
A lazy-loading, dynamic namespace that mimics the real KERAS_DEPS object.
|
|
94
|
+
|
|
95
|
+
It generates dummy objects on-the-fly for any attribute that is
|
|
96
|
+
requested, based on the central TENSORFLOW_CONFIG. This ensures it
|
|
97
|
+
is always in sync with the real dependency loader.
|
|
98
|
+
"""
|
|
99
|
+
def __getattr__(self, name: str) -> Any:
|
|
100
|
+
# Check if the requested name exists in the central config file.
|
|
101
|
+
if name in TENSORFLOW_CONFIG:
|
|
102
|
+
config_value = TENSORFLOW_CONFIG[name]
|
|
103
|
+
|
|
104
|
+
# For attributes that are just strings (like dtypes), return them directly.
|
|
105
|
+
if isinstance(config_value, str):
|
|
106
|
+
return config_value
|
|
107
|
+
|
|
108
|
+
# For objects that can be instantiated or called, create a dummy.
|
|
109
|
+
# We determine if it's a class/function primarily by capitalization.
|
|
110
|
+
is_class_or_func = not name.islower()
|
|
111
|
+
return _create_dummy(name, is_callable=is_class_or_func)()
|
|
112
|
+
|
|
113
|
+
# Fallback for any unexpected attribute.
|
|
114
|
+
raise AttributeError(
|
|
115
|
+
f"'DummyKerasDeps' has no attribute '{name}'. Please add it to "
|
|
116
|
+
"the TENSORFLOW_CONFIG in `fusionlab/_configs.py`."
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|