Skip to content
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

Create load_from_idata method #1211

Merged
merged 2 commits into from
Nov 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 28 additions & 5 deletions pymc_marketing/model_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,12 +480,39 @@ def attrs_to_init_kwargs(cls, attrs) -> dict[str, Any]:
"sampler_config": json.loads(attrs["sampler_config"]),
}

def build_from_idata(self, idata: az.InferenceData) -> None:
"""Build model from the InferenceData object.

This is part of the :func:`load` method. See :func:`load` for more larger context.

Usually a wrapper around the :func:`build_model` method unless the model
has some additional steps to be built.

Parameters
----------
idata : az.InferenceData
The InferenceData object to build the model from.

"""
dataset = idata.fit_data.to_dataframe() # type: ignore
X = dataset.drop(columns=[self.output_var])
y = dataset[self.output_var]

self.build_model(X, y)

@classmethod
def load(cls, fname: str):
"""Create a ModelBuilder instance from a file.

Loads inference data for the model.

This class method has a few steps:

- Load the InferenceData from the file.
- Construct a new instance of the model using the InferenceData attrs
- Build the model from the InferenceData
- Check if the model id matches the id in the InferenceData loaded.

Parameters
----------
fname : string
Expand Down Expand Up @@ -521,11 +548,7 @@ def load(cls, fname: str):
model = cls(**init_kwargs)

model.idata = idata
dataset = idata.fit_data.to_dataframe()
X = dataset.drop(columns=[model.output_var])
y = dataset[model.output_var]
model.build_model(X, y)
# All previously used data is in idata.
model.build_from_idata(idata)

if model.id != idata.attrs["id"]:
error_msg = (
Expand Down
Loading