pymc_forecast.fit#

Functional fitters shared with the forecaster classes. Each takes an optional already-built model=, which must be a training-window model: a model with forecast-horizon variables (forecast or *_future free variables) is rejected with HorizonError. Only the model_fn, data, covariates path trims covariates: when model is omitted, the fitter drops covariate rows past the training window, calls build_model(model_fn, data, covariates) once, and samples that model. Class _fit methods pass model=self.model and do not build again.

Functional fitters: one sampling path shared with the forecaster classes.

Each fitter accepts an already-built model=, which must be a training-window model: a model with forecast-horizon variables (forecast or {name}_future free variables) is rejected with HorizonError. When model is given, model_fn, data and covariates are ignored (model_fn is still a required positional argument). When model is omitted, the fitter drops covariate rows past the training window, calls build_model() once, and samples that model; only the model_fn, data, covariates path performs that trim. The forecaster classes pass their own training model and do not build again.

class pymc_forecast.fit.FitResult(idata, approx, losses, method)[source]#

Bases: object

A completed fit.

Variational results carry approx and losses and keep idata=None; the result is frozen and never filled in, so pass draw_posterior(result, n) (a posterior Dataset) to forecast. MCMC and Pathfinder set idata, which can also be passed to forecast directly. method is "mcmc", "pathfinder", or the VI method passed to fit_vi() (a name or an inference object).

Each parameter is available as an attribute of the same name.

Parameters:
  • idata (xarray.DataTree or arviz.InferenceData or None) – Output of pm.sample (MCMC) or pymc_extras.fit_pathfinder (Pathfinder) with a posterior group: a DataTree with current PyMC/ArviZ, InferenceData with older releases. None for VI.

  • approx (pymc.variational.Approximation or None) – The fitted variational approximation for VI; None otherwise.

  • losses (numpy.ndarray or None) – Loss history (approx.hist) for VI: one value per step for ADVI and full-rank ADVI, empty for "svgd"/"asvgd" (no loss is recorded); None otherwise.

  • method (str or pymc.variational.Inference) – "mcmc", "pathfinder", or the method argument of fit_vi() as passed.

pymc_forecast.fit.draw_posterior(result, num_samples, random_seed=None, *, batch_size=None)[source]#

Draw or thin num_samples posterior samples from a FitResult.

Variational results are sampled from the approximation, optionally in host-side chunks of batch_size. MCMC and Pathfinder results are thinned once from idata.posterior.

Parameters:
  • result (FitResult) – A result of fit_vi(), fit_mcmc() or fit_pathfinder().

  • num_samples (int) – Number of posterior draws to return.

  • random_seed (int or numpy.random.Generator, optional) – Seed for sampling the approximation or thinning idata.

  • batch_size (int, optional) – For variational results, draw at most this many samples at once and concatenate the chunks; None draws all at once. Ignored (but still validated) for MCMC and Pathfinder results.

Returns:

xarray.Dataset – Posterior samples with a single chain and num_samples draws.

Raises:

ValueError – If batch_size is not positive, or num_samples is not positive for an MCMC or Pathfinder result.

pymc_forecast.fit.fit_mcmc(model_fn, data=None, covariates=None, *, draws=1000, tune=1000, chains=2, nuts_sampler='pymc', random_seed=None, progressbar=None, sample_kwargs=None, model=None)[source]#

Fit model_fn (or an already-built model) with MCMC.

Parameters:
  • model_fn (callable or pymc_forecast.model.ForecastingModel) – Model body called as model_fn(covariates, data); it must register obs (normally via predict()). Ignored when model is given.

  • data (xarray.DataArray, pandas.Series, pandas.DataFrame or array_like, optional) – Observed training series, normalized with as_dataarray() ("time" first; 2-D input gets a "series" dim). Required unless model is given.

  • covariates (xarray.DataArray, pandas.Series, pandas.DataFrame or array_like, optional) – Covariates on the same "time" coordinate as data (normalized with as_dataarray; 2-D input gets a "covariate" dim). Rows past the training window are dropped. None means no covariates.

  • draws (int, default 1000) – Posterior draws per chain, forwarded to pm.sample.

  • tune (int, default 1000) – Tuning steps per chain, forwarded to pm.sample.

  • chains (int, default 2) – Number of chains, forwarded to pm.sample.

  • nuts_sampler ({"pymc", "nutpie", "numpyro", "blackjax"}, default "pymc") – NUTS implementation, forwarded to pm.sample; non-PyMC samplers need their optional package.

  • random_seed (int or numpy.random.Generator, optional) – Seed forwarded to pm.sample.

  • progressbar (bool, optional) – Show the sampling progress bar; None means off. May instead be given as a sample_kwargs key, but not both.

  • sample_kwargs (mapping, optional) – Extra keyword arguments forwarded to pm.sample.

  • model (pymc.Model, optional) – An already-built training-window model to sample instead of building one from model_fn, data and covariates.

