pymc_forecast.prediction#
Predictive drivers: forecasting and in-sample posterior prediction.
Both drivers rebuild the model via build_model()
(forecasting with extended covariates, in-sample with the observed window) and
run pm.sample_posterior_predictive over a posterior. Posteriors are
accepted in any of the shapes the fitting paths produce — an
xarray.DataTree or arviz.InferenceData with a posterior group, or
a bare posterior Dataset.
Prediction outputs are draw-level by contract: every variable in the
predictions (out-of-sample) and posterior_predictive (in-sample)
groups carries chain/draw dims with the full posterior-predictive
samples — nothing is reduced to means or quantiles on the default path.
prediction_samples() extracts that samples Dataset from any result
shape the drivers produce.
- pymc_forecast.prediction.forecast(model_fn, posterior, data, covariates, *, num_samples=None, var_names=None, batch_size=None, random_seed=None, progressbar=False)[source]#
Sample probabilistic forecasts over the covariate horizon.
Rebuilds the model with
covariatesextendingdataalong"time"; the surplus covariate steps are the forecast horizon. The posterior is replayed for in-sample latents while*_futurevariables (absent from it) are drawn fresh.- Parameters:
model_fn (
callableorpymc_forecast.model.ForecastingModel) – The model body ((covariates, data=None) -> Noneor aForecastingModel).posterior (
xarray.Dataset,xarray.DataTreeorarviz.InferenceData) – A posterior Dataset or any object with aposteriorgroup (posterior_dataset()); thinned only ifnum_samplesis given.data (
xarray.DataArray,pandas.Series,pandas.DataFrameorarray_like) – Observed series over the training window, normalized withas_dataarray()("time"first; 2-D input gets a"series"dim).covariates (
xarray.DataArray,pandas.Series,pandas.DataFrameorarray_like) – Covariates on the same"time"coordinate asdata, spanning the training window plus the forecast horizon (normalized withas_dataarray; 2-D input gets a"covariate"dim); the steps pastdatadefine the horizon. Required: for covariate-free models passnull_covariates()over the full time index.num_samples (
int, optional) – Thinposteriorto this many draws first (seethin_draws());Noneuses every draw.var_names (
sequenceofstr, optional) – Variables to record (a bare string is not accepted as a single name). Default:"forecast", all*_futurelatents, and — for models registered throughpredict()— the noise-free"mu_future"predictor plus"expected_observation_future"when supplied by the model. On very wide panels, restricting this to["forecast"]also shrinks the result’s memory footprint.batch_size (
int, optional) – Maximum posterior draws (per chain) per predictive pass. When set, the posterior is processed in consecutive blocks of at most this many draws and the blocks are concatenated alongdraw— bounding the working memory of each pass on very wide panels (the port of upstream’s chunked prediction, juanitorduz/numpyro_forecast#65). Per-block seeds are derived fromrandom_seed, so a batched run is deterministic given the seed but draws different (equally valid) noise than an unbatched run.Noneruns a single pass.random_seed (
intornumpy.random.Generator, optional) – Seed for thinning and predictive sampling.progressbar (
bool, defaultFalse) – Show the sampling progress bar.
- Returns:
xarray.DataTreeorarviz.InferenceData– Result ofpm.sample_posterior_predictive(a DataTree with current PyMC/ArviZ, InferenceData with older releases), with apredictionsgroup carryingtime_futurecoords.- Raises:
pymc_forecast.exceptions.HorizonError – If
covariateshas the same length asdataalong"time"(no forecast horizon; shorter covariates raiseAlignmentError), or the model body does not register"obs".pymc_forecast.exceptions.AlignmentError – If
dataorcovariatescannot be normalized or do not align.ValueError – If
num_samplesorbatch_sizeis not positive.TypeError – If
posteriorhas noposteriorgroup.
- pymc_forecast.prediction.posterior_dataset(posterior)[source]#
Extract the posterior group as a plain
xarray.Dataset.Accepts an
xarray.DataTree/arviz.InferenceData(or any object with aposterioritem or attribute; uses itsposteriorgroup) or a bareDataset(returned unchanged).- Parameters:
posterior (
xarray.Dataset,xarray.DataTreeorarviz.InferenceData) – The posterior container.- Returns:
xarray.Dataset– The posterior samples.- Raises:
TypeError – If
posterioris not a Dataset and has noposteriorgroup.
- pymc_forecast.prediction.predict_in_sample(model_fn, posterior, data, covariates=None, *, num_samples=None, batch_size=None, random_seed=None, progressbar=False)[source]#
Sample the in-sample posterior predictive of
"obs"and registered predictors.The in-sample counterpart of
forecast(): the model is rebuilt over the observed window only (no forecast horizon) and the observed variable is resampled given replayed latents. For models registered throughpredict(), the noise-free"mu"predictor is recorded alongside"obs";"expected_observation"is also recorded when supplied by the model.- Parameters:
model_fn (
callableorpymc_forecast.model.ForecastingModel) – The model body ((covariates, data=None) -> Noneor aForecastingModel).posterior (
xarray.Dataset,xarray.DataTreeorarviz.InferenceData) – A posterior Dataset or any object with aposteriorgroup (posterior_dataset()); thinned only ifnum_samplesis given.data (
xarray.DataArray,pandas.Series,pandas.DataFrameorarray_like) – Observed series, normalized withas_dataarray()("time"first; 2-D input gets a"series"dim).covariates (
xarray.DataArray,pandas.Series,pandas.DataFrameorarray_like, optional) – Covariates on the same"time"coordinate asdata, covering (at least) the observed window (normalized withas_dataarray; 2-D input gets a"covariate"dim); rows pastdataare dropped.Nonefor models without covariates.num_samples (
int, optional) – Thinposteriorto this many draws first (seethin_draws());Noneuses every draw.batch_size (
int, optional) – Maximum posterior draws (per chain) per predictive pass;Noneruns a single pass (seeforecast()).random_seed (
intornumpy.random.Generator, optional) – Seed for thinning and predictive sampling.progressbar (
bool, defaultFalse) – Show the sampling progress bar.
- Returns:
xarray.DataTreeorarviz.InferenceData– Result ofpm.sample_posterior_predictive(a DataTree with current PyMC/ArviZ, InferenceData with older releases), with aposterior_predictivegroup holding"obs", plus"mu"and"expected_observation"when the model registers them.- Raises:
pymc_forecast.exceptions.AlignmentError – If
dataorcovariatescannot be normalized or do not align.pymc_forecast.exceptions.HorizonError – If the model body does not register
"obs".ValueError – If
num_samplesorbatch_sizeis not positive.TypeError – If
posteriorhas noposteriorgroup.
- pymc_forecast.prediction.prediction_samples(result)[source]#
Extract the draw-level predictive samples from a prediction result.
Accepts any result shape the predictive drivers produce — an
xarray.DataTree/arviz.InferenceDatawith apredictionsgroup (fromforecast()) or aposterior_predictivegroup (frompredict_in_sample()) — or a bareDataset(returned unchanged), and returns the samples as anxarray.Datasetwhose variables retain the fullchain/drawdims. Point summaries are the caller’s choice, e.g.prediction_samples(result)["forecast"].mean(("chain", "draw")).- Parameters:
result (
xarray.Dataset,xarray.DataTreeorarviz.InferenceData) – A prediction result;predictionsis looked up beforeposterior_predictive.- Returns:
xarray.Dataset– The draw-level predictive samples.- Raises:
TypeError – If
resultcarries none of the predictive groups.
- pymc_forecast.prediction.thin_draws(posterior, num_samples, random_seed=None)[source]#
Subsample a posterior to
num_samplesdraws (chain-flattened).Draws are selected uniformly without replacement from the flattened
(chain, draw)axes (with replacement only if more draws are requested than exist). The result is a posteriorDatasetwithchain=1, directly consumable bypm.sample_posterior_predictive.- Parameters:
posterior (
xarray.Dataset,xarray.DataTreeorarviz.InferenceData) – A posterior Dataset or any object with aposteriorgroup (seeposterior_dataset()), withchainanddrawdims.num_samples (
int) – Number of draws to keep; must be positive.random_seed (
intornumpy.random.Generator, optional) – Seed for the draw selection (passed tonumpy.random.default_rng).
- Returns:
xarray.Dataset– Posterior with dims(chain, draw, ...),chaincoord[0]anddrawcoord0 .. num_samples - 1.- Raises:
ValueError – If
num_samplesis not positive.TypeError – If
posteriorhas noposteriorgroup.