Base (base.py)¶
This module defines the BaseMMM class, which serves as the foundational abstract base class for all Marketing Mix Models within the ABACUS library. It integrates functionalities from various mixins and the ModelBuilder.
BaseMMM¶
The core base class for MMMs, providing fundamental structure and integrating functionalities for model building, validation, preprocessing, fitting, prediction, and accessing results. It inherits from ModelBuilder and several mixins.
class BaseMMM(
bd.ModelBuilder,
PredictivePlottingMixin,
ContributionPlottingMixin,
ParameterPlottingMixin,
ScenarioPlottingMixin,
ContributionMixin,
OptimizationMixin,
DiagnosticsMixin,
):
"""Base class for MMM (Marketing Mix Modelling) models."""
# ... attributes and methods ...
Inheritance:
abacus.core.build.ModelBuilder: Provides the corebuild_model,fit,predict,save,loadmethods.abacus.core.mixins.plotting_predictive.PredictivePlottingMixin: Adds methods for plotting predictive checks.abacus.core.mixins.plotting_contribution.ContributionPlottingMixin: Adds methods for plotting channel contributions.abacus.core.mixins.plotting_parameter.ParameterPlottingMixin: Adds methods for plotting model parameters.abacus.core.mixins.plotting_scenario.ScenarioPlottingMixin: Adds methods for plotting scenario analyses (e.g., response curves, budget scenarios).abacus.core.mixins.contribution.ContributionMixin: Adds methods for computing channel contributions.abacus.core.mixins.optimization.OptimizationMixin: Adds methods for budget optimization.abacus.core.mixins.diagnostics.DiagnosticsMixin: Adds methods for model diagnostics.
Initialization¶
def __init__(
self,
date_column: str,
channel_columns: Union[List[str], Tuple[str, ...]],
model_config: Optional[Dict],
sampler_config: Optional[Dict],
**kwargs: Any,
) -> None:
Initialises the BaseMMM object. Stores configuration and basic information about the data structure.
Parameters:
date_column(str): The name of the column representing the date or time period.channel_columns(Union[List[str], Tuple[str, ...]]): A list or tuple of column names representing the media channels.model_config(Optional[Dict]): Configuration dictionary for the PyMC model structure.sampler_config(Optional[Dict]): Configuration dictionary for the PyMC sampler.**kwargs: Additional keyword arguments passed up the inheritance chain (potentially toModelBuilder).
Attributes Initialised:
date_column(str): Name of the date column.channel_columns(Union[List[str], Tuple[str, ...]]): List/tuple of channel column names.n_channel(int): Number of media channels.model(Optional[pm.Model]): Placeholder for the PyMC model object (built later).idata(Optional[az.InferenceData]): Placeholder for the ArviZ InferenceData object containing fit results.X,y: Placeholders for feature and target data (set during fitting).preprocessed_data: Placeholder for preprocessed data dictionary.target_transformer: Placeholder for the target variable transformer pipeline._fit_result,_posterior_predictive: Internal placeholders for results (useidataproperties instead).
Properties¶
methods¶
@property
def methods(self) -> List[Any]:
Returns a list of all callable methods (excluding dunder methods and descriptors) of the BaseMMM instance, including inherited methods from mixins.
validation_methods¶
@property
def validation_methods(self) -> Tuple[List[Callable], List[Callable]]:
Identifies and returns methods tagged for data validation. Methods are tagged via a _tags attribute (e.g., _tags={"validation_X": True}).
Returns:
Tuple[List[Callable], List[Callable]]: A tuple containing two lists:Methods tagged for feature (
X) validation.Methods tagged for target (
y) validation.
preprocessing_methods¶
@property
def preprocessing_methods(self) -> Tuple[List[Callable], List[Callable]]:
Identifies and returns methods tagged for data preprocessing. Methods are tagged via a _tags attribute (e.g., _tags={"preprocessing_y": True}).
Returns:
Tuple[List[Callable], List[Callable]]: A tuple containing two lists:Methods tagged for feature (
X) preprocessing.Methods tagged for target (
y) preprocessing.
prior¶
@property
def prior(self) -> xr.Dataset:
Returns the prior samples from the fitted model’s InferenceData. Raises RuntimeError if accessed before sample_prior_predictive is called with extend_idata=True.
prior_predictive¶
@property
def prior_predictive(self) -> az.InferenceData:
Returns the prior predictive samples from the fitted model’s InferenceData. Raises RuntimeError if accessed before fitting or sampling prior predictive.
fit_result¶
@property
def fit_result(self) -> xr.Dataset:
Returns the posterior samples (the main fitting result) from the model’s InferenceData. Raises RuntimeError if accessed before fitting.
posterior_predictive¶
@property
def posterior_predictive(self) -> xr.Dataset:
Returns the posterior predictive samples from the fitted model’s InferenceData. Raises RuntimeError if accessed before fitting.
Instance Methods¶
validate¶
def validate(
self,
target: Literal["X", "y"],
data: Union[pd.DataFrame, pd.Series, np.ndarray]
) -> None:
Applies all registered validation methods (identified by validation_methods) for the specified target ("X" or "y") to the provided data.
preprocess¶
def preprocess(
self,
target: str,
data: Union[pd.DataFrame, pd.Series, np.ndarray]
) -> Union[pd.DataFrame, pd.Series, np.ndarray]:
Applies all registered preprocessing methods (identified by preprocessing_methods) for the specified target ("X" or "y") sequentially to the provided data. Returns the processed data.
get_target_transformer¶
def get_target_transformer(self) -> skpip.Pipeline:
Returns the scikit-learn compatible pipeline used for transforming the target variable. If no specific transformer was set during preprocessing, it returns a pipeline containing only an identity function.
_get_distribution¶
def _get_distribution(self, dist: Dict[str, Any]) -> Callable:
Internal helper method to retrieve a PyMC distribution function (e.g., pm.Normal, pm.HalfNormal) based on a name provided in a dictionary (e.g., {'dist': 'Normal'}).
graphviz¶
def graphviz(self, **kwargs: Any) -> gz.Digraph:
Generates a graphviz.Digraph object representing the structure of the built PyMC model. Requires the model to be built first.
Note: Core methods like build_model, fit, predict, save, load, as well as various plotting, contribution calculation, optimization, and diagnostic methods are inherited from ModelBuilder and the various Mixin classes. Refer to their respective documentation for details.