-
-
Notifications
You must be signed in to change notification settings - Fork 52
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add build_model
abstractmethod to ModelBuilder
#142
Merged
Merged
Changes from 4 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
455de05
adaptations to integrate with mmm
michaelraczycki e62f924
adapted model_config and descriptions
michaelraczycki 6f4bb25
fixed ModuleNotFoundError from build
michaelraczycki 4c99877
small tweaks to make mmm tests work smoother
michaelraczycki e89724c
new test for save, fit allows custom configs
michaelraczycki 947a67d
updating create_sample_input example
michaelraczycki File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -17,12 +17,13 @@ | |
import json | ||
from abc import abstractmethod | ||
from pathlib import Path | ||
from typing import Dict, Union | ||
from typing import Any, Dict, Union | ||
|
||
import arviz as az | ||
import numpy as np | ||
import pandas as pd | ||
import pymc as pm | ||
from pymc.util import RandomState | ||
|
||
|
||
class ModelBuilder: | ||
|
@@ -100,7 +101,7 @@ def _data_setter( | |
@abstractmethod | ||
def create_sample_input(): | ||
""" | ||
Needs to be implemented by the user in the inherited class. | ||
Needs to be implemented by the user in the child class. | ||
Returns examples for data, model_config, sampler_config. | ||
This is useful for understanding the required | ||
data structures for the user model. | ||
|
@@ -114,12 +115,15 @@ def create_sample_input(): | |
>>> data = pd.DataFrame({'input': x, 'output': y}) | ||
|
||
>>> model_config = { | ||
>>> 'a_loc': 7, | ||
>>> 'a_scale': 3, | ||
>>> 'b_loc': 5, | ||
>>> 'b_scale': 3, | ||
>>> 'obs_error': 2, | ||
>>> } | ||
>>> 'a' : { | ||
>>> 'a_loc': 7, | ||
>>> 'a_scale' : 3 | ||
>>> }, | ||
>>> 'b' : { | ||
>>> 'b_loc': 3, | ||
>>> 'b_scale': 5 | ||
>>> } | ||
>>> 'obs_error': 2 | ||
|
||
>>> sampler_config = { | ||
>>> 'draws': 1_000, | ||
|
@@ -132,6 +136,31 @@ def create_sample_input(): | |
|
||
raise NotImplementedError | ||
|
||
@abstractmethod | ||
def build_model( | ||
model_data: Dict[str, Union[np.ndarray, pd.DataFrame, pd.Series]], | ||
model_config: Dict[str, Union[int, float, Dict]], | ||
) -> None: | ||
""" | ||
Needs to be implemented by the user in the child class. | ||
Creates an instance of pm.Model based on provided model_data and model_config, and | ||
attaches it to self. | ||
|
||
Required Parameters | ||
---------- | ||
model_data - preformated data that is going to be used in the model. | ||
For efficiency reasons it should contain only the necesary data columns, not entire available | ||
dataset since it's going to be encoded into data used to recreate the model. | ||
model_config - dictionary where keys are strings representing names of parameters of the model, values are | ||
dictionaries of parameters needed for creating model parameters (see example in create_model_input) | ||
|
||
Returns: | ||
---------- | ||
None | ||
|
||
""" | ||
raise NotImplementedError | ||
|
||
def save(self, fname: str) -> None: | ||
""" | ||
Saves inference data of the model. | ||
|
@@ -191,7 +220,7 @@ def load(cls, fname: str): | |
data=idata.fit_data.to_dataframe(), | ||
) | ||
model_builder.idata = idata | ||
model_builder.build() | ||
model_builder.idata = model_builder.fit() | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What if the model was already fit? |
||
if model_builder.id != idata.attrs["id"]: | ||
raise ValueError( | ||
f"The file '{fname}' does not contain an inference data of the same model or configuration as '{cls._model_type}'" | ||
|
@@ -200,7 +229,12 @@ def load(cls, fname: str): | |
return model_builder | ||
|
||
def fit( | ||
self, data: Dict[str, Union[np.ndarray, pd.DataFrame, pd.Series]] = None | ||
self, | ||
progressbar: bool = True, | ||
random_seed: RandomState = None, | ||
data: Dict[str, Union[np.ndarray, pd.DataFrame, pd.Series]] = None, | ||
*args: Any, | ||
**kwargs: Any, | ||
) -> az.InferenceData: | ||
""" | ||
Fit a model using the data passed as a parameter. | ||
|
@@ -227,20 +261,21 @@ def fit( | |
# If a new data was provided, assign it to the model | ||
if data is not None: | ||
self.data = data | ||
|
||
self.build() | ||
self._data_setter(data) | ||
|
||
self.model_data, self.model_config, self.sampler_config = self.create_sample_input( | ||
data=self.data | ||
) | ||
self.build_model(self.model_data, self.model_config) | ||
self._data_setter(self.model_data) | ||
with self.model: | ||
self.idata = pm.sample(**self.sampler_config) | ||
self.idata = pm.sample(**self.sampler_config, **kwargs) | ||
self.idata.extend(pm.sample_prior_predictive()) | ||
self.idata.extend(pm.sample_posterior_predictive(self.idata)) | ||
|
||
self.idata.attrs["id"] = self.id | ||
self.idata.attrs["model_type"] = self._model_type | ||
self.idata.attrs["version"] = self.version | ||
self.idata.attrs["sampler_config"] = json.dumps(self.sampler_config) | ||
self.idata.attrs["model_config"] = json.dumps(self.model_config) | ||
self.idata.attrs["model_config"] = json.dumps(self.serializable_model_config) | ||
self.idata.add_groups(fit_data=self.data.to_xarray()) | ||
return self.idata | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should this not just be
loc
, thea
seems redundant.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
true, good catch