pymc-extras 0.2.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.
- pymc_extras/__init__.py +29 -0
- pymc_extras/distributions/__init__.py +40 -0
- pymc_extras/distributions/continuous.py +351 -0
- pymc_extras/distributions/discrete.py +399 -0
- pymc_extras/distributions/histogram_utils.py +163 -0
- pymc_extras/distributions/multivariate/__init__.py +3 -0
- pymc_extras/distributions/multivariate/r2d2m2cp.py +446 -0
- pymc_extras/distributions/timeseries.py +356 -0
- pymc_extras/gp/__init__.py +18 -0
- pymc_extras/gp/latent_approx.py +183 -0
- pymc_extras/inference/__init__.py +18 -0
- pymc_extras/inference/find_map.py +431 -0
- pymc_extras/inference/fit.py +44 -0
- pymc_extras/inference/laplace.py +570 -0
- pymc_extras/inference/pathfinder.py +134 -0
- pymc_extras/inference/smc/__init__.py +13 -0
- pymc_extras/inference/smc/sampling.py +451 -0
- pymc_extras/linearmodel.py +130 -0
- pymc_extras/model/__init__.py +0 -0
- pymc_extras/model/marginal/__init__.py +0 -0
- pymc_extras/model/marginal/distributions.py +276 -0
- pymc_extras/model/marginal/graph_analysis.py +372 -0
- pymc_extras/model/marginal/marginal_model.py +595 -0
- pymc_extras/model/model_api.py +56 -0
- pymc_extras/model/transforms/__init__.py +0 -0
- pymc_extras/model/transforms/autoreparam.py +434 -0
- pymc_extras/model_builder.py +759 -0
- pymc_extras/preprocessing/__init__.py +0 -0
- pymc_extras/preprocessing/standard_scaler.py +17 -0
- pymc_extras/printing.py +182 -0
- pymc_extras/statespace/__init__.py +13 -0
- pymc_extras/statespace/core/__init__.py +7 -0
- pymc_extras/statespace/core/compile.py +48 -0
- pymc_extras/statespace/core/representation.py +438 -0
- pymc_extras/statespace/core/statespace.py +2268 -0
- pymc_extras/statespace/filters/__init__.py +15 -0
- pymc_extras/statespace/filters/distributions.py +453 -0
- pymc_extras/statespace/filters/kalman_filter.py +820 -0
- pymc_extras/statespace/filters/kalman_smoother.py +126 -0
- pymc_extras/statespace/filters/utilities.py +59 -0
- pymc_extras/statespace/models/ETS.py +670 -0
- pymc_extras/statespace/models/SARIMAX.py +536 -0
- pymc_extras/statespace/models/VARMAX.py +393 -0
- pymc_extras/statespace/models/__init__.py +6 -0
- pymc_extras/statespace/models/structural.py +1651 -0
- pymc_extras/statespace/models/utilities.py +387 -0
- pymc_extras/statespace/utils/__init__.py +0 -0
- pymc_extras/statespace/utils/constants.py +74 -0
- pymc_extras/statespace/utils/coord_tools.py +0 -0
- pymc_extras/statespace/utils/data_tools.py +182 -0
- pymc_extras/utils/__init__.py +23 -0
- pymc_extras/utils/linear_cg.py +290 -0
- pymc_extras/utils/pivoted_cholesky.py +69 -0
- pymc_extras/utils/prior.py +200 -0
- pymc_extras/utils/spline.py +131 -0
- pymc_extras/version.py +11 -0
- pymc_extras/version.txt +1 -0
- pymc_extras-0.2.0.dist-info/LICENSE +212 -0
- pymc_extras-0.2.0.dist-info/METADATA +99 -0
- pymc_extras-0.2.0.dist-info/RECORD +101 -0
- pymc_extras-0.2.0.dist-info/WHEEL +5 -0
- pymc_extras-0.2.0.dist-info/top_level.txt +2 -0
- tests/__init__.py +13 -0
- tests/distributions/__init__.py +19 -0
- tests/distributions/test_continuous.py +185 -0
- tests/distributions/test_discrete.py +210 -0
- tests/distributions/test_discrete_markov_chain.py +258 -0
- tests/distributions/test_multivariate.py +304 -0
- tests/model/__init__.py +0 -0
- tests/model/marginal/__init__.py +0 -0
- tests/model/marginal/test_distributions.py +131 -0
- tests/model/marginal/test_graph_analysis.py +182 -0
- tests/model/marginal/test_marginal_model.py +867 -0
- tests/model/test_model_api.py +29 -0
- tests/statespace/__init__.py +0 -0
- tests/statespace/test_ETS.py +411 -0
- tests/statespace/test_SARIMAX.py +405 -0
- tests/statespace/test_VARMAX.py +184 -0
- tests/statespace/test_coord_assignment.py +116 -0
- tests/statespace/test_distributions.py +270 -0
- tests/statespace/test_kalman_filter.py +326 -0
- tests/statespace/test_representation.py +175 -0
- tests/statespace/test_statespace.py +818 -0
- tests/statespace/test_statespace_JAX.py +156 -0
- tests/statespace/test_structural.py +829 -0
- tests/statespace/utilities/__init__.py +0 -0
- tests/statespace/utilities/shared_fixtures.py +9 -0
- tests/statespace/utilities/statsmodel_local_level.py +42 -0
- tests/statespace/utilities/test_helpers.py +310 -0
- tests/test_blackjax_smc.py +222 -0
- tests/test_find_map.py +98 -0
- tests/test_histogram_approximation.py +109 -0
- tests/test_laplace.py +238 -0
- tests/test_linearmodel.py +208 -0
- tests/test_model_builder.py +306 -0
- tests/test_pathfinder.py +45 -0
- tests/test_pivoted_cholesky.py +24 -0
- tests/test_printing.py +98 -0
- tests/test_prior_from_trace.py +172 -0
- tests/test_splines.py +77 -0
- tests/utils.py +31 -0
|
@@ -0,0 +1,759 @@
|
|
|
1
|
+
# Copyright 2023 The PyMC Developers
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
import hashlib
|
|
17
|
+
import json
|
|
18
|
+
import warnings
|
|
19
|
+
|
|
20
|
+
from abc import abstractmethod
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
import arviz as az
|
|
25
|
+
import numpy as np
|
|
26
|
+
import pandas as pd
|
|
27
|
+
import pymc as pm
|
|
28
|
+
import xarray as xr
|
|
29
|
+
|
|
30
|
+
from pymc.util import RandomState
|
|
31
|
+
|
|
32
|
+
# If scikit-learn is available, use its data validator
|
|
33
|
+
try:
|
|
34
|
+
from sklearn.utils.validation import check_array, check_X_y
|
|
35
|
+
# If scikit-learn is not available, return the data unchanged
|
|
36
|
+
except ImportError:
|
|
37
|
+
|
|
38
|
+
def check_X_y(X, y, **kwargs):
|
|
39
|
+
return X, y
|
|
40
|
+
|
|
41
|
+
def check_array(X, **kwargs):
|
|
42
|
+
return X
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ModelBuilder:
|
|
46
|
+
"""
|
|
47
|
+
ModelBuilder can be used to provide an easy-to-use API (similar to scikit-learn) for models
|
|
48
|
+
and help with deployment.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
_model_type = "BaseClass"
|
|
52
|
+
version = "None"
|
|
53
|
+
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
model_config: dict | None = None,
|
|
57
|
+
sampler_config: dict | None = None,
|
|
58
|
+
):
|
|
59
|
+
"""
|
|
60
|
+
Initializes model configuration and sampler configuration for the model
|
|
61
|
+
|
|
62
|
+
Parameters
|
|
63
|
+
----------
|
|
64
|
+
data : Dictionary, optional
|
|
65
|
+
It is the data we need to train the model on.
|
|
66
|
+
model_config : Dictionary, optional
|
|
67
|
+
dictionary of parameters that initialise model configuration. Class-default defined by the user default_model_config method.
|
|
68
|
+
sampler_config : Dictionary, optional
|
|
69
|
+
dictionary of parameters that initialise sampler configuration. Class-default defined by the user default_sampler_config method.
|
|
70
|
+
|
|
71
|
+
Examples
|
|
72
|
+
--------
|
|
73
|
+
>>> class MyModel(ModelBuilder):
|
|
74
|
+
>>> ...
|
|
75
|
+
>>> model = MyModel(model_config, sampler_config)
|
|
76
|
+
"""
|
|
77
|
+
sampler_config = (
|
|
78
|
+
self.get_default_sampler_config() if sampler_config is None else sampler_config
|
|
79
|
+
)
|
|
80
|
+
self.sampler_config = sampler_config
|
|
81
|
+
model_config = self.get_default_model_config() if model_config is None else model_config
|
|
82
|
+
|
|
83
|
+
self.model_config = model_config # parameters for priors etc.
|
|
84
|
+
self.model = None # Set by build_model
|
|
85
|
+
self.idata: az.InferenceData | None = None # idata is generated during fitting
|
|
86
|
+
self.is_fitted_ = False
|
|
87
|
+
|
|
88
|
+
def _validate_data(self, X, y=None):
|
|
89
|
+
if y is not None:
|
|
90
|
+
return check_X_y(X, y, accept_sparse=False, y_numeric=True, multi_output=False)
|
|
91
|
+
else:
|
|
92
|
+
return check_array(X, accept_sparse=False)
|
|
93
|
+
|
|
94
|
+
@abstractmethod
|
|
95
|
+
def _data_setter(
|
|
96
|
+
self,
|
|
97
|
+
X: np.ndarray | pd.DataFrame,
|
|
98
|
+
y: np.ndarray | pd.DataFrame | list = None,
|
|
99
|
+
) -> None:
|
|
100
|
+
"""
|
|
101
|
+
Sets new data in the model.
|
|
102
|
+
|
|
103
|
+
Parameters
|
|
104
|
+
----------
|
|
105
|
+
X : array, shape (n_obs, n_features)
|
|
106
|
+
The training input samples.
|
|
107
|
+
y : array, shape (n_obs,)
|
|
108
|
+
The target values (real numbers).
|
|
109
|
+
|
|
110
|
+
Returns
|
|
111
|
+
-------
|
|
112
|
+
None
|
|
113
|
+
|
|
114
|
+
Examples
|
|
115
|
+
--------
|
|
116
|
+
>>> def _data_setter(self, data : pd.DataFrame):
|
|
117
|
+
>>> with self.model:
|
|
118
|
+
>>> pm.set_data({'x': X['x'].values})
|
|
119
|
+
>>> try: # if y values in new data
|
|
120
|
+
>>> pm.set_data({'y_data': y.values})
|
|
121
|
+
>>> except: # dummies otherwise
|
|
122
|
+
>>> pm.set_data({'y_data': np.zeros(len(data))})
|
|
123
|
+
|
|
124
|
+
"""
|
|
125
|
+
|
|
126
|
+
raise NotImplementedError
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
@abstractmethod
|
|
130
|
+
def output_var(self):
|
|
131
|
+
"""
|
|
132
|
+
Returns the name of the output variable of the model.
|
|
133
|
+
|
|
134
|
+
Returns
|
|
135
|
+
-------
|
|
136
|
+
output_var : str
|
|
137
|
+
Name of the output variable of the model.
|
|
138
|
+
"""
|
|
139
|
+
raise NotImplementedError
|
|
140
|
+
|
|
141
|
+
@staticmethod
|
|
142
|
+
@abstractmethod
|
|
143
|
+
def get_default_model_config() -> dict:
|
|
144
|
+
"""
|
|
145
|
+
Returns a class default config dict for model builder if no model_config is provided on class initialization
|
|
146
|
+
Useful for understanding structure of required model_config to allow its customization by users
|
|
147
|
+
|
|
148
|
+
Examples
|
|
149
|
+
--------
|
|
150
|
+
>>> @staticmethod
|
|
151
|
+
>>> def default_model_config():
|
|
152
|
+
>>> return {
|
|
153
|
+
>>> 'a' : {
|
|
154
|
+
>>> 'loc': 7,
|
|
155
|
+
>>> 'scale' : 3
|
|
156
|
+
>>> },
|
|
157
|
+
>>> 'b' : {
|
|
158
|
+
>>> 'loc': 3,
|
|
159
|
+
>>> 'scale': 5
|
|
160
|
+
>>> }
|
|
161
|
+
>>> 'obs_error': 2
|
|
162
|
+
>>> }
|
|
163
|
+
|
|
164
|
+
Returns
|
|
165
|
+
-------
|
|
166
|
+
model_config : dict
|
|
167
|
+
A set of default parameters for predictor distributions that allow to save and recreate the model.
|
|
168
|
+
"""
|
|
169
|
+
raise NotImplementedError
|
|
170
|
+
|
|
171
|
+
@staticmethod
|
|
172
|
+
@abstractmethod
|
|
173
|
+
def get_default_sampler_config(self) -> dict:
|
|
174
|
+
"""
|
|
175
|
+
Returns a class default sampler dict for model builder if no sampler_config is provided on class initialization
|
|
176
|
+
Useful for understanding structure of required sampler_config to allow its customization by users
|
|
177
|
+
|
|
178
|
+
Examples
|
|
179
|
+
--------
|
|
180
|
+
>>> @staticmethod
|
|
181
|
+
>>> def default_sampler_config():
|
|
182
|
+
>>> return {
|
|
183
|
+
>>> 'draws': 1_000,
|
|
184
|
+
>>> 'tune': 1_000,
|
|
185
|
+
>>> 'chains': 1,
|
|
186
|
+
>>> 'target_accept': 0.95,
|
|
187
|
+
>>> }
|
|
188
|
+
|
|
189
|
+
Returns
|
|
190
|
+
-------
|
|
191
|
+
sampler_config : dict
|
|
192
|
+
A set of default settings for used by model in fit process.
|
|
193
|
+
"""
|
|
194
|
+
raise NotImplementedError
|
|
195
|
+
|
|
196
|
+
@abstractmethod
|
|
197
|
+
def _generate_and_preprocess_model_data(
|
|
198
|
+
self, X: pd.DataFrame | pd.Series, y: pd.Series
|
|
199
|
+
) -> None:
|
|
200
|
+
"""
|
|
201
|
+
Applies preprocessing to the data before fitting the model.
|
|
202
|
+
if validate is True, it will check if the data is valid for the model.
|
|
203
|
+
sets self.model_coords based on provided dataset
|
|
204
|
+
|
|
205
|
+
In case of optional parameters being passed into the model, this method should implement the conditional
|
|
206
|
+
logic responsible for correct handling of the optional parameters, and including them into the dataset.
|
|
207
|
+
|
|
208
|
+
Parameters
|
|
209
|
+
----------
|
|
210
|
+
X : array, shape (n_obs, n_features)
|
|
211
|
+
y : array, shape (n_obs,)
|
|
212
|
+
|
|
213
|
+
Examples
|
|
214
|
+
--------
|
|
215
|
+
>>> @classmethod
|
|
216
|
+
>>> def _generate_and_preprocess_model_data(self, X, y):
|
|
217
|
+
coords = {
|
|
218
|
+
'x_dim': X.dim_variable,
|
|
219
|
+
} #only include if applicable for your model
|
|
220
|
+
>>> self.X = X
|
|
221
|
+
>>> self.y = y
|
|
222
|
+
|
|
223
|
+
Returns
|
|
224
|
+
-------
|
|
225
|
+
None
|
|
226
|
+
|
|
227
|
+
"""
|
|
228
|
+
raise NotImplementedError
|
|
229
|
+
|
|
230
|
+
@abstractmethod
|
|
231
|
+
def build_model(
|
|
232
|
+
self,
|
|
233
|
+
X: pd.DataFrame,
|
|
234
|
+
y: pd.Series,
|
|
235
|
+
**kwargs,
|
|
236
|
+
) -> None:
|
|
237
|
+
"""
|
|
238
|
+
Creates an instance of pm.Model based on provided data and model_config, and
|
|
239
|
+
attaches it to self.
|
|
240
|
+
|
|
241
|
+
Parameters
|
|
242
|
+
----------
|
|
243
|
+
X : pd.DataFrame
|
|
244
|
+
The input data that is going to be used in the model. This should be a DataFrame
|
|
245
|
+
containing the features (predictors) for the model. For efficiency reasons, it should
|
|
246
|
+
only contain the necessary data columns, not the entire available dataset, as this
|
|
247
|
+
will be encoded into the data used to recreate the model.
|
|
248
|
+
|
|
249
|
+
y : pd.Series
|
|
250
|
+
The target data for the model. This should be a Series representing the output
|
|
251
|
+
or dependent variable for the model.
|
|
252
|
+
|
|
253
|
+
kwargs : dict
|
|
254
|
+
Additional keyword arguments that may be used for model configuration.
|
|
255
|
+
|
|
256
|
+
See Also
|
|
257
|
+
--------
|
|
258
|
+
default_model_config : returns default model config
|
|
259
|
+
|
|
260
|
+
Returns
|
|
261
|
+
-------
|
|
262
|
+
None
|
|
263
|
+
|
|
264
|
+
Raises
|
|
265
|
+
------
|
|
266
|
+
NotImplementedError
|
|
267
|
+
This is an abstract method and must be implemented in a subclass.
|
|
268
|
+
"""
|
|
269
|
+
raise NotImplementedError
|
|
270
|
+
|
|
271
|
+
def sample_model(self, **kwargs):
|
|
272
|
+
"""
|
|
273
|
+
Sample from the PyMC model.
|
|
274
|
+
|
|
275
|
+
Parameters
|
|
276
|
+
----------
|
|
277
|
+
**kwargs : dict
|
|
278
|
+
Additional keyword arguments to pass to the PyMC sampler.
|
|
279
|
+
|
|
280
|
+
Returns
|
|
281
|
+
-------
|
|
282
|
+
xarray.Dataset
|
|
283
|
+
The PyMC samples dataset.
|
|
284
|
+
|
|
285
|
+
Raises
|
|
286
|
+
------
|
|
287
|
+
RuntimeError
|
|
288
|
+
If the PyMC model hasn't been built yet.
|
|
289
|
+
|
|
290
|
+
Examples
|
|
291
|
+
--------
|
|
292
|
+
>>> self.build_model()
|
|
293
|
+
>>> idata = self.sample_model(draws=100, tune=10)
|
|
294
|
+
>>> assert isinstance(idata, xr.Dataset)
|
|
295
|
+
>>> assert "posterior" in idata
|
|
296
|
+
>>> assert "prior" in idata
|
|
297
|
+
>>> assert "observed_data" in idata
|
|
298
|
+
>>> assert "log_likelihood" in idata
|
|
299
|
+
"""
|
|
300
|
+
if self.model is None:
|
|
301
|
+
raise RuntimeError(
|
|
302
|
+
"The model hasn't been built yet, call .build_model() first or call .fit() instead."
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
with self.model:
|
|
306
|
+
sampler_args = {**self.sampler_config, **kwargs}
|
|
307
|
+
idata = pm.sample(**sampler_args)
|
|
308
|
+
idata.extend(pm.sample_prior_predictive(), join="right")
|
|
309
|
+
idata.extend(pm.sample_posterior_predictive(idata), join="right")
|
|
310
|
+
|
|
311
|
+
idata = self.set_idata_attrs(idata)
|
|
312
|
+
return idata
|
|
313
|
+
|
|
314
|
+
def set_idata_attrs(self, idata=None):
|
|
315
|
+
"""
|
|
316
|
+
Set attributes on an InferenceData object.
|
|
317
|
+
|
|
318
|
+
Parameters
|
|
319
|
+
----------
|
|
320
|
+
idata : arviz.InferenceData, optional
|
|
321
|
+
The InferenceData object to set attributes on.
|
|
322
|
+
|
|
323
|
+
Raises
|
|
324
|
+
------
|
|
325
|
+
RuntimeError
|
|
326
|
+
If no InferenceData object is provided.
|
|
327
|
+
|
|
328
|
+
Returns
|
|
329
|
+
-------
|
|
330
|
+
None
|
|
331
|
+
|
|
332
|
+
Examples
|
|
333
|
+
--------
|
|
334
|
+
>>> model = MyModel(ModelBuilder)
|
|
335
|
+
>>> idata = az.InferenceData(your_dataset)
|
|
336
|
+
>>> model.set_idata_attrs(idata=idata)
|
|
337
|
+
>>> assert "id" in idata.attrs #this and the following lines are part of doctest, not user manual
|
|
338
|
+
>>> assert "model_type" in idata.attrs
|
|
339
|
+
>>> assert "version" in idata.attrs
|
|
340
|
+
>>> assert "sampler_config" in idata.attrs
|
|
341
|
+
>>> assert "model_config" in idata.attrs
|
|
342
|
+
"""
|
|
343
|
+
if idata is None:
|
|
344
|
+
idata = self.idata
|
|
345
|
+
if idata is None:
|
|
346
|
+
raise RuntimeError("No idata provided to set attrs on.")
|
|
347
|
+
idata.attrs["id"] = self.id
|
|
348
|
+
idata.attrs["model_type"] = self._model_type
|
|
349
|
+
idata.attrs["version"] = self.version
|
|
350
|
+
idata.attrs["sampler_config"] = json.dumps(self.sampler_config)
|
|
351
|
+
idata.attrs["model_config"] = json.dumps(self._serializable_model_config)
|
|
352
|
+
# Only classes with non-dataset parameters will implement save_input_params
|
|
353
|
+
if hasattr(self, "_save_input_params"):
|
|
354
|
+
self._save_input_params(idata)
|
|
355
|
+
return idata
|
|
356
|
+
|
|
357
|
+
def save(self, fname: str) -> None:
|
|
358
|
+
"""
|
|
359
|
+
Save the model's inference data to a file.
|
|
360
|
+
|
|
361
|
+
Parameters
|
|
362
|
+
----------
|
|
363
|
+
fname : str
|
|
364
|
+
The name and path of the file to save the inference data with model parameters.
|
|
365
|
+
|
|
366
|
+
Returns
|
|
367
|
+
-------
|
|
368
|
+
None
|
|
369
|
+
|
|
370
|
+
Raises
|
|
371
|
+
------
|
|
372
|
+
RuntimeError
|
|
373
|
+
If the model hasn't been fit yet (no inference data available).
|
|
374
|
+
|
|
375
|
+
Examples
|
|
376
|
+
--------
|
|
377
|
+
This method is meant to be overridden and implemented by subclasses.
|
|
378
|
+
It should not be called directly on the base abstract class or its instances.
|
|
379
|
+
|
|
380
|
+
>>> class MyModel(ModelBuilder):
|
|
381
|
+
>>> def __init__(self):
|
|
382
|
+
>>> super().__init__()
|
|
383
|
+
>>> model = MyModel()
|
|
384
|
+
>>> model.fit(data)
|
|
385
|
+
>>> model.save('model_results.nc') # This will call the overridden method in MyModel
|
|
386
|
+
"""
|
|
387
|
+
if self.idata is not None and "posterior" in self.idata:
|
|
388
|
+
file = Path(str(fname))
|
|
389
|
+
self.idata.to_netcdf(str(file))
|
|
390
|
+
else:
|
|
391
|
+
raise RuntimeError("The model hasn't been fit yet, call .fit() first")
|
|
392
|
+
|
|
393
|
+
@classmethod
|
|
394
|
+
def _model_config_formatting(cls, model_config: dict) -> dict:
|
|
395
|
+
"""
|
|
396
|
+
Because of json serialization, model_config values that were originally tuples or numpy are being encoded as lists.
|
|
397
|
+
This function converts them back to tuples and numpy arrays to ensure correct id encoding.
|
|
398
|
+
"""
|
|
399
|
+
for key in model_config:
|
|
400
|
+
if isinstance(model_config[key], dict):
|
|
401
|
+
for sub_key in model_config[key]:
|
|
402
|
+
if isinstance(model_config[key][sub_key], list):
|
|
403
|
+
# Check if "dims" key to convert it to tuple
|
|
404
|
+
if sub_key == "dims":
|
|
405
|
+
model_config[key][sub_key] = tuple(model_config[key][sub_key])
|
|
406
|
+
# Convert all other lists to numpy arrays
|
|
407
|
+
else:
|
|
408
|
+
model_config[key][sub_key] = np.array(model_config[key][sub_key])
|
|
409
|
+
return model_config
|
|
410
|
+
|
|
411
|
+
@classmethod
|
|
412
|
+
def load(cls, fname: str):
|
|
413
|
+
"""
|
|
414
|
+
Creates a ModelBuilder instance from a file,
|
|
415
|
+
Loads inference data for the model.
|
|
416
|
+
|
|
417
|
+
Parameters
|
|
418
|
+
----------
|
|
419
|
+
fname : string
|
|
420
|
+
This denotes the name with path from where idata should be loaded from.
|
|
421
|
+
|
|
422
|
+
Returns
|
|
423
|
+
-------
|
|
424
|
+
Returns an instance of ModelBuilder.
|
|
425
|
+
|
|
426
|
+
Raises
|
|
427
|
+
------
|
|
428
|
+
ValueError
|
|
429
|
+
If the inference data that is loaded doesn't match with the model.
|
|
430
|
+
|
|
431
|
+
Examples
|
|
432
|
+
--------
|
|
433
|
+
>>> class MyModel(ModelBuilder):
|
|
434
|
+
>>> ...
|
|
435
|
+
>>> name = './mymodel.nc'
|
|
436
|
+
>>> imported_model = MyModel.load(name)
|
|
437
|
+
"""
|
|
438
|
+
filepath = Path(str(fname))
|
|
439
|
+
idata = az.from_netcdf(filepath)
|
|
440
|
+
# needs to be converted, because json.loads was changing tuple to list
|
|
441
|
+
model_config = cls._model_config_formatting(json.loads(idata.attrs["model_config"]))
|
|
442
|
+
model = cls(
|
|
443
|
+
model_config=model_config,
|
|
444
|
+
sampler_config=json.loads(idata.attrs["sampler_config"]),
|
|
445
|
+
)
|
|
446
|
+
model.idata = idata
|
|
447
|
+
dataset = idata.fit_data.to_dataframe()
|
|
448
|
+
X = dataset.drop(columns=[model.output_var])
|
|
449
|
+
y = dataset[model.output_var]
|
|
450
|
+
model.build_model(X, y)
|
|
451
|
+
# All previously used data is in idata.
|
|
452
|
+
|
|
453
|
+
if model.id != idata.attrs["id"]:
|
|
454
|
+
raise ValueError(
|
|
455
|
+
f"The file '{fname}' does not contain an inference data of the same model or configuration as '{cls._model_type}'"
|
|
456
|
+
)
|
|
457
|
+
|
|
458
|
+
return model
|
|
459
|
+
|
|
460
|
+
def fit(
|
|
461
|
+
self,
|
|
462
|
+
X: pd.DataFrame,
|
|
463
|
+
y: pd.Series | None = None,
|
|
464
|
+
progressbar: bool = True,
|
|
465
|
+
predictor_names: list[str] | None = None,
|
|
466
|
+
random_seed: RandomState = None,
|
|
467
|
+
**kwargs: Any,
|
|
468
|
+
) -> az.InferenceData:
|
|
469
|
+
"""
|
|
470
|
+
Fit a model using the data passed as a parameter.
|
|
471
|
+
Sets attrs to inference data of the model.
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
Parameters
|
|
475
|
+
----------
|
|
476
|
+
X : array-like if sklearn is available, otherwise array, shape (n_obs, n_features)
|
|
477
|
+
The training input samples.
|
|
478
|
+
y : array-like if sklearn is available, otherwise array, shape (n_obs,)
|
|
479
|
+
The target values (real numbers).
|
|
480
|
+
progressbar : bool
|
|
481
|
+
Specifies whether the fit progressbar should be displayed
|
|
482
|
+
predictor_names: List[str] = None,
|
|
483
|
+
Allows for custom naming of predictors given in a form of 2dArray
|
|
484
|
+
allows for naming of predictors when given in a form of np.ndarray, if not provided the predictors will be named like predictor1, predictor2...
|
|
485
|
+
random_seed : RandomState
|
|
486
|
+
Provides sampler with initial random seed for obtaining reproducible samples
|
|
487
|
+
**kwargs : Any
|
|
488
|
+
Custom sampler settings can be provided in form of keyword arguments.
|
|
489
|
+
|
|
490
|
+
Returns
|
|
491
|
+
-------
|
|
492
|
+
self : az.InferenceData
|
|
493
|
+
returns inference data of the fitted model.
|
|
494
|
+
|
|
495
|
+
Examples
|
|
496
|
+
--------
|
|
497
|
+
>>> model = MyModel()
|
|
498
|
+
>>> idata = model.fit(data)
|
|
499
|
+
Auto-assigning NUTS sampler...
|
|
500
|
+
Initializing NUTS using jitter+adapt_diag...
|
|
501
|
+
"""
|
|
502
|
+
if predictor_names is None:
|
|
503
|
+
predictor_names = []
|
|
504
|
+
if y is None:
|
|
505
|
+
y = np.zeros(X.shape[0])
|
|
506
|
+
y = pd.DataFrame({self.output_var: y})
|
|
507
|
+
self._generate_and_preprocess_model_data(X, y.values.flatten())
|
|
508
|
+
self.build_model(self.X, self.y)
|
|
509
|
+
|
|
510
|
+
sampler_config = self.sampler_config.copy()
|
|
511
|
+
sampler_config["progressbar"] = progressbar
|
|
512
|
+
sampler_config["random_seed"] = random_seed
|
|
513
|
+
sampler_config.update(**kwargs)
|
|
514
|
+
self.idata = self.sample_model(**sampler_config)
|
|
515
|
+
|
|
516
|
+
X_df = pd.DataFrame(X, columns=X.columns)
|
|
517
|
+
combined_data = pd.concat([X_df, y], axis=1)
|
|
518
|
+
assert all(combined_data.columns), "All columns must have non-empty names"
|
|
519
|
+
with warnings.catch_warnings():
|
|
520
|
+
warnings.filterwarnings(
|
|
521
|
+
"ignore",
|
|
522
|
+
category=UserWarning,
|
|
523
|
+
message="The group fit_data is not defined in the InferenceData scheme",
|
|
524
|
+
)
|
|
525
|
+
self.idata.add_groups(fit_data=combined_data.to_xarray()) # type: ignore
|
|
526
|
+
|
|
527
|
+
return self.idata # type: ignore
|
|
528
|
+
|
|
529
|
+
def predict(
|
|
530
|
+
self,
|
|
531
|
+
X_pred: np.ndarray | pd.DataFrame | pd.Series,
|
|
532
|
+
extend_idata: bool = True,
|
|
533
|
+
**kwargs,
|
|
534
|
+
) -> np.ndarray:
|
|
535
|
+
"""
|
|
536
|
+
Uses model to predict on unseen data and return point prediction of all the samples. The point prediction
|
|
537
|
+
for each input row is the expected output value, computed as the mean of MCMC samples.
|
|
538
|
+
|
|
539
|
+
Parameters
|
|
540
|
+
----------
|
|
541
|
+
X_pred : array-like if sklearn is available, otherwise array, shape (n_pred, n_features)
|
|
542
|
+
The input data used for prediction.
|
|
543
|
+
extend_idata : Boolean determining whether the predictions should be added to inference data object.
|
|
544
|
+
Defaults to True.
|
|
545
|
+
**kwargs: Additional arguments to pass to pymc.sample_posterior_predictive
|
|
546
|
+
|
|
547
|
+
Returns
|
|
548
|
+
-------
|
|
549
|
+
y_pred : ndarray, shape (n_pred,)
|
|
550
|
+
Predicted output corresponding to input X_pred.
|
|
551
|
+
|
|
552
|
+
Examples
|
|
553
|
+
--------
|
|
554
|
+
>>> model = MyModel()
|
|
555
|
+
>>> idata = model.fit(data)
|
|
556
|
+
>>> x_pred = []
|
|
557
|
+
>>> prediction_data = pd.DataFrame({'input':x_pred})
|
|
558
|
+
>>> pred_mean = model.predict(prediction_data)
|
|
559
|
+
"""
|
|
560
|
+
|
|
561
|
+
posterior_predictive_samples = self.sample_posterior_predictive(
|
|
562
|
+
X_pred, extend_idata, combined=False, **kwargs
|
|
563
|
+
)
|
|
564
|
+
|
|
565
|
+
if self.output_var not in posterior_predictive_samples:
|
|
566
|
+
raise KeyError(
|
|
567
|
+
f"Output variable {self.output_var} not found in posterior predictive samples."
|
|
568
|
+
)
|
|
569
|
+
|
|
570
|
+
posterior_means = posterior_predictive_samples[self.output_var].mean(
|
|
571
|
+
dim=["chain", "draw"], keep_attrs=True
|
|
572
|
+
)
|
|
573
|
+
return posterior_means.data
|
|
574
|
+
|
|
575
|
+
def sample_prior_predictive(
|
|
576
|
+
self,
|
|
577
|
+
X_pred,
|
|
578
|
+
y_pred=None,
|
|
579
|
+
samples: int | None = None,
|
|
580
|
+
extend_idata: bool = False,
|
|
581
|
+
combined: bool = True,
|
|
582
|
+
**kwargs,
|
|
583
|
+
):
|
|
584
|
+
"""
|
|
585
|
+
Sample from the model's prior predictive distribution.
|
|
586
|
+
|
|
587
|
+
Parameters
|
|
588
|
+
----------
|
|
589
|
+
X_pred : array, shape (n_pred, n_features)
|
|
590
|
+
The input data used for prediction using prior distribution.
|
|
591
|
+
samples : int
|
|
592
|
+
Number of samples from the prior parameter distributions to generate.
|
|
593
|
+
If not set, uses sampler_config['draws'] if that is available, otherwise defaults to 500.
|
|
594
|
+
extend_idata : Boolean determining whether the predictions should be added to inference data object.
|
|
595
|
+
Defaults to False.
|
|
596
|
+
combined: Combine chain and draw dims into sample. Won't work if a dim named sample already exists.
|
|
597
|
+
Defaults to True.
|
|
598
|
+
**kwargs: Additional arguments to pass to pymc.sample_prior_predictive
|
|
599
|
+
|
|
600
|
+
Returns
|
|
601
|
+
-------
|
|
602
|
+
prior_predictive_samples : DataArray, shape (n_pred, samples)
|
|
603
|
+
Prior predictive samples for each input X_pred
|
|
604
|
+
"""
|
|
605
|
+
if y_pred is None:
|
|
606
|
+
y_pred = pd.Series(np.zeros(len(X_pred)), name=self.output_var)
|
|
607
|
+
if samples is None:
|
|
608
|
+
samples = self.sampler_config.get("draws", 500)
|
|
609
|
+
|
|
610
|
+
if self.model is None:
|
|
611
|
+
self.build_model(X_pred, y_pred)
|
|
612
|
+
else:
|
|
613
|
+
self._data_setter(X_pred, y_pred)
|
|
614
|
+
with self.model: # sample with new input data
|
|
615
|
+
prior_pred: az.InferenceData = pm.sample_prior_predictive(samples, **kwargs)
|
|
616
|
+
self.set_idata_attrs(prior_pred)
|
|
617
|
+
if extend_idata:
|
|
618
|
+
if self.idata is not None:
|
|
619
|
+
self.idata.extend(prior_pred, join="right")
|
|
620
|
+
else:
|
|
621
|
+
self.idata = prior_pred
|
|
622
|
+
|
|
623
|
+
prior_predictive_samples = az.extract(prior_pred, "prior_predictive", combined=combined)
|
|
624
|
+
|
|
625
|
+
return prior_predictive_samples
|
|
626
|
+
|
|
627
|
+
def sample_posterior_predictive(self, X_pred, extend_idata, combined, **kwargs):
|
|
628
|
+
"""
|
|
629
|
+
Sample from the model's posterior predictive distribution.
|
|
630
|
+
|
|
631
|
+
Parameters
|
|
632
|
+
----------
|
|
633
|
+
X_pred : array, shape (n_pred, n_features)
|
|
634
|
+
The input data used for prediction using prior distribution..
|
|
635
|
+
extend_idata : Boolean determining whether the predictions should be added to inference data object.
|
|
636
|
+
Defaults to False.
|
|
637
|
+
combined: Combine chain and draw dims into sample. Won't work if a dim named sample already exists.
|
|
638
|
+
Defaults to True.
|
|
639
|
+
**kwargs: Additional arguments to pass to pymc.sample_posterior_predictive
|
|
640
|
+
|
|
641
|
+
Returns
|
|
642
|
+
-------
|
|
643
|
+
posterior_predictive_samples : DataArray, shape (n_pred, samples)
|
|
644
|
+
Posterior predictive samples for each input X_pred
|
|
645
|
+
"""
|
|
646
|
+
self._data_setter(X_pred)
|
|
647
|
+
|
|
648
|
+
with self.model: # sample with new input data
|
|
649
|
+
post_pred = pm.sample_posterior_predictive(self.idata, **kwargs)
|
|
650
|
+
if extend_idata:
|
|
651
|
+
self.idata.extend(post_pred, join="right")
|
|
652
|
+
|
|
653
|
+
posterior_predictive_samples = az.extract(
|
|
654
|
+
post_pred, "posterior_predictive", combined=combined
|
|
655
|
+
)
|
|
656
|
+
|
|
657
|
+
return posterior_predictive_samples
|
|
658
|
+
|
|
659
|
+
def get_params(self, deep=True):
|
|
660
|
+
"""
|
|
661
|
+
Get all the model parameters needed to instantiate a copy of the model, not including training data.
|
|
662
|
+
"""
|
|
663
|
+
return {
|
|
664
|
+
"model_config": self.model_config,
|
|
665
|
+
"sampler_config": self.sampler_config,
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
def set_params(self, **params):
|
|
669
|
+
"""
|
|
670
|
+
Set all the model parameters needed to instantiate the model, not including training data.
|
|
671
|
+
"""
|
|
672
|
+
self.model_config = params["model_config"]
|
|
673
|
+
self.sampler_config = params["sampler_config"]
|
|
674
|
+
|
|
675
|
+
@property
|
|
676
|
+
@abstractmethod
|
|
677
|
+
def _serializable_model_config(self) -> dict[str, int | float | dict]:
|
|
678
|
+
"""
|
|
679
|
+
Converts non-serializable values from model_config to their serializable reversable equivalent.
|
|
680
|
+
Data types like pandas DataFrame, Series or datetime aren't JSON serializable,
|
|
681
|
+
so in order to save the model they need to be formatted.
|
|
682
|
+
|
|
683
|
+
Returns
|
|
684
|
+
-------
|
|
685
|
+
model_config: dict
|
|
686
|
+
"""
|
|
687
|
+
|
|
688
|
+
def predict_proba(
|
|
689
|
+
self,
|
|
690
|
+
X_pred: np.ndarray | pd.DataFrame | pd.Series,
|
|
691
|
+
extend_idata: bool = True,
|
|
692
|
+
combined: bool = False,
|
|
693
|
+
**kwargs,
|
|
694
|
+
) -> xr.DataArray:
|
|
695
|
+
"""Alias for `predict_posterior`, for consistency with scikit-learn probabilistic estimators."""
|
|
696
|
+
return self.predict_posterior(X_pred, extend_idata, combined, **kwargs)
|
|
697
|
+
|
|
698
|
+
def predict_posterior(
|
|
699
|
+
self,
|
|
700
|
+
X_pred: np.ndarray | pd.DataFrame | pd.Series,
|
|
701
|
+
extend_idata: bool = True,
|
|
702
|
+
combined: bool = True,
|
|
703
|
+
**kwargs,
|
|
704
|
+
) -> xr.DataArray:
|
|
705
|
+
"""
|
|
706
|
+
Generate posterior predictive samples on unseen data.
|
|
707
|
+
|
|
708
|
+
Parameters
|
|
709
|
+
----------
|
|
710
|
+
X_pred : array-like if sklearn is available, otherwise array, shape (n_pred, n_features)
|
|
711
|
+
The input data used for prediction.
|
|
712
|
+
extend_idata : Boolean determining whether the predictions should be added to inference data object.
|
|
713
|
+
Defaults to True.
|
|
714
|
+
combined: Combine chain and draw dims into sample. Won't work if a dim named sample already exists.
|
|
715
|
+
Defaults to True.
|
|
716
|
+
**kwargs: Additional arguments to pass to pymc.sample_posterior_predictive
|
|
717
|
+
|
|
718
|
+
Returns
|
|
719
|
+
-------
|
|
720
|
+
y_pred : DataArray, shape (n_pred, chains * draws) if combined is True, otherwise (chains, draws, n_pred)
|
|
721
|
+
Posterior predictive samples for each input X_pred
|
|
722
|
+
"""
|
|
723
|
+
|
|
724
|
+
X_pred = self._validate_data(X_pred)
|
|
725
|
+
posterior_predictive_samples = self.sample_posterior_predictive(
|
|
726
|
+
X_pred, extend_idata, combined, **kwargs
|
|
727
|
+
)
|
|
728
|
+
|
|
729
|
+
if self.output_var not in posterior_predictive_samples:
|
|
730
|
+
raise KeyError(
|
|
731
|
+
f"Output variable {self.output_var} not found in posterior predictive samples."
|
|
732
|
+
)
|
|
733
|
+
|
|
734
|
+
return posterior_predictive_samples[self.output_var]
|
|
735
|
+
|
|
736
|
+
@property
|
|
737
|
+
def id(self) -> str:
|
|
738
|
+
"""
|
|
739
|
+
Generate a unique hash value for the model.
|
|
740
|
+
|
|
741
|
+
The hash value is created using the last 16 characters of the SHA256 hash encoding, based on the model configuration,
|
|
742
|
+
version, and model type.
|
|
743
|
+
|
|
744
|
+
Returns
|
|
745
|
+
-------
|
|
746
|
+
str
|
|
747
|
+
A string of length 16 characters containing a unique hash of the model.
|
|
748
|
+
|
|
749
|
+
Examples
|
|
750
|
+
--------
|
|
751
|
+
>>> model = MyModel()
|
|
752
|
+
>>> model.id
|
|
753
|
+
'0123456789abcdef'
|
|
754
|
+
"""
|
|
755
|
+
hasher = hashlib.sha256()
|
|
756
|
+
hasher.update(str(self.model_config.values()).encode())
|
|
757
|
+
hasher.update(self.version.encode())
|
|
758
|
+
hasher.update(self._model_type.encode())
|
|
759
|
+
return hasher.hexdigest()[:16]
|