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:
objectA completed fit.
Variational results carry
approxandlossesand keepidata=None; the result is frozen and never filled in, so passdraw_posterior(result, n)(a posteriorDataset) toforecast. MCMC and Pathfinder setidata, which can also be passed toforecastdirectly.methodis"mcmc","pathfinder", or the VI method passed tofit_vi()(a name or an inference object).Each parameter is available as an attribute of the same name.
- Parameters:
idata (
xarray.DataTreeorarviz.InferenceDataorNone) – Output ofpm.sample(MCMC) orpymc_extras.fit_pathfinder(Pathfinder) with aposteriorgroup: a DataTree with current PyMC/ArviZ, InferenceData with older releases.Nonefor VI.approx (
pymc.variational.ApproximationorNone) – The fitted variational approximation for VI;Noneotherwise.losses (
numpy.ndarrayorNone) – Loss history (approx.hist) for VI: one value per step for ADVI and full-rank ADVI, empty for"svgd"/"asvgd"(no loss is recorded);Noneotherwise.method (
strorpymc.variational.Inference) –"mcmc","pathfinder", or themethodargument offit_vi()as passed.
- pymc_forecast.fit.draw_posterior(result, num_samples, random_seed=None, *, batch_size=None)[source]#
Draw or thin
num_samplesposterior samples from aFitResult.Variational results are sampled from the approximation, optionally in host-side chunks of
batch_size. MCMC and Pathfinder results are thinned once fromidata.posterior.- Parameters:
result (
FitResult) – A result offit_vi(),fit_mcmc()orfit_pathfinder().num_samples (
int) – Number of posterior draws to return.random_seed (
intornumpy.random.Generator, optional) – Seed for sampling the approximation or thinningidata.batch_size (
int, optional) – For variational results, draw at most this many samples at once and concatenate the chunks;Nonedraws all at once. Ignored (but still validated) for MCMC and Pathfinder results.
- Returns:
xarray.Dataset– Posterior samples with a singlechainandnum_samplesdraws.- Raises:
ValueError – If
batch_sizeis not positive, ornum_samplesis 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-builtmodel) with MCMC.- Parameters:
model_fn (
callableorpymc_forecast.model.ForecastingModel) – Model body called asmodel_fn(covariates, data); it must registerobs(normally viapredict()). Ignored whenmodelis given.data (
xarray.DataArray,pandas.Series,pandas.DataFrameorarray_like, optional) – Observed training series, normalized withas_dataarray()("time"first; 2-D input gets a"series"dim). Required unlessmodelis given.covariates (
xarray.DataArray,pandas.Series,pandas.DataFrameorarray_like, optional) – Covariates on the same"time"coordinate asdata(normalized withas_dataarray; 2-D input gets a"covariate"dim). Rows past the training window are dropped.Nonemeans no covariates.draws (
int, default1000) – Posterior draws per chain, forwarded topm.sample.tune (
int, default1000) – Tuning steps per chain, forwarded topm.sample.chains (
int, default2) – Number of chains, forwarded topm.sample.nuts_sampler (
{"pymc", "nutpie", "numpyro", "blackjax"}, default"pymc") – NUTS implementation, forwarded topm.sample; non-PyMC samplers need their optional package.random_seed (
intornumpy.random.Generator, optional) – Seed forwarded topm.sample.progressbar (
bool, optional) – Show the sampling progress bar;Nonemeans off. May instead be given as asample_kwargskey, but not both.sample_kwargs (
mapping, optional) – Extra keyword arguments forwarded topm.sample.model (
pymc.Model, optional) – An already-built training-window model to sample instead of building one frommodel_fn,dataandcovariates.
- Returns:
FitResult– Result withidataset andmethod="mcmc".- Raises:
ValueError – If
progressbaris given both directly and insample_kwargs.pymc_forecast.exceptions.HorizonError – If
modelhas forecast-horizon variables, or the built model does not registerobs.pymc_forecast.exceptions.AlignmentError – If
data/covariatescannot be normalized or do not align.
- 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-builtmodel) with Pathfinder.- Parameters:
model_fn (
callableorpymc_forecast.model.ForecastingModel) – Model body called asmodel_fn(covariates, data); it must registerobs(normally viapredict()). Ignored whenmodelis given.data (
xarray.DataArray,pandas.Series,pandas.DataFrameorarray_like, optional) – Observed training series, normalized withas_dataarray()("time"first; 2-D input gets a"series"dim). Required unlessmodelis given.covariates (
xarray.DataArray,pandas.Series,pandas.DataFrameorarray_like, optional) – Covariates on the same"time"coordinate asdata(normalized withas_dataarray; 2-D input gets a"covariate"dim). Rows past the training window are dropped.Nonemeans no covariates.random_seed (
int, optional) – Seed forwarded topymc_extras.fit_pathfinder.progressbar (
bool, optional) – Show the progress bar;Nonemeans off. May instead be given as apathfinder_kwargskey, but not both.pathfinder_kwargs (
mapping, optional) – Extra keyword arguments forwarded topymc_extras.fit_pathfinder.model (
pymc.Model, optional) – An already-built training-window model to fit instead of building one frommodel_fn,dataandcovariates.
- Returns:
FitResult– Result withidataset andmethod="pathfinder".- Raises:
pymc_forecast.exceptions.OptionalDependencyError – If pymc-extras is not installed.
ValueError – If
progressbaris given both directly and inpathfinder_kwargs.pymc_forecast.exceptions.HorizonError – If
modelhas forecast-horizon variables, or the built model does not registerobs.pymc_forecast.exceptions.AlignmentError – If
data/covariatescannot be normalized or do not align.
- 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-builtmodel) with variational inference.- Parameters:
model_fn (
callableorpymc_forecast.model.ForecastingModel) – Model body called asmodel_fn(covariates, data); it must registerobs(normally viapredict()). Ignored whenmodelis given.data (
xarray.DataArray,pandas.Series,pandas.DataFrameorarray_like, optional) – Observed training series, normalized withas_dataarray()("time"first; 2-D input gets a"series"dim). Required unlessmodelis given.covariates (
xarray.DataArray,pandas.Series,pandas.DataFrameorarray_like, optional) – Covariates on the same"time"coordinate asdata(normalized withas_dataarray; 2-D input gets a"covariate"dim). Rows past the training window are dropped.Nonemeans no covariates.method (
strorpymc.variational.Inference, default"advi") – Forwarded topm.fit(e.g."advi"or"fullrank_advi", or an inference object, which fits the model it was built on and ignoresrandom_seed). The JAX backend accepts only"advi".optimizer (
callableorfloat, optional) –Noneuses Adam with learning rate 0.01; a positive number is an Adam learning rate; a callable is passed topm.fitasobj_optimizer(PyTensor backend only).backend (
{"pytensor", "jax"}, optional) –Noneor"pytensor"runspm.fit;"jax"runspymc_forecast.jax_backend.fit_advi_jax.num_steps (
int, default10_000) – Number of optimization steps.random_seed (
int, optional) – Seed for the fit.progressbar (
bool, optional) – Show the fit progress bar;Nonemeans off. May instead be given as afit_kwargskey, but not both. Ignored by the JAX backend.fit_kwargs (
mapping, optional) – Extra keyword arguments forwarded topm.fit. Not supported withbackend="jax".model (
pymc.Model, optional) – An already-built training-window model to fit instead of building one frommodel_fn,dataandcovariates.
- Returns:
FitResult– Result withapproxandlossesset andidata=None.- Raises:
pymc_forecast.exceptions.MethodResolutionError – If
backend,optimizer,fit_kwargsormethodcannot be resolved (unknown backend or VI method name, non-positive learning rate, unsupported optimizer, or a JAX backend with a method other than"advi", a non-numeric optimizer, orfit_kwargs).ValueError – If
progressbaris given both directly and infit_kwargs, ornum_stepsis not positive withbackend="jax".pymc_forecast.exceptions.HorizonError – If
modelhas forecast-horizon variables, or the built model does not registerobs.pymc_forecast.exceptions.AlignmentError – If
data/covariatescannot be normalized or do not align.pymc_forecast.exceptions.OptionalDependencyError – If
backend="jax"and JAX is not installed.
- 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.