View source on GitHub
|
Contains the main functionality for fitting the Meridian MMM model.
meridian.model.model.Meridian(
input_data: meridian.data.input_data.InputData,
model_spec: (meridian.model.spec.ModelSpec | None) = None,
inference_data: (az.InferenceData | None) = None,
eda_spec: meridian.model.eda.eda_spec.EDASpec = eda_spec_module.EDASpec(),
health_summary: (meridian.analysis.review.results.ReviewSummary | None) = None
)
Attributes | |
|---|---|
input_data
|
An InputData object containing the input data for the model.
|
model_spec
|
A ModelSpec object containing the model specification.
|
model_context
|
A ModelContext object containing the model context.
|
model_equations
|
A ModelEquations object containing stateless mathematical
functions and utilities for Meridian MMM.
|
inference_data
|
A mutable arviz.InferenceData object containing the
resulting data from fitting the model.
|
eda_engine
|
An EDAEngine object containing the EDA engine.
|
eda_spec
|
An EDASpec object containing the EDA specification.
|
eda_outcomes
|
A list of EDAOutcome objects containing the outcomes from
running critical EDA checks.
|
health_summary
|
A ReviewSummary object containing the results of the model
health checks, or None if review() has not been called.
|
n_geos
|
Number of geos in the data. |
n_media_channels
|
Number of media channels in the data. |
n_rf_channels
|
Number of reach and frequency (RF) channels in the data. |
n_organic_media_channels
|
Number of organic media channels in the data. |
n_organic_rf_channels
|
Number of organic reach and frequency (RF) channels in the data. |
n_controls
|
Number of control variables in the data. |
n_non_media_channels
|
Number of non-media treatment channels in the data. |
n_times
|
Number of time periods in the KPI or spend data. |
n_media_times
|
Number of time periods in the media data. |
is_national
|
A boolean indicating whether the data is national (single geo) or not (multiple geos). |
knot_info
|
A KnotInfo derived from input data and model spec.
|
kpi
|
A tensor constructed from input_data.kpi.
|
revenue_per_kpi
|
A tensor constructed from input_data.revenue_per_kpi. If
input_data.revenue_per_kpi is None, then this is also None.
|
controls
|
A tensor constructed from input_data.controls.
|
non_media_treatments
|
A tensor constructed from
input_data.non_media_treatments.
|
population
|
A tensor constructed from input_data.population.
|
media_tensors
|
A collection of media tensors derived from input_data.
|
rf_tensors
|
A collection of Reach & Frequency (RF) media tensors. |
organic_media_tensors
|
A collection of organic media tensors. |
organic_rf_tensors
|
A collection of organic Reach & Frequency (RF) media tensors. |
total_spend
|
A tensor containing total spend, including
media_tensors.media_spend and rf_tensors.rf_spend.
|
total_outcome
|
A tensor containing the total outcome, aggregated over geos and times. |
controls_transformer
|
A ControlsTransformer to scale controls tensors
using the model's controls data.
|
non_media_transformer
|
A CenteringAndScalingTransformer to scale non-media
treatmenttensors using the model's non-media treatment data.
|
kpi_transformer
|
A KpiTransformer to scale KPI tensors using the model's
KPI data.
|
controls_scaled
|
The controls tensor after pre-modeling transformations
including population scaling (for variables with
ModelSpec.control_population_scaling_id set to True), centering by the
mean, and scaling by the standard deviation.
|
non_media_treatments_scaled
|
The non-media treatment tensor after
pre-modeling transformations including population scaling (for variables
with ModelSpec.non_media_population_scaling_id set to True), centering
by the mean, and scaling by the standard deviation.
|
kpi_scaled
|
The KPI tensor after pre-modeling transformations including population scaling, centering by the mean, and scaling by the standard deviation. |
media_effects_dist
|
A string to specify the distribution of media random effects across geos. |
unique_sigma_for_each_geo
|
A boolean indicating whether to use a unique residual variance for each geo. |
prior_broadcast
|
A PriorDistribution object containing broadcasted
distributions.
|
baseline_geo_idx
|
The index of the baseline geo. |
holdout_id
|
A tensor containing the holdout id, if present. |
adstock_decay_spec
|
Returns AdstockDecaySpec object with correctly mapped channels.
|
computation_backend
|
The name of the computational backend used to initialize this model. |
computation_precision
|
The computation precision used to train the model. |
non_media_treatments_normalized
|
Normalized non-media treatments.
The non-media treatments values are scaled by population (for channels where
|
posterior_sampler_callable
|
A PosteriorMCMCSampler callable bound to this model.
|
prior_sampler_callable
|
A PriorDistributionSampler callable bound to this model.
|
Methods
adstock_hill_media
adstock_hill_media(
media: meridian.backend.Tensor,
alpha: meridian.backend.Tensor,
ec: meridian.backend.Tensor,
slope: meridian.backend.Tensor,
decay_functions: (str | Sequence[str]) = constants.GEOMETRIC_DECAY,
n_times_output: (int | None) = None
) -> meridian.backend.Tensor
Transforms media using Adstock and Hill functions in the desired order.
| Args | |
|---|---|
media
|
Tensor of dimensions (n_geos, n_media_times, n_channels)
containing non-negative media execution values, where n_channels is
the number of paid or organic media channels (n_media_channels or
n_organic_media_channels). Typically this is impressions, but it can
be any metric, such as media_spend. Clicks are often used for paid
search ads.
|
alpha
|
Tensor of Adstock decay parameters with dimensions [...,
n_channels].
|
ec
|
Tensor of Hill half-saturation parameters with dimensions [...,
n_channels].
|
slope
|
Tensor of Hill slope parameters with dimensions [...,
n_channels].
|
decay_functions
|
String or sequence of strings denoting the adstock decay function(s) for each channel. Default: 'geometric'. |
n_times_output
|
Number of time periods to output. This argument is
optional when the number of time periods in media equals
self.n_media_times, in which case n_times_output defaults to
self.n_times.
|
| Returns | |
|---|---|
Tensor with dimensions [..., n_geos, n_times, n_channels]
representing Adstock and Hill-transformed media.
|
adstock_hill_rf
adstock_hill_rf(
reach: meridian.backend.Tensor,
frequency: meridian.backend.Tensor,
alpha: meridian.backend.Tensor,
ec: meridian.backend.Tensor,
slope: meridian.backend.Tensor,
decay_functions: (str | Sequence[str]) = constants.GEOMETRIC_DECAY,
n_times_output: (int | None) = None
) -> meridian.backend.Tensor
Transforms reach and frequency (RF) using Hill and Adstock functions.
| Args | |
|---|---|
reach
|
Tensor of dimensions (n_geos, n_media_times, n_channels)
containing non-negative media for reach, where n_channels is the
number of paid or organic RF channels (n_rf_channels or
n_organic_rf_channels).
|
frequency
|
Tensor of dimensions (n_geos, n_media_times, n_channels)
containing non-negative media for frequency.
|
alpha
|
Tensor of Adstock decay parameters with dimensions [...,
n_channels].
|
ec
|
Tensor of Hill half-saturation parameters with dimensions [...,
n_channels].
|
slope
|
Tensor of Hill slope parameters with dimensions [...,
n_channels].
|
decay_functions
|
String or sequence of strings denoting the adstock decay function(s) for each channel. Default: 'geometric'. |
n_times_output
|
Number of time periods to output. This argument is
optional when the number of time periods in reach equals
self.n_media_times, in which case n_times_output defaults to
self.n_times.
|
| Returns | |
|---|---|
Tensor with dimensions [..., n_geos, n_times, n_channels]
representing Hill and Adstock-transformed RF.
|
calculate_beta_x
calculate_beta_x(
is_non_media: bool,
incremental_outcome_x: meridian.backend.Tensor,
linear_predictor_counterfactual_difference: meridian.backend.Tensor,
eta_x: meridian.backend.Tensor,
beta_gx_dev: meridian.backend.Tensor
) -> meridian.backend.Tensor
Calculates coefficient mean parameter for any treatment variable type.
The "beta_x" in the function name refers to the coefficient mean parameter of any treatment variable. The "x" can represent "m", "rf", "om", or "orf". This function can also be used to calculate "gamma_n" for any non-media treatments.
| Args | |
|---|---|
is_non_media
|
Boolean indicating whether the treatment variable is a
non-media treatment. This argument is used to determine whether the
coefficient random effects are normal or log-normal. If True, then
random effects are assumed to be normal. Otherwise, the distribution is
inferred from self.media_effects_dist.
|
incremental_outcome_x
|
The incremental outcome of the treatment variable, which depends on the parameter values of a particular prior or posterior draw. The "_x" indicates that this is a tensor with length equal to the dimension of the treatment variable. |
linear_predictor_counterfactual_difference
|
The difference between the treatment variable and its counterfactual on the linear predictor scale. "Linear predictor" refers to the quantity that is multiplied by the geo-level coefficient. For media variables, this is the output of the hill/adstock transformation function. For non-media treatments, this is simply the treatment variable after centering/scaling transformations. This tensor has dimensions for geo, time, and channel. |
eta_x
|
The random effect standard deviation parameter values. For media
variables, the "x" represents "m", "rf", "om", or "orf". For non-media
treatments, this argument should be set to xi_n, which is analogous to
"eta".
|
beta_gx_dev
|
The latent standard normal parameter values of the geo-level
coefficients. For media variables, the "x" represents "m", "rf", "om",
or "orf". For non-media treatments, this argument should be set to
gamma_gn_dev, which is analogous to "beta_gx_dev".
|
| Returns | |
|---|---|
| The coefficient mean parameter of the treatment variable, which has dimension equal to the number of treatment channels. |
compute_non_media_treatments_baseline
compute_non_media_treatments_baseline(
non_media_baseline_values: (Sequence[str | float] | None) = None
) -> meridian.backend.Tensor
Computes the baseline for each non-media treatment channel.
| Args | |
|---|---|
non_media_baseline_values
|
Optional list of shape
(n_non_media_channels,). Each element is either a float (which means
that the fixed value will be used as baseline for the given channel) or
one of the strings "min" or "max" (which mean that the global minimum or
maximum value will be used as baseline for the values of the given
non_media treatment channel). If float values are provided, it is
expected that they are scaled by population for the channels where
model_spec.non_media_population_scaling_id is True. If None, the
model_spec.non_media_baseline_values is used, which defaults to the
minimum value for each non_media treatment channel.
|
| Returns | |
|---|---|
A tensor of shape (n_non_media_channels,) containing the
baseline values for each non-media treatment channel.
|
create_inference_data_coords
create_inference_data_coords(
n_chains: int, n_draws: int
) -> Mapping[str, np.ndarray | Sequence[str]]
Creates data coordinates for inference data.
create_inference_data_dims
create_inference_data_dims() -> Mapping[str, Sequence[str]]
expand_selected_time_dims
expand_selected_time_dims(
start_date: meridian.data.time_coordinates.Date = None,
end_date: meridian.data.time_coordinates.Date = None
) -> (list[str] | None)
Validates and returns time dimension values based on the selected times.
If both start_date and end_date are None, returns None. If specified,
both start_date and end_date are inclusive, and must be present in the
time coordinates of the input data.
| Args | |
|---|---|
start_date
|
Start date of the selected time period. If None, implies the earliest time dimension value in the input data. |
end_date
|
End date of the selected time period. If None, implies the latest time dimension value in the input data. |
| Returns | |
|---|---|
A list of time dimension values (as Meridian-formatted strings) in the
input data within the selected time period, or do nothing and pass through
None if both arguments are Nones, or if start_date and end_date
correspond to the entire time range in the input data.
|
| Raises | |
|---|---|
ValueError if start_date or end_date is not in the input data time
dimensions.
|
linear_predictor_counterfactual_difference_media
linear_predictor_counterfactual_difference_media(
media_transformed: meridian.backend.Tensor,
alpha_m: meridian.backend.Tensor,
ec_m: meridian.backend.Tensor,
slope_m: meridian.backend.Tensor
) -> meridian.backend.Tensor
Calculates linear predictor counterfactual difference for non-RF media.
For non-RF media variables (paid or organic), this function calculates the linear predictor difference between the treatment variable and its counterfactual. "Linear predictor" refers to the output of the hill/adstock function, which is multiplied by the geo-level coefficient.
This function does the calculation efficiently by only calling the hill/adstock function if the prior counterfactual is not all zeros.
| Args | |
|---|---|
media_transformed
|
The output of the hill/adstock function for actual historical media data. |
alpha_m
|
The adstock alpha parameter values. |
ec_m
|
The Hill ec parameter values. |
slope_m
|
The Hill slope parameter values. |
| Returns | |
|---|---|
| The linear predictor difference between the treatment variable and its counterfactual. |
linear_predictor_counterfactual_difference_rf
linear_predictor_counterfactual_difference_rf(
rf_transformed: meridian.backend.Tensor,
alpha_rf: meridian.backend.Tensor,
ec_rf: meridian.backend.Tensor,
slope_rf: meridian.backend.Tensor
) -> meridian.backend.Tensor
Calculates linear predictor counterfactual difference for RF media.
For RF media variables (paid or organic), this function calculates the linear predictor difference between the treatment variable and its counterfactual. "Linear predictor" refers to the output of the hill/adstock function, which is multiplied by the geo-level coefficient.
This function does the calculation efficiently by only calling the hill/adstock function if the prior counterfactual is not all zeros.
| Args | |
|---|---|
rf_transformed
|
The output of the hill/adstock function for actual historical media data. |
alpha_rf
|
The adstock alpha parameter values. |
ec_rf
|
The Hill ec parameter values. |
slope_rf
|
The Hill slope parameter values. |
| Returns | |
|---|---|
| The linear predictor difference between the treatment variable and its counterfactual. |
posterior_thinning
posterior_thinning(
sampling_rate: (float | None) = None,
n_draws: (int | None) = None,
method: ThinningMethod = ThinningMethod.SYSTEMATIC,
seed: (int | Sequence[int] | None) = None,
preserve_original: bool = True
) -> xr.Dataset
Thins inference_data.posterior while preserving chains.
This method replaces self.inference_data.posterior with a chain-preserving
subset of posterior draws. For example, a posterior with shape
chain=10, draw=1000 and sampling_rate=0.1 becomes
chain=10, draw=100.
The main use case is accelerating posterior workflows such as budget optimization while continuing to use Meridian's existing APIs unchanged. Outputs produced after thinning are approximate with respect to the full posterior.
Systematic sampling selects posterior samples from each MCMC chain at a fixed, regular interval (such as every 10th sample) starting from a randomly chosen point. This is done to minimize the auto-correlation of the sample.
| Args | |
|---|---|
sampling_rate
|
Fraction of draws to keep per chain. Must be in (0, 1].
Exactly one of sampling_rate or n_draws must be provided.
|
n_draws
|
Number of draws to keep per chain. Must be in [1,
original_n_draws]. Exactly one of sampling_rate or n_draws must be
provided.
|
method
|
Draw selection method. Currently only
ThinningMethod.SYSTEMATIC is supported.
|
seed
|
Optional random seed for reproducible draw selection. This is used only for selecting posterior draw indices. |
preserve_original
|
If True, stores a copy of the full posterior on this
model so restore_full_posterior() can restore it.
|
| Returns | |
|---|---|
The thinned posterior xarray.Dataset.
|
| Raises | |
|---|---|
NotFittedModelError
|
If the model does not have posterior samples. |
ValueError
|
If arguments are invalid. |
restore_full_posterior
restore_full_posterior() -> xr.Dataset
Restores the full posterior saved by posterior_thinning().
review
review(
*,
convergence_check_config: (meridian.analysis.review.configs.ConvergenceConfig | None) = None,
post_convergence_checks: (reviewer.ChecksBattery | None) = None
) -> meridian.analysis.review.results.ReviewSummary
Runs the model health checks and stores the results in health_summary.
This method should be called after the model has been fitted, i.e., after
sample_posterior has been executed to populate self.inference_data.
| Args | |
|---|---|
convergence_check_config
|
Optional configuration for the convergence check. |
post_convergence_checks
|
Optional battery of post-convergence checks to run. |
| Returns | |
|---|---|
A ReviewSummary object containing the results of the health checks.
|
sample_posterior
sample_posterior(
n_chains: (Sequence[int] | int),
n_adapt: int,
n_burnin: int,
n_keep: int,
current_state: (Mapping[str, backend.Tensor] | None) = None,
init_step_size: (int | None) = None,
dual_averaging_kwargs: (Mapping[str, int] | None) = None,
max_tree_depth: int = 10,
max_energy_diff: float = 500.0,
unrolled_leapfrog_steps: int = 1,
parallel_iterations: int = 10,
seed: (Sequence[int] | int | None) = None,
reconstruction_batch_size: int = constants.DEFAULT_RECONSTRUCTION_BATCH_SIZE,
*,
progress_callback: (meridian.model.progress.PosteriorProgressCallback | None) = None,
**pins
)
Runs Markov Chain Monte Carlo (MCMC) sampling of posterior distributions.
For more information about the arguments, see windowed_adaptive_nuts.
Drawn samples are merged into this model's Arviz inference_data property.
| Args | |
|---|---|
n_chains
|
Number of MCMC chains. Given a sequence of integers,
windowed_adaptive_nuts will be called once for each element. The
n_chains argument of each windowed_adaptive_nuts call will be equal
to the respective integer element. Using a list of integers, one can
split the chains of a windowed_adaptive_nuts call into multiple calls
with fewer chains per call. This can reduce memory usage. This might
require an increased number of adaptation steps for convergence, as the
optimization is occurring across fewer chains per sampling call.
|
n_adapt
|
Number of adaptation draws per chain. |
n_burnin
|
Number of burn-in draws per chain. Burn-in draws occur after adaptation draws and before the kept draws. |
n_keep
|
Integer number of draws per chain to keep for inference. |
current_state
|
Optional structure of tensors at which to initialize
sampling. Use the same shape and structure as
model.experimental_pin(**pins).sample(n_chains).
|
init_step_size
|
Optional integer determining where to initialize the step
size for the leapfrog integrator. The structure must broadcast with
current_state. For example, if the initial state is: { 'a':
tf.zeros(n_chains), 'b': tf.zeros([n_chains, n_features]), } then
any of 1., {'a': 1., 'b': 1.}, or {'a': tf.ones(n_chains), 'b':
tf.ones([n_chains, n_features])} will work. Defaults to the dimension
of the log density to the ¼ power.
|
dual_averaging_kwargs
|
Optional dict keyword arguments to pass to
tfp.mcmc.DualAveragingStepSizeAdaptation. By default, a
target_accept_prob of 0.85 is set, acceptance probabilities across
chains are reduced using a harmonic mean, and the class defaults are
used otherwise.
|
max_tree_depth
|
Maximum depth of the tree implicitly built by NUTS. The
maximum number of leapfrog steps is bounded by 2**max_tree_depth, for
example, the number of nodes in a binary tree max_tree_depth nodes
deep. The default setting of 10 takes up to 1024 leapfrog steps.
|
max_energy_diff
|
Scalar threshold of energy differences at each leapfrog,
divergence samples are defined as leapfrog steps that exceed this
threshold. Default is 1000.
|
unrolled_leapfrog_steps
|
The number of leapfrogs to unroll per tree
expansion step. Applies a direct linear multiplier to the maximum
trajectory length implied by max_tree_depth. Defaults is 1.
|
parallel_iterations
|
Number of iterations allowed to run in parallel. Must
be a positive integer. For more information, see tf.while_loop.
|
seed
|
An int32[2] Tensor or a Python list or tuple of 2 ints, which
will be treated as stateless seeds; or a Python int or None, which
will be treated as stateful seeds. See tfp.random.sanitize_seed.
|
reconstruction_batch_size
|
Maximum number of combined chain-and-draw samples to reconstruct in a single forward pass. Limits device OOMs caused by wide vectorized models. |
progress_callback
|
Optional callable that receives a
progress.PosteriorSamplingProgress snapshot each time sampling
advances: when a chain batch starts, after every MCMC draw on the JAX
backend, when a chain batch finishes, and after each batch of the
posterior reconstruction. The callback must be fast and may run on a
different thread than the caller. Exceptions it raises are reported as
warnings and don't interrupt sampling. On the JAX backend, reporting
every draw holds the latent adaptation draws in device memory until
the chain batch finishes, which raises the latent draw-buffer memory
of a chain batch by n_adapt / (n_burnin + n_keep). To display
progress bars, pass progress.TqdmProgressBar().
|
**pins
|
These are used to condition the provided joint distribution, and
are passed directly to joint_dist.experimental_pin(**pins).
|
| Throws | |
|---|---|
MCMCOOMError
|
If the model is out of memory. Try reducing n_keep, pass
a list of integers as n_chains to sample chains serially, or lower
reconstruction_batch_size to reduce forward pass memory footprint.
For more information, see
ResourceExhaustedError when running Meridian.sample_posterior.
|
sample_posterior_and_review
sample_posterior_and_review(
*,
n_chains: (Sequence[int] | int),
n_adapt: int,
n_burnin: int,
n_keep: int,
current_state: (Mapping[str, backend.Tensor] | None) = None,
init_step_size: (int | None) = None,
dual_averaging_kwargs: (Mapping[str, int] | None) = None,
max_tree_depth: int = 10,
max_energy_diff: float = 500.0,
unrolled_leapfrog_steps: int = 1,
parallel_iterations: int = 10,
seed: (Sequence[int] | int | None) = None,
reconstruction_batch_size: int = constants.DEFAULT_RECONSTRUCTION_BATCH_SIZE,
convergence_check_config: (meridian.analysis.review.configs.ConvergenceConfig | None) = None,
post_convergence_checks: (reviewer.ChecksBattery | None) = None,
progress_callback: (meridian.model.progress.PosteriorProgressCallback | None) = None,
**pins
) -> None
Runs MCMC sampling and then the model health checks.
sample_prior
sample_prior(
n_draws: int,
seed: (int | None) = None,
batch_size: int = constants.DEFAULT_BATCH_SIZE,
*,
progress_callback: (meridian.model.progress.PriorProgressCallback | None) = None
)
Draws samples from the prior distributions.
Drawn samples are merged into this model's Arviz inference_data property.
| Args | |
|---|---|
n_draws
|
Number of samples drawn from the prior distribution. |
seed
|
Used to set the seed for reproducible results. For more information, see PRNGS and seeds. |
batch_size
|
Maximum number of draws to process per batch when computing media/RF transformations and derived parameters. Limits device OOMs caused by wide vectorized models. |
progress_callback
|
Optional callable that receives a
progress.PriorSamplingProgress snapshot each time a sampling stage
(base, media, RF, ...) completes. Exceptions it raises are reported as
warnings and don't interrupt sampling. To display a progress bar, pass
progress.TqdmProgressBar().
|
View source on GitHub