BayesianBasisExpansionTimeSeries#
- class causalpy.pymc_models.BayesianBasisExpansionTimeSeries[source]#
Bayesian Structural Time Series Model.
This model allows for the inclusion of trend, seasonality (via Fourier series), and optional exogenous regressors.
\[\begin{split}\text{trend} &\sim \text{LinearTrend}(...) \\ \text{seasonality} &\sim \text{YearlyFourier}(...) \\ \beta &\sim \mathrm{Normal}(0, \sigma_{\beta}) \quad \text{(if X is provided)} \\ \sigma &\sim \mathrm{HalfNormal}(\sigma_{err}) \\ \mu &= \text{trend_component} + \text{seasonality_component} + X \cdot \beta \quad \text{(if X is provided)} \\ y &\sim \mathrm{Normal}(\mu, \sigma)\end{split}\]- Parameters:
n_order (
int) – The number of Fourier components for the yearly seasonality. Defaults to 3. Only used if seasonality_component is None.n_changepoints_trend (
int) – The number of changepoints for the linear trend component. Defaults to 10. Only used if trend_component is None.prior_sigma (
float|None) – Explicit scale of the HalfNormal observation-noise prior. If None, use the fitted outcome scale whenauto_scale_priors=True, or the legacy scale 5 otherwise. Asigmaentry inpriorstakes precedence.trend_component (
Any|None) – A custom trend component model. If None, the default pymc-marketing LinearTrend component is used. Must have an apply(time_data) method that returns a PyMC tensor.seasonality_component (
Any|None) – A custom seasonality component model. If None, the default pymc-marketing YearlyFourier component is used. Must have an apply(time_data) method that returns a PyMC tensor.sample_kwargs (
dict[str,Any] |None) – A dictionary of kwargs that get unpacked and passed to thepymc.sample()function. Defaults to an empty dictionary.priors (
dict[str,Any] |None) – Explicitpymc_extras.prior.Prioroverrides keyed bybeta(dimensionscoeffs),sigma(treated_units),delta(changepoint), orfourier_beta(fourier). Component overrides apply only to the built-in components; custom components retain their own priors.prior_sample_kwargs (
dict[str,Any] |None) – A dictionary of kwargs that get unpacked and passed to thepymc.sample_prior_predictive()function when the prior phase runs. Defaults to{"draws": 500}plus the posteriorrandom_seedifNone.auto_scale_priors (
bool) – Calibrate built-in priors using the fitted data only. Defaults to True. Set False to retain the legacy fixed scales, including HalfNormal(5) noise unless explicitly overridden.
Notes
Automatic calibration is an empirical-Bayes reference default, not a substitute for prior predictive checks or domain knowledge. In an InterruptedTimeSeries experiment only pre-intervention data reach this model. Let
sbe the fitted outcome sample standard deviation ands_tthe sample standard deviation of fitted elapsed times in years. Noise uses HalfNormal(s), using total outcome variation as a reference scale rather than estimating residual noise. Regression coefficient scales use the largest absolute outcome divided by each design column’s root mean square, including an intercept; each coefficient’s individual fitted RMS contribution then has that outcome-magnitude scale.Fourier coefficients use Laplace scale
s / sqrt(2 * n_order). Since each sine/cosine pair has squared basis norm 1 and a Laplace variance is twice its squared scale, the pointwise seasonal prior SD iss. ForM = n_changepoints_trend, the initial slope uses Laplace scales / (sqrt(2) * s_t), making its expected sample variance over the fitted dates equal tos**2, independently ofM. The remainingM - 1slope changes use scales / (sqrt(2 * (M - 1)) * s_t). Each hinge has sample SD at mosts_t, so their aggregate expected sample variance is at mosts**2, and total trend expected sample variance is at most2 * s**2. A single distinct fitted date uses a one-day time scale. These are reference scales for component contributions, not guarantees of local coefficient recovery or calibrated uncertainty.A constant, numerically constant, or singleton outcome has no estimable spread: its largest absolute value is used instead, or 1 for an all-zero outcome, with a warning. This fallback keeps prior scales finite; it does not ensure an identifiable or well-behaved posterior for noiseless data. Zero design columns use a denominator of 1. Predictions retain the original outcome units. Custom components are never rescaled; their priors must be calibrated by the caller.
Methods
Register a dimension coordinate with the model.
Vectorized version of
Model.add_coord.Add a random graph variable to the named variables of the model.
Construct the graph and record the time-feature data nodes.
Construct a specialized mapping-input graph without sampling.
Defines the PyMC model.
Check that the logp is defined and finite at the starting point.
Compiled log probability density hessian function.
Compiled log probability density gradient function.
Compiles a PyTensor function.
Compiled log probability density function.
Clone the model.
Create a
TensorVariablethat will be used as the random variable's "value" in log-likelihood graphs.Hessian of the models log-probability w.r.t.
Debug model function at point.
Gradient of the models log-probability w.r.t.
Evaluate shapes of untransformed AND transformed free variables.
BayesianBasisExpansionTimeSeries.fit(X, y[, ...])Build the graph (if needed), then sample prior and posterior phases.
Fit a specialized model that accepts mapping-valued inputs.
Compute the initial point of the model.
Elemwise log-probability of the model.
Compile a PyTensor function that computes logp and gradient.
Create a TensorVariable for an observed random variable.
Check if name has prefix and adds if needed.
Check if name has prefix and deletes if needed.
Compute the log probability of point for all random variables in the model.
Predict data given input data X, conditioned on the given draw group.
Calibrate stock priors from fitted inputs, preserving explicit choices.
Compile and profile a PyTensor function which returns
outsand takes values of model vars as a dict as an argument.Register a data variable with the model.
Register an (un)observed random variable with the model.
Clone and replace random variables in graphs with their value variables.
Raise unless the PyMC graph has been constructed with
build().Return the draws Dataset for group or raise an actionable error.
Sample the posterior phase: NUTS plus posterior predictive draws.
BayesianBasisExpansionTimeSeries.sample_prior_predictive(...)Sample the prior predictive phase and merge it into
idata.Score the Bayesian \(R^2\) given inputs
Xand outputsy.Change the values of a data variable in the model.
Update a mutable dimension.
Set an initial value (strategy) for a random variable.
BayesianBasisExpansionTimeSeries.table(*[, ...])Create a rich table summarizing the model's variables and their expressions.
Produce a graphviz Digraph from a PyMC model.
Attributes
basic_RVsList of random variables the model is defined in terms of.
continuous_value_varsAll the continuous value variables in the model.
coordsCoordinate values for model dimensions.
datalogpPyTensor scalar of log-probability of the observed variables and potential terms.
default_priorsdim_lengthsThe symbolic lengths of dimensions in the model.
discrete_value_varsAll the discrete value variables in the model.
isrootobservedlogpPyTensor scalar of log-probability of the observed variables.
parentpotentiallogpPyTensor scalar of log-probability of the Potential terms.
prefixrootsupports_prior_predictiveWhether this backend can sample a prior predictive phase.
unobserved_RVsList of all random variables, including deterministic ones.
unobserved_value_varsList of all random variables (including untransformed projections), as well as deterministics used as inputs and outputs of the model's log-likelihood graph.
value_varsList of unobserved random variables used as inputs to the model's log-likelihood (which excludes deterministics).
varlogpPyTensor scalar of log-probability of the unobserved random variables (excluding deterministic).
varlogp_nojacPyTensor scalar of log-probability of the unobserved random variables (excluding deterministic) without jacobian term.
- __init__(n_order=3, n_changepoints_trend=10, prior_sigma=None, trend_component=None, seasonality_component=None, sample_kwargs=None, priors=None, prior_sample_kwargs=None, *, auto_scale_priors=True)[source]#
- Parameters:
sample_kwargs (
dict[str,Any] |None) – Dictionary of kwargs that get unpacked and passed to thepymc.sample()function. Defaults to an empty dictionary if None.priors (
dict[str,Any] |None) – Dictionary of priors for the model. Defaults to None, in which case default priors are used.prior_sample_kwargs (
dict[str,Any] |None) – Dictionary of kwargs that get unpacked and passed to thepymc.sample_prior_predictive()function when the prior predictive phase runs. Defaults to{"draws": 500}plus the posteriorrandom_seedifNone.n_order (int)
n_changepoints_trend (int)
prior_sigma (float | None)
trend_component (Any | None)
seasonality_component (Any | None)
auto_scale_priors (bool)
- classmethod __new__(*args, **kwargs)#