### Initialize environment and imports Source: https://prophetverse.com/latest/tutorials/count_data.html Setup necessary libraries and suppress warnings for the forecasting workflow. ```python # Disable warnings import warnings warnings.simplefilter(action="ignore") import matplotlib.pyplot as plt import numpy as np import pandas as pd from numpyro import distributions as dist from sktime.forecasting.compose import ForecastingPipeline from sktime.transformations.series.fourier import FourierFeatures from prophetverse.datasets.loaders import load_pedestrian_count ``` ```python import numpyro numpyro.enable_x64() ``` -------------------------------- ### Install development dependencies Source: https://prophetverse.com/latest/development.html Use this command to install the necessary dependencies for development after installing Python and Poetry. ```bash poetry install --extras dev ``` -------------------------------- ### Install Prophetverse with Pip Source: https://prophetverse.com/latest Use this command to install the Prophetverse package using pip. ```bash pip install prophetverse ``` -------------------------------- ### Configure and fit Prophetverse with Hurdle Likelihood Source: https://prophetverse.com/latest/tutorials/count_data.html Setup of exogenous effects and model initialization using HurdleTargetLikelihood. ```python from prophetverse.effects.target.hurdle import HurdleTargetLikelihood from prophetverse.effects.constant import Constant import jax.numpy as jnp seasonality = LinearFourierSeasonality( sp_list=[24, 24 * 7, 24 * 365.5], fourier_terms_list=[2, 2, 10], freq="H", prior_scale=1, effect_mode="additive", ) exogenous_effects = [ ( "seasonality", seasonality, no_input_columns, ), ("zero_proba/constant_term", Constant(prior=dist.Normal(0.5, 1)), no_input_columns), ("zero_proba/seasonality", seasonality, no_input_columns), ] model = Prophetverse( trend=FlatTrend(), exogenous_effects=exogenous_effects, inference_engine=MAPInferenceEngine(), likelihood=HurdleTargetLikelihood( likelihood_family="negbinomial", ), ) model.fit(y=y_train) ``` -------------------------------- ### Optimization Output Log Source: https://prophetverse.com/latest/mmm/budget_allocation.html Example output log from a successful optimization run. ```text Optimization terminated successfully (Exit mode 0) Current function value: -754679704.6820625 Iterations: 108 Function evaluations: 125 Gradient evaluations: 104 Optimization completed in 3.38 seconds ``` -------------------------------- ### Prophetverse Model Configuration Example Source: https://prophetverse.com/latest/mmm/proxy_variables.html This snippet shows a detailed configuration of a Prophetverse model, including yearly and weekly seasonality, a latent awareness effect, and inference engine settings. It is useful for understanding the structure of a complex model setup. ```python Prophetverse(exogenous_effects=[('yearly_seasonality', LinearFourierSeasonality(effect_mode='multiplicative', fourier_terms_list=[5], freq='D', prior_scale=0.1, sp_list=[365.25]), None), ('weekly_seasonality', LinearFourierSeasonality(effect_mode='multiplicative', fourier_terms_list=[3], freq='D', prior_scale=0.05, sp_list=[7]), None), ('latent/awareness', HillEf... 2004-05-15 0.842808 2002-11-06 0.076063 2002-12-31 0.079602 2002-03-06 0.744027 ... 2004-10-21 0.351357 2004-05-23 0.813127 2000-05-29 0.914647 2003-06-26 0.040826 2001-03-17 0.791952 [180 rows x 1 columns]), None)], inference_engine=MAPInferenceEngine(num_steps=5000, optimizer=LBFGSSolver(max_linesearch_steps=300, memory_size=300)), trend=PiecewiseLinearTrend(changepoint_interval=300)) ``` -------------------------------- ### Install Prophetverse with Poetry Source: https://prophetverse.com/latest Use this command to add Prophetverse to your project dependencies using Poetry. ```bash poetry add prophetverse ``` -------------------------------- ### Forecasting with Prophetverse Defaults (sktime compatible) Source: https://prophetverse.com/latest Example of initializing, fitting, and forecasting using Prophetverse with its default settings. This interface is compatible with sktime. ```python from prophetverse.sktime import Prophetverse # Create the model model = Prophetverse() # Fit the model model.fit(y=y, X=X) # Forecast in sample y_pred = model.predict(X=X, fh=y.index) ``` -------------------------------- ### Load and Split Synthetic Dataset Source: https://prophetverse.com/latest/howto/composite_effects.html Loads the synthetic example dataset and splits it into training and testing sets using sktime. ```python import numpyro import numpyro.distributions as dist from matplotlib import pyplot as plt from sktime.split import temporal_train_test_split from sktime.utils.plotting import plot_series from prophetverse.datasets.synthetic import load_composite_effect_example numpyro.enable_x64() y, X = load_composite_effect_example() y_train, y_test, X_train, X_test = temporal_train_test_split(y, X, test_size=365) display(y_train.head()) display(X_train.head()) ``` -------------------------------- ### Prophetverse Model Representation Source: https://prophetverse.com/latest/mmm/fitting_and_calibration.html Example output showing the configuration of a Prophetverse model with exogenous effects and inference engine settings. ```python Prophetverse(exogenous_effects=[('yearly_seasonality', LinearFourierSeasonality(effect_mode='multiplicative', fourier_terms_list=[5], freq='D', prior_scale=0.1, sp_list=[365.25]), None), ('weekly_seasonality', LinearFourierSeasonality(effect_mode='multiplicative', fourier_terms_list=[3], freq='D', prior_scale=0.05, sp_list=[7]), None), ('ad_spend_search', LiftExp... 2002-07-03 1.053316 25537.869750 38025.254409 2004-09-27 1.010456 8523.749415 11037.466255 2000-10-25 0.980559 50964.957119 65038.733878 2002-11-02 1.355164 1195.765141 1603.253926, prior_scale=0.05), 'ad_spend_social_media')], inference_engine=MAPInferenceEngine(num_steps=5000, optimizer=LBFGSSolver(max_linesearch_steps=300, memory_size=300)), trend=PiecewiseLinearTrend(changepoint_interval=100)) ``` -------------------------------- ### Import Libraries for Prophetverse Source: https://prophetverse.com/latest/tutorials/hierarchical.html Imports necessary libraries for data manipulation, plotting, and the Prophetverse model. Ensure these are installed before running. ```python import matplotlib.pyplot as plt import numpy as np import pandas as pd from prophetverse.datasets.loaders import load_tourism ``` -------------------------------- ### Training Progress Bar Output Source: https://prophetverse.com/latest/tutorials/univariate.html Example output from a Prophetverse model training progress bar, showing iteration count, loss, and progress percentage. ```text 0 [00:26<00:03, 3536.70it/s, init loss: 22917835223.3965, avg. loss [80001-85000]: -2397.8516] 89%|████████▉ | 89112/100000 [00:26<00:03, 3614.81it/s, init loss: 22917835223.3965, avg. loss [80001-85000]: -2397.8516] 89%|████████▉ | 89474/100000 [00:26<00:02, 3540.74it/s, init loss: 22917835223.3965, avg. loss [80001-85000]: -2397.8516] 90%|████████▉ | 89829/100000 [00:26<00:02, 3505.35it/s, init loss: 22917835223.3965, avg. loss [80001-85000]: -2397.8516] 90%|█████████ | 90191/100000 [00:26<00:02, 3538.49it/s, init loss: 22917835223.3965, avg. loss [85001-90000]: -2841.6718] 91%|█████████ | 90546/100000 [00:26<00:02, 3487.48it/s, init loss: 22917835223.3965, avg. loss [85001-90000]: -2841.6718] 91%|█████████ | 90896/100000 [00:26<00:02, 3472.88it/s, init loss: 22917835223.3965, avg. loss [85001-90000]: -2841.6718] 91%|█████████▏| 91257/100000 [00:26<00:02, 3510.56it/s, init loss: 22917835223.3965, avg. loss [85001-90000]: -2841.6718] 92%|█████████▏| 91635/100000 [00:26<00:02, 3590.16it/s, init loss: 22917835223.3965, avg. loss [85001-90000]: -2841.6718] 92%|█████████▏| 91995/100000 [00:26<00:02, 3544.38it/s, init loss: 22917835223.3965, avg. loss [85001-90000]: -2841.6718] 92%|█████████▏| 92350/100000 [00:27<00:02, 3465.42it/s, init loss: 22917835223.3965, avg. loss [85001-90000]: -2841.6718] 93%|█████████▎| 92734/100000 [00:27<00:02, 3573.59it/s, init loss: 22917835223.3965, avg. loss [85001-90000]: -2841.6718] 93%|█████████▎| 93092/100000 [00:27<00:01, 3486.60it/s, init loss: 22917835223.3965, avg. loss [85001-90000]: -2841.6718] 93%|█████████▎| 93442/100000 [00:27<00:01, 3445.57it/s, init loss: 22917835223.3965, avg. loss [85001-90000]: -2841.6718] 94%|█████████▍| 93820/100000 [00:27<00:01, 3541.92it/s, init loss: 22917835223.3965, avg. loss [85001-90000]: -2841.6718] 94%|█████████▍| 94177/100000 [00:27<00:01, 3547.47it/s, init loss: 22917835223.3965, avg. loss [85001-90000]: -2841.6718] 95%|█████████▍| 94533/100000 [00:27<00:01, 3534.98it/s, init loss: 22917835223.3965, avg. loss [85001-90000]: -2841.6718] 95%|█████████▍| 94887/100000 [00:27<00:01, 3535.88it/s, init loss: 22917835223.3965, avg. loss [85001-90000]: -2841.6718] 95%|█████████▌| 95241/100000 [00:27<00:01, 3462.69it/s, init loss: 22917835223.3965, avg. loss [90001-95000]: -3190.8188] 96%|█████████▌| 95588/100000 [00:28<00:01, 3412.70it/s, init loss: 22917835223.3965, avg. loss [90001-95000]: -3190.8188] 96%|█████████▌| 95947/100000 [00:28<00:01, 3462.49it/s, init loss: 22917835223.3965, avg. loss [90001-95000]: -3190.8188] 96%|█████████▋| 96294/100000 [00:28<00:01, 3412.54it/s, init loss: 22917835223.3965, avg. loss [90001-95000]: -3190.8188] 97%|█████████▋| 96640/100000 [00:28<00:00, 3426.26it/s, init loss: 22917835223.3965, avg. loss [90001-95000]: -3190.8188] 97%|█████████▋| 96996/100000 [00:28<00:00, 3465.22it/s, init loss: 22917835223.3965, avg. loss [90001-95000]: -3190.8188] 97%|█████████▋| 97343/100000 [00:28<00:00, 3450.32it/s, init loss: 22917835223.3965, avg. loss [90001-95000]: -3190.8188] 98%|█████████▊| 97702/100000 [00:28<00:00, 3491.22it/s, init loss: 22917835223.3965, avg. loss [90001-95000]: -3190.8188] 98%|█████████▊| 98085/100000 [00:28<00:00, 3589.82it/s, init loss: 22917835223.3965, avg. loss [90001-95000]: -3190.8188] 98%|█████████▊| 98448/100000 [00:28<00:00, 3601.51it/s, init loss: 22917835223.3965, avg. loss [90001-95000]: -3190.8188] 99%|█████████▉| 98831/100000 [00:28<00:00, 3668.79it/s, init loss: 22917835223.3965, avg. loss [90001-95000]: -3190.8188] 99%|█████████▉| 99199/100000 [00:29<00:00, 3596.15it/s, init loss: 22917835223.3965, avg. loss [90001-95000]: -3190.8188]100%|█████████▉| 99560/100000 [00:29<00:00, 3499.23it/s, init loss: 22917835223.3965, avg. loss [90001-95000]: -3190.8188]100%|█████████▉| 99911/100000 [00:29<00:00, 3439.85it/s, init loss: 22917835223.3965, avg. loss [90001-95000]: -3190.8188]100%|██████████| 100000/100000 [00:29<00:00, 3417.23it/s, init loss: 22917835223.3965, avg. loss [95001-100000]: -3381.6672] ``` -------------------------------- ### Get Component Samples with Prophetverse Source: https://prophetverse.com/latest/mmm/getting_familiar.html Use `predict_component_samples` to obtain all samples for computing probabilistic intervals and measuring risk. Requires `fh` and `X` to be defined. ```python samples = model.predict_component_samples(fh=fh, X=X) samples ``` -------------------------------- ### Prophetverse Model Configuration Source: https://prophetverse.com/latest/tutorials/univariate.html Displays the configuration of a Prophetverse model, including its exogenous effects, inference engine, and trend settings. This is useful for verifying model setup. ```python Prophetverse(exogenous_effects=[('seasonality', LinearFourierSeasonality(effect_mode='multiplicative', fourier_terms_list=[3, 10], freq='D', prior_scale=0.1, sp_list=[7, 365.25]), '^$')], inference_engine=MCMCInferenceEngine(num_warmup=1000), trend=PiecewiseLinearTrend(changepoint_interval=500, changepoint_prior_scale=1e-05, changepoint_range=-500)) ``` -------------------------------- ### Initialize Environment and Libraries Source: https://prophetverse.com/latest/mmm/fitting_and_calibration.html Sets up the necessary libraries, enables float64 precision for numerical stability, and configures the plotting style. ```python import numpy as np import pandas as pd import matplotlib.pyplot as plt import numpyro import numpyro.distributions as dist plt.style.use("seaborn-v0_8-whitegrid") numpyro.enable_x64() ``` -------------------------------- ### Initialize Environment Source: https://prophetverse.com/latest/mmm/budget_allocation.html Configure the environment for optimization by enabling X64 precision and setting the plotting style. ```python import numpyro numpyro.enable_x64() import matplotlib.pyplot as plt import matplotlib.dates as mdates import pandas as pd plt.style.use("seaborn-v0_8-whitegrid") ``` -------------------------------- ### Configure Budget Optimizer Source: https://prophetverse.com/latest/mmm/budget_allocation.html Initialize the BudgetOptimizer with a KPI maximization objective and total budget constraints. ```python from prophetverse.budget_optimization import ( BudgetOptimizer, TotalBudgetConstraint, MaximizeKPI, ) budget_optimizer = BudgetOptimizer( objective=MaximizeKPI(), constraints=[TotalBudgetConstraint()], options={"disp": True, "maxiter":1000}, ) ``` -------------------------------- ### GET get_changepoint_matrix Source: https://prophetverse.com/latest/reference/PiecewiseLinearTrend.html Retrieves the changepoint matrix for a specified index. ```APIDOC ## get_changepoint_matrix ### Description Return the changepoint matrix for the given index. ### Parameters #### Path Parameters - **idx** (pd.PeriodIndex) - Required - The index for which to compute the changepoint matrix. ### Response - **jnp.ndarray** - The changepoint matrix. ``` -------------------------------- ### Initialize MAPInferenceEngine Source: https://prophetverse.com/latest/mmm/mediators_and_frontdoor.html Sets up the Maximum A Posteriori inference engine with progress bar enabled. ```python MAPInferenceEngine(progress_bar=True) ``` -------------------------------- ### Initialize Budget Optimizer with Investment Per Series Parametrization Source: https://prophetverse.com/latest/mmm/budget_allocation.html Sets up the BudgetOptimizer to optimize investment allocation across different series while keeping channel shares fixed within each series. This is useful for adjusting the total budget distribution among series. ```python from prophetverse.budget_optimization.parametrization_transformations import InvestmentPerSeries budget_optimizer_panel_s = BudgetOptimizer( objective=MaximizeKPI(), constraints=[TotalBudgetConstraint()], parametrization_transform=InvestmentPerSeries(), options={"disp": True}, ) ``` -------------------------------- ### Initialize Budget Optimizer for Panel Data Source: https://prophetverse.com/latest/mmm/budget_allocation.html Sets up the BudgetOptimizer for panel data with a KPI maximization objective and total budget constraints. The 'disp' option enables verbose output during optimization. ```python budget_optimizer_panel = BudgetOptimizer( objective=MaximizeKPI(), constraints=[TotalBudgetConstraint()], options={"disp": True, "maxiter": 1000}, ) ``` -------------------------------- ### Initialize pre-commit hooks Source: https://prophetverse.com/latest/development.html Run this command from the repository root to enable automatic styling checks on every commit. ```bash pre-commit install ``` -------------------------------- ### Get Test Parameters for Prophetverse Source: https://prophetverse.com/latest/reference/Prophetverse.html Retrieve default test parameters for the Prophetverse forecaster, useful for unit testing. ```python sktime.Prophetverse.get_test_params(parameter_set='default') ``` -------------------------------- ### Initialize and fit a Prophetverse model Source: https://prophetverse.com/latest/tutorials/count_data.html Configure a model with exogenous seasonality effects and a flat trend, then fit it to training data. ```python exogenous_effects = [ ( "seasonality", LinearFourierSeasonality( sp_list=[24, 24 * 7, 24 * 365.5], fourier_terms_list=[2, 2, 10], freq="H", prior_scale=0.1, effect_mode="multiplicative", ), no_input_columns, ), ] model = Prophetverse( trend=FlatTrend(), exogenous_effects=exogenous_effects, inference_engine=MAPInferenceEngine(), ) model.fit(y=y_train) ``` -------------------------------- ### Get HierarchicalProphet Test Parameters Source: https://prophetverse.com/latest/reference/HierarchicalProphet.html Retrieves parameters for testing the HierarchicalProphet model. The parameter_set argument is ignored in this implementation. ```python sktime.HierarchicalProphet.get_test_params(parameter_set='default') ``` -------------------------------- ### LiftExperimentLikelihood with Chained Effects Source: https://prophetverse.com/latest/mmm/fitting_and_calibration.html This snippet shows a LiftExperimentLikelihood configured with chained effects, starting with GeometricAdstockEffect and followed by saturation. ```python LiftExperimentLikelihood(effect=ChainedEffects(steps=[('adstock', GeometricAdstockEffect()), ('saturation', ``` -------------------------------- ### Initialize Prophetverse Forecaster Source: https://prophetverse.com/latest/reference/Prophetverse.html Instantiate the Prophetverse forecaster with various configuration options for trend, exogenous effects, and likelihood. ```python sktime.Prophetverse( self, trend='linear', exogenous_effects=None, default_effect=None, feature_transformer=None, noise_scale=None, likelihood='normal', scale=None, rng_key=None, inference_engine=None, broadcast_mode='estimator', ) ``` -------------------------------- ### Configure VIInferenceEngine Source: https://prophetverse.com/latest/tutorials/univariate.html Sets up the VIInferenceEngine for Prophetverse model training. This engine uses Variational Inference with specified steps, optimizer, and progress bar. ```python VIInferenceEngine(num_steps=100000, optimizer=CosineScheduleAdamOptimizer(), progress_bar=True) ``` -------------------------------- ### Initialize Prophetverse model Source: https://prophetverse.com/latest/tutorials/tuning.html Configures the Prophetverse model with specific trend and seasonality components before tuning. ```python # Create the initial Prophetverse model. model = Prophetverse( trend=PiecewiseLinearTrend( changepoint_interval=500, changepoint_prior_scale=0.00001, changepoint_range=-250, ), exogenous_effects=[ ( "seasonality", LinearFourierSeasonality( freq="D", sp_list=[7, 365.25], fourier_terms_list=[3, 10], prior_scale=0.1, effect_mode="multiplicative", ), no_input_columns, ), ], inference_engine=MAPInferenceEngine(), ) model ``` -------------------------------- ### Initialize and fit a Prophetverse model Source: https://prophetverse.com/latest/mmm/getting_familiar.html Configure a model with linear effects and seasonality, then fit it to training data. ```python from prophetverse import Prophetverse, LinearEffect, LinearFourierSeasonality from prophetverse.utils.regex import starts_with, no_input_columns seasonality_effect = LinearFourierSeasonality( sp_list=[365.25, 7], fourier_terms_list=[10, 3], prior_scale=0.1, freq="D", effect_mode="additive", ) ad_spend_effect = LinearEffect() model = Prophetverse( exogenous_effects=[ ("ad_spend", ad_spend_effect, starts_with("ad")), ("seasonality", seasonality_effect, no_input_columns), ], ) model.fit(y=y_train, X=X_train) ``` -------------------------------- ### Run pre-commit checks manually Source: https://prophetverse.com/latest/development.html Commands to execute pre-commit checks manually without installing hooks or to run specific stages. ```bash pre-commit run --files ``` ```bash pre-commit run --from-ref=upstream/main --to-ref=HEAD --all-files ``` ```bash pre-commit run --hook-stage manual --all-files ``` -------------------------------- ### Initialize model components Source: https://prophetverse.com/latest/howto/custom_trend.html Individual component initializations for trend, seasonality, and inference engine. ```python GenLogisticTrend() ``` ```python LinearFourierSeasonality(effect_mode='multiplicative', fourier_terms_list=[3, 8], freq='D', prior_scale=0.1, sp_list=[7, 365.25]) ``` ```python MCMCInferenceEngine(num_samples=500, num_warmup=1000) ``` -------------------------------- ### Get Changepoint Matrix Source: https://prophetverse.com/latest/reference/PiecewiseLinearTrend.html Retrieves the changepoint matrix for a given index. This method is useful for understanding the internal structure of the trend model. ```python effects.PiecewiseLinearTrend.get_changepoint_matrix(idx) ``` -------------------------------- ### BudgetOptimizer Class Initialization Source: https://prophetverse.com/latest/reference/BudgetOptimizer.html Initializes the BudgetOptimizer with objective, constraints, and other optimization parameters. ```APIDOC ## BudgetOptimizer Class ### Description Budget optimizer using scipy.optimize.minimize. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **objective** (BaseOptimizationObjective) - Required - Objective function object - **constraints** (list of BaseConstraint) - Required - List of constraint objects - **decision_variable_transform** (BaseDecisionVariableTransform) - Required - Decision variable transform object - **method** (str) - Optional - Optimization method to use. Default is “SLSQP”. - **tol** (float) - Optional - Tolerance for termination. Default is None. - **bounds** (Union[List[tuple], dict[str, tuple]]) - Optional - Bounds for decision variables. If a list, the value is used directly in scipy.optimize.minimize. If a dict, the keys are the column names and the values are the bounds for each column. Default is (0, np.inf) for each column. - **options** (dict) - Optional - Options for the optimization method. Default is None. - **callback** (callable) - Optional - Callback function to be called after each iteration. Default is None. ### Request Example ```json { "objective": "", "constraints": ["", ""], "decision_variable_transform": "", "method": "SLSQP", "tol": 0.001, "bounds": {"col1": (0, 100), "col2": (None, 50)}, "options": {"disp": True}, "callback": "" } ``` ### Response #### Success Response (200) - **BudgetOptimizer object** - The initialized BudgetOptimizer instance. #### Response Example ```json { "message": "BudgetOptimizer initialized successfully." } ``` ``` -------------------------------- ### Calculate Average MAPE Source: https://prophetverse.com/latest/mmm/fitting_and_calibration.html Calculate the mean of the test Mean Absolute Percentage Error across all cross-validation folds to get an overall performance metric. ```python cv_results["test_MeanAbsolutePercentageError"].mean() ``` -------------------------------- ### Prophetverse Model Initialization Source: https://prophetverse.com/latest/tutorials/univariate.html Initializes a Prophetverse model with multiplicative seasonality, Fourier terms for seasonality, and a piecewise linear trend. The inference engine is configured for 100,000 steps using a cosine schedule Adam optimizer with a progress bar. ```python Prophetverse(exogenous_effects=[('seasonality', LinearFourierSeasonality(effect_mode='multiplicative', fourier_terms_list=[3, 10], freq='D', prior_scale=0.1, sp_list=[7, 365.25]), '^$')], inference_engine=VIInferenceEngine(num_steps=100000, optimizer=CosineScheduleAdamOptimizer(), progress_bar=True), trend=PiecewiseLinearTrend(changepoint_interval=500, changepoint_prior_scale=1e-05, changepoint_range=-500)) ``` -------------------------------- ### Get Component Contributions with Prophetverse Source: https://prophetverse.com/latest/mmm/getting_familiar.html Use `predict_components` to retrieve the contribution of each component. Ensure `fh` (forecast horizon) and `X` (exogenous variables) are defined. ```python components = model.predict_components(fh=fh, X=X) components.head() ``` -------------------------------- ### Predict Components with Prophetverse Source: https://prophetverse.com/latest/mmm Use the `predict_components` method to get a dataframe of model components for future dates. The 'mean' column represents the final prediction. ```python fh = pd.period_range(start="2023-01-01", end="2023-06-30", freq="D") y_pred_components = model.predict_components(fh=fh, X=X) ``` -------------------------------- ### Initialize BudgetOptimizer Source: https://prophetverse.com/latest/reference/BudgetOptimizer.html Constructor for the BudgetOptimizer class, requiring an objective function and constraints. ```python budget_optimization.optimizer.BudgetOptimizer( self, objective, constraints, parametrization_transform=None, method='SLSQP', tol=None, bounds=None, options=None, callback=None, ) ``` -------------------------------- ### Initialize and Fit Prophetverse Model Source: https://prophetverse.com/latest/mmm/fitting_and_calibration.html Initializes the Prophetverse model with specified trend, seasonality, and media effects, then fits the model to the provided time-series data (y) and exogenous variables (X). ```python baseline_model = Prophetverse( trend=PiecewiseLinearTrend(changepoint_interval=100), exogenous_effects=[yearly, weekly, chained_search, chained_social], inference_engine=MAPInferenceEngine( num_steps=5000, optimizer=LBFGSSolver(memory_size=300, max_linesearch_steps=300), ), ) baseline_model.fit(y=y, X=X) ``` -------------------------------- ### Define Chained Effects for Awareness to Sales Source: https://prophetverse.com/latest/mmm/proxy_variables.html Models a sequence of effects, starting with saturation and followed by adstock, to represent the customer journey from awareness to sales. ```python ChainedEffects(steps=[('saturation', Forward(effect_name='latent/awareness')), ('adstock', WeibullAdstockEffect(max_lag=90))]) ``` -------------------------------- ### Initialize Budget Optimizer with Channel Share Parametrization Source: https://prophetverse.com/latest/mmm/budget_allocation.html Configures the BudgetOptimizer to optimize channel share globally across all series. This transformation keeps total investment and spending patterns fixed while optimizing the proportion of budget allocated to each channel. ```python from prophetverse.budget_optimization import InvestmentPerChannelTransform budget_optimizer_panel_ch = BudgetOptimizer( objective=MaximizeKPI(), constraints=[TotalBudgetConstraint()], parametrization_transform=InvestmentPerChannelTransform(), options={"disp": True}, ) ``` -------------------------------- ### MaximizeKPI Objective Function Source: https://prophetverse.com/latest/reference/MaximizeKPI.html Use this objective to maximize the key performance indicator (KPI) during budget optimization. No specific setup is required beyond instantiating the objective. ```python budget_optimization.objectives.MaximizeKPI(self) ``` -------------------------------- ### Initialize and Fit Prophetverse Model Source: https://prophetverse.com/latest/mmm/proxy_variables.html Configures the Prophetverse model with exogenous effects and a MAP inference engine, then fits the model to data. ```python baseline_model = Prophetverse( trend=trend, exogenous_effects=[ yearly, weekly, spend_awareness, awareness_to_sales, latent_baseline, chained_last_click, ], inference_engine=MAPInferenceEngine( num_steps=5000, optimizer=LBFGSSolver(memory_size=300, max_linesearch_steps=300), ), ) baseline_model.fit(y=y, X=X) ``` -------------------------------- ### Configure and Fit Prophetverse Model Source: https://prophetverse.com/latest/howto/composite_effects.html Initializes a Prophetverse model with trend, seasonality, and linear effects, then fits it to the training data. ```python from prophetverse.effects import LinearEffect from prophetverse.effects.fourier import LinearFourierSeasonality from prophetverse.effects.trend import PiecewiseLinearTrend from prophetverse.engine import MAPInferenceEngine from prophetverse.engine.optimizer import LBFGSSolver from prophetverse.sktime import Prophetverse from prophetverse.utils.regex import exact, no_input_columns model = Prophetverse( trend=PiecewiseLinearTrend( changepoint_interval=500, changepoint_prior_scale=0.00001, changepoint_range=-500, ), exogenous_effects=[ ( "seasonality", LinearFourierSeasonality( freq="D", sp_list=[365.25], fourier_terms_list=[5], prior_scale=1, effect_mode="multiplicative", ), no_input_columns, ), ( "investment", LinearEffect("multiplicative", prior=dist.Normal(0, 1)), exact("investment"), ), ], inference_engine=MAPInferenceEngine( optimizer=LBFGSSolver(memory_size=100, max_linesearch_steps=100), progress_bar=True, ), ) model.fit(y=y_train, X=X_train) model ``` -------------------------------- ### MAPInferenceEngine Initialization Source: https://prophetverse.com/latest/howto/custom_effects.html Initializes the MAPInferenceEngine for the Prophetverse model. ```python MAPInferenceEngine() ``` -------------------------------- ### Configure MAPInferenceEngine Source: https://prophetverse.com/latest/mmm/fitting_and_calibration.html Sets up the Maximum A Posteriori inference engine with LBFGS optimization. ```python MAPInferenceEngine(num_steps=5000, optimizer=LBFGSSolver(max_linesearch_steps=300, memory_size=300)) ``` -------------------------------- ### Initialize and fit a Prophetverse model Source: https://prophetverse.com/latest/howto/custom_trend.html Configures the model with negative binomial likelihood, logistic trend, and Fourier seasonality before fitting to training data. ```python import numpyro from sktime.transformations.series.fourier import FourierFeatures from prophetverse.effects import LinearFourierSeasonality from prophetverse.effects.linear import LinearEffect from prophetverse.engine import MCMCInferenceEngine from prophetverse.sktime import Prophetverse from prophetverse.utils.regex import no_input_columns, starts_with numpyro.enable_x64() model = Prophetverse( likelihood="negbinomial", trend=GenLogisticTrend(), exogenous_effects=[ ( "seasonality", LinearFourierSeasonality( sp_list=[7, 365.25], fourier_terms_list=[3, 8], freq="D", prior_scale=0.1, effect_mode="multiplicative", ), no_input_columns, ), ], inference_engine=MCMCInferenceEngine( num_samples=500, num_warmup=1000, ), # Avoid normalization of the timeseries by setting # scale=1 scale=1, noise_scale=10, ) numpyro.enable_x64() model.fit(y_train) ``` -------------------------------- ### Configure Prophetverse with Exogenous Effects Source: https://prophetverse.com/latest/howto/effect_api_intro.html Demonstrates how to define and pass a list of exogenous effects to the Prophetverse model using predefined effect classes and regex utilities. ```python from prophetverse.sktime import Prophetverse from prophetverse.effects import LinearFourierSeasonality, HillEffect from prophetverse.utils.regex import starts_with, no_input_columns exogenous_effects = [ ( "seasonality", # The name of the effect LinearFourierSeasonality( # The object freq="D", sp_list=[7, 365.25], fourier_terms_list=[3, 10], prior_scale=0.1, effect_mode="multiplicative", ), no_input_columns, # The regex ), ( "exog", HillEffect(effect_mode="additive"), starts_with("exog") ) ] model = Prophetverse(exogenous_effects=exogenous_effects) ``` -------------------------------- ### Configure Prophetverse model components Source: https://prophetverse.com/latest/tutorials/count_data.html Import necessary modules for defining seasonality, trend, and inference engines for the Prophetverse model. ```python from prophetverse.effects.fourier import LinearFourierSeasonality from prophetverse.effects.trend import FlatTrend from prophetverse.engine import MAPInferenceEngine from prophetverse.engine.optimizer import CosineScheduleAdamOptimizer, LBFGSSolver from prophetverse.sktime import Prophetverse from prophetverse.utils.regex import no_input_columns # Here we set the prior for the seasonality effect ``` -------------------------------- ### Initialize LiftExperimentLikelihood Source: https://prophetverse.com/latest/reference/LiftExperimentLikelihood.html Initializes the class with an effect, lift test results, and prior scale parameters. ```python effects.LiftExperimentLikelihood( self, effect, lift_test_results, prior_scale, likelihood_scale=1, ) ``` -------------------------------- ### Compare Spend and Predict KPIs Source: https://prophetverse.com/latest/mmm/budget_allocation.html Visualize the difference in spend between baseline and optimized scenarios and print predicted KPIs and spend. This helps in understanding the impact of budget optimization. ```python plot_spend_comparison_panel( X0_panel, X_opt_min_panel, ["ad_spend_search", "ad_spend_social_media"], indexer=horizon, ) plt.show() y_pred_baseline_min_panel = fitted_model_panel.predict(X=X0_panel, fh=horizon) y_pred_opt_min_panel = fitted_model_panel.predict(X=X_opt_min_panel, fh=horizon) print( f"MMM Predictions \n", f"Baseline KPI: {y_pred_baseline_min_panel.values.sum()/1e9:.2f} B \n", f"Optimized KPI: {y_pred_opt_min_panel.values.sum()/1e9:.2f} B \n", f"Target KPI: {target_panel/1e9:.2f} B \n", "Baseline spend: ", X0_panel.loc[ pd.IndexSlice[:, horizon], ["ad_spend_search", "ad_spend_social_media"] ] .sum() .sum(), "\n", "Optimized spend: ", X_opt_min_panel.loc[ pd.IndexSlice[:, horizon], ["ad_spend_search", "ad_spend_social_media"] ] .sum() .sum(), "\n", ) ``` ```text MMM Predictions Baseline KPI: 1.63 B Optimized KPI: 1.96 B Target KPI: 1.96 B Baseline spend: 4179163.3068621266 Optimized spend: 7755666.679734475 ``` -------------------------------- ### Initialize ForecastingGridSearchCV Source: https://prophetverse.com/latest/tutorials/tuning.html Set up GridSearchCV with a specified model, parameter grid, and cross-validation strategy. This is used for hyperparameter tuning. ```python grid_search = ForecastingGridSearchCV( model, param_grid=param_grid, cv=cv ) grid_search ``` -------------------------------- ### Configure Prophetverse Model with Exogenous Effects Source: https://prophetverse.com/latest/mmm/fitting_and_calibration.html Clone an existing model and set parameters to include new exogenous effects for search and social media attribution. Ensure the likelihood and ad spend data are correctly specified. ```python model_umm = model_lift.clone() model_umm.set_params( exogenous_effects=model_lift.get_params()["exogenous_effects"] + [ ( "attribution_search", ExactLikelihood("ad_spend_search", attr_search, 0.01), None, ), ( "attribution_social_media", ExactLikelihood("ad_spend_social_media", attr_social, 0.01), None, ), ] ) model_umm.fit(y=y, X=X) ``` -------------------------------- ### Initialize HierarchicalProphet Source: https://prophetverse.com/latest/reference/HierarchicalProphet.html Initializes the HierarchicalProphet model with specified parameters. Use this to set up the forecasting model before fitting it to data. ```python sktime.HierarchicalProphet( self, trend='linear', feature_transformer=None, exogenous_effects=None, default_effect=None, shared_features=None, noise_scale=0.05, correlation_matrix_concentration=1.0, rng_key=None, inference_engine=None, likelihood=None, ) ``` -------------------------------- ### Display model configuration Source: https://prophetverse.com/latest/howto/custom_trend.html Shows the string representation of the initialized Prophetverse model. ```python Prophetverse(exogenous_effects=[('seasonality', LinearFourierSeasonality(effect_mode='multiplicative', fourier_terms_list=[3, 8], freq='D', prior_scale=0.1, sp_list=[7, 365.25]), '^$')], inference_engine=MCMCInferenceEngine(num_samples=500, num_warmup=1000), likelihood='negbinomial', noise_scale=10, scale=1, trend=GenLogisticTrend()) ``` -------------------------------- ### Load Synthetic Marketing Dataset Source: https://prophetverse.com/latest/mmm/proxy_variables.html Imports necessary libraries and retrieves a synthetic dataset containing investment and sales data. ```python import numpy as np import matplotlib.pyplot as plt from prophetverse.datasets._mmm.dataset2_branding import get_dataset y, X, true_effect, true_model = get_dataset() display(X.head()) ``` -------------------------------- ### Instantiate LogEffect Source: https://prophetverse.com/latest/reference/LogEffect.html Instantiate a LogEffect with specified parameters. Prior distributions for scale and rate can be provided, or they will default to Gamma. The effect mode can be set to 'additive' or 'multiplicative'. ```python effects.LogEffect( self, effect_mode='multiplicative', scale_prior=None, rate_prior=None, ) ``` -------------------------------- ### Initialize GammaTargetLikelihood Source: https://prophetverse.com/latest/reference/GammaTargetLikelihood.html Instantiate the GammaTargetLikelihood class. Adjust noise_scale and epsilon for specific model tuning. ```python effects.GammaTargetLikelihood(self, noise_scale=0.05, epsilon=1e-05) ``` -------------------------------- ### MCMCInferenceEngine Configuration Source: https://prophetverse.com/latest/tutorials/hierarchical.html Shows the settings for the MCMCInferenceEngine. ```python MCMCInferenceEngine(num_warmup=500) ``` -------------------------------- ### Initialize MinimumTargetResponse Source: https://prophetverse.com/latest/reference/MinimumTargetResponse.html Instantiate the constraint to enforce a minimum output value during budget optimization. ```python budget_optimization.constraints.MinimumTargetResponse( self, target_response, constraint_type='ineq', ) ``` -------------------------------- ### Create Prophetverse Model Source: https://prophetverse.com/latest/mmm Assemble the model by combining trend, seasonality, and exogenous effects with column selection regex. ```python from prophetverse import Prophetverse from prophetverse.utils.regex import starts_with, no_input_columns model = Prophetverse( trend=trend, exogenous_effects=[ ("channelA", saturation_with_adstock, starts_with("channelA")), ("channelB", saturation, starts_with("channelB")), ("seasonality", seasonality_effect, no_input_columns), ], ) ``` -------------------------------- ### Compare Budget and Prediction for Minimum Spend Optimization Source: https://prophetverse.com/latest/mmm/budget_allocation.html Compares baseline and optimized spend, and prints KPI and spend figures for both scenarios against the target KPI. Uses plot_spend_comparison and model.predict. ```python plot_spend_comparison( X0, X_opt_min, ["ad_spend_search", "ad_spend_social_media"], indexer=horizon, ) plt.show() y_pred_baseline_min = model.predict(X=X0, fh=horizon) y_pred_opt_min = model.predict(X=X_opt_min, fh=horizon) print( f"MMM Predictions \n", f"Baseline KPI: {y_pred_baseline_min.sum()/1e9:.2f} B \n", f"Optimized KPI: {y_pred_opt_min.sum()/1e9:.2f} B \n", f"Target KPI: {target/1e9:.2f} B \n", "Baseline spend: ", X0.loc[horizon, ["ad_spend_search", "ad_spend_social_media"]].sum().sum(), "\n", "Optimized spend: ", X_opt_min.loc[horizon, ["ad_spend_search", "ad_spend_social_media"]].sum().sum(), "\n", ) ``` -------------------------------- ### Initialize TotalBudgetConstraint Source: https://prophetverse.com/latest/reference/TotalBudgetConstraint.html Initializes the TotalBudgetConstraint with optional channels and a total budget. If channels is None, all channels are considered. If total is None, it's computed from input data. ```python budget_optimization.constraints.TotalBudgetConstraint( self, channels=None, total=None, ) ``` -------------------------------- ### Compare Baseline vs. Optimized Spend Source: https://prophetverse.com/latest/mmm/budget_allocation.html Visualize the difference between baseline and optimized ad spend across specified channels and plot the predicted KPI gain. Requires the model, original X, optimized X, channel columns, and horizon. ```python y_pred_opt_reparam = model.predict(X=X_opt_reparam, fh=horizon) fig, ax = plot_spend_comparison( X, X_opt_reparam, ["ad_spend_search", "ad_spend_social_media"], horizon, ) kpi_gain = y_pred_opt_reparam.sum() / y_pred_baseline.sum() - 1 fig.suptitle(f"KPI gain: +{kpi_gain:.2%}", fontsize=16, weight="bold", y=1.02) fig.tight_layout() fig.show() ``` -------------------------------- ### Prophetverse Model Configuration Summary Source: https://prophetverse.com/latest/mmm/mediators_and_frontdoor.html Shows the configuration of the fitted Prophetverse model, detailing its trend, inference engine, exogenous effects (seasonality, investment, visit_sales), and scale. ```python Prophetverse(exogenous_effects=[('seasonality', MultiplyEffects(effects=[('trend', Forward(effect_name='trend')), ('seasonality', LinearFourierSeasonality(fourier_terms_list=[1], freq='D', prior_scale=0.1, sp_list=[30.25]))]), None), ('investment', MultiplyEffects(effects=[('trend', Forward(effect_name='trend')), ('investment', ChainedEffects(steps=[('adstock',...) max_effect_prior=))]))]), '^investment$'), ('visit_sales', LinearEffect(effect_mode='additive', prior=), '^visits$')], inference_engine=MAPInferenceEngine(progress_bar=True), scale=1, ``` -------------------------------- ### NegativeBinomialTargetLikelihood Constructor Source: https://prophetverse.com/latest/reference/NegativeBinomialTargetLikelihood.html Initializes the NegativeBinomialTargetLikelihood with specified noise scale and epsilon values. ```APIDOC ## NegativeBinomialTargetLikelihood Constructor ### Description Initializes the NegativeBinomialTargetLikelihood class. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **noise_scale** (float) - Optional - Default value is 0.05. The noise scale parameter. - **epsilon** (float) - Optional - Default value is 1e-05. The epsilon parameter. ### Request Example ```python from prophetverse.effects import NegativeBinomialTargetLikelihood # Example with default values likelihood = NegativeBinomialTargetLikelihood() # Example with custom values likelihood = NegativeBinomialTargetLikelihood(noise_scale=0.1, epsilon=1e-06) ``` ### Response #### Success Response (200) None (This is a constructor, it does not return a value directly but initializes an object). #### Response Example None ```