Serialization

Model persistence: MMMSerializer save/load for core and extended models.

Model serialization utilities for BayesianMMM.

This module provides functions to save and load BayesianMMM models, separating the serialization logic from the main model class.

class mmm_framework.serialization.MMMSerializer[source]

Bases: object

Handles save/load operations for BayesianMMM models.

This class encapsulates all serialization logic, keeping the main BayesianMMM class focused on modeling.

Examples

>>> # Save a model
>>> MMMSerializer.save(model, "models/my_mmm")
>>> # Load a model
>>> model = MMMSerializer.load("models/my_mmm", panel)
classmethod save(model, path, save_trace=True, compress=True)[source]

Save a BayesianMMM model to disk.

Return type:

None

Parameters

modelBayesianMMM

The model instance to save.

pathstr or Path

Directory path where the model will be saved.

save_tracebool, default True

Whether to save the fitted trace. Set to False for a smaller save file if you only need configurations.

compressbool, default True

Whether to compress the trace file with gzip.

Raises

ValueError

If the model has no trace and save_trace is True.

classmethod load(path, panel=None, rebuild_model=True)[source]

Load a saved model from disk.

Return type:

BayesianMMM

Parameters

pathstr or Path

Directory path where the model was saved.

panelPanelDataset | None

Panel data to use with the loaded model. Must be compatible with the original data (same channels, controls, dimensions). REQUIRED for core (BayesianMMM-family) saves; ignored for extended-flavor saves (BaseExtendedMMM models carry their arrays in the pickle and need no panel).

rebuild_modelbool, default True

Whether to rebuild the PyMC model. Set to False if you only need access to the trace and don’t need to make predictions.

Returns

BayesianMMM

Loaded model instance with fitted trace (if available).

Raises

ValueError

If the panel data is incompatible with the saved model.

FileNotFoundError

If the model files are not found.

classmethod save_trace_only(trace, path)[source]

Save only a trace to a file.

Return type:

None

Parameters

traceaz.InferenceData

The trace to save.

pathstr or Path

File path for the trace (should end in .nc or .nc.gz).

classmethod load_trace_only(path)[source]

Load a trace from a file.

Return type:

InferenceData

Parameters

pathstr or Path

File path to the trace (.nc or .nc.gz).

Returns

az.InferenceData

The loaded trace.