Returns:

FitResult – Result with idata set and method="mcmc".

Raises:
pymc_forecast.fit.fit_pathfinder(model_fn, data=None, covariates=None, *, random_seed=None, progressbar=None, pathfinder_kwargs=None, model=None)[source]#

Fit model_fn (or an already-built model) with Pathfinder.

Parameters:
  • model_fn (callable or pymc_forecast.model.ForecastingModel) – Model body called as model_fn(covariates, data); it must register obs (normally via predict()). Ignored when model is given.

  • data (xarray.DataArray, pandas.Series, pandas.DataFrame or array_like, optional) – Observed training series, normalized with as_dataarray() ("time" first; 2-D input gets a "series" dim). Required unless model is given.

  • covariates (xarray.DataArray, pandas.Series, pandas.DataFrame or array_like, optional) – Covariates on the same "time" coordinate as data (normalized with as_dataarray; 2-D input gets a "covariate" dim). Rows past the training window are dropped. None means no covariates.

  • random_seed (int, optional) – Seed forwarded to pymc_extras.fit_pathfinder.

  • progressbar (bool, optional) – Show the progress bar; None means off. May instead be given as a pathfinder_kwargs key, but not both.

  • pathfinder_kwargs (mapping, optional) – Extra keyword arguments forwarded to pymc_extras.fit_pathfinder.

  • model (pymc.Model, optional) – An already-built training-window model to fit instead of building one from model_fn, data and covariates.

Returns:

FitResult – Result with idata set and method="pathfinder".

Raises:
pymc_forecast.fit.fit_vi(model_fn, data=None, covariates=None, *, method='advi', optimizer=None, backend=None, num_steps=10000, random_seed=None, progressbar=None, fit_kwargs=None, model=None)[source]#

Fit model_fn (or an already-built model) with variational inference.

Parameters:
  • model_fn (callable or pymc_forecast.model.ForecastingModel) – Model body called as model_fn(covariates, data); it must register obs (normally via predict()). Ignored when model is given.

  • data (xarray.DataArray, pandas.Series, pandas.DataFrame or array_like, optional) – Observed training series, normalized with as_dataarray() ("time" first; 2-D input gets a "series" dim). Required unless model is given.

  • covariates (xarray.DataArray, pandas.Series, pandas.DataFrame or array_like, optional) – Covariates on the same "time" coordinate as data (normalized with as_dataarray; 2-D input gets a "covariate" dim). Rows past the training window are dropped. None means no covariates.

  • method (str or pymc.variational.Inference, default "advi") – Forwarded to pm.fit (e.g. "advi" or "fullrank_advi", or an inference object, which fits the model it was built on and ignores random_seed). The JAX backend accepts only "advi".

  • optimizer (callable or float, optional) – None uses Adam with learning rate 0.01; a positive number is an Adam learning rate; a callable is passed to pm.fit as obj_optimizer (PyTensor backend only).

  • backend ({"pytensor", "jax"}, optional) – None or "pytensor" runs pm.fit; "jax" runs pymc_forecast.jax_backend.fit_advi_jax.

  • num_steps (int, default 10_000) – Number of optimization steps.

  • random_seed (int, optional) – Seed for the fit.

  • progressbar (bool, optional) – Show the fit progress bar; None means off. May instead be given as a fit_kwargs key, but not both. Ignored by the JAX backend.

  • fit_kwargs (mapping, optional) – Extra keyword arguments forwarded to pm.fit. Not supported with backend="jax".

  • model (pymc.Model, optional) – An already-built training-window model to fit instead of building one from model_fn, data and covariates.

Returns:

FitResult – Result with approx and losses set and idata=None.

Raises:
Warns:

UserWarning – If the loss is still clearly decreasing at the end of the fit (a heuristic convergence check), or if the loss history contains non-finite values so convergence cannot be assessed